# Clean Env
# ==========
rm(list = ls())

# Libraries
# ==========
library("gnumeric")
library("patchwork")
library("dplyr")
library("reshape2")

# Viz focus
library("ggplot2")
library("ggstream")
library("ggpubr")
library("ggpol")
library("cowplot")
library("ggstatsplot")

# CI
library("Rmisc")

# Survival
library("survival")
library("survminer")

# Tables
library("gtsummary")
library("flextable")

# Odd ratios
library("epitools")

# Generic stats
library("statsExpressions")

# ==========
# =====================================================================
#  FIGURE 1
#    Penetrance and predictivity of pathology
# =====================================================================
# ==========
# Panel TOP - Neuropath + in/vivo bk
# ==========
## Neuropath
rm(list = ls())
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

# APOE-4/4
apoe44 <- subset(naccdb, APOE == "4-4"  & ADNC != "-4")
apoe44$AGE_round <- round(apoe44$NACCAGEDEATH)

tostream44 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream44)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe44$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream44[posdf,"AGE"] <- cage
    tostream44[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe44$ADNC == thrs[idx]  &  apoe44$AGE_round == cage)
    tostream44[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream44$PATH <- factor(tostream44$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path44 <- ggplot(tostream44, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +   
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='(A) ADNC pathology', 
       subtitle='APOE-4/4') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# APOE-3/3
apoe33 <- subset(naccdb, APOE == "3-3"  & ADNC != "-4")
apoe33$AGE_round <- round(apoe33$NACCAGEDEATH)

tostream33 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream33)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe33$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream33[posdf,"AGE"] <- cage
    tostream33[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe33$ADNC == thrs[idx]  &  apoe33$AGE_round == cage)
    tostream33[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream33$PATH <- factor(tostream33$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path33 <- ggplot(tostream33, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE-3/3') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffneuropath <- ggarrange(path44,path33,
                        ncol=2, nrow=1,
                        common.legend = TRUE, legend = "bottom")
ffneuropath

## 5-year interval stats a44 vs a33
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))


markers = c("PET_Centiloid","CSF_AB42_Elecsys","Plasma_pTau_Simoa","CSF_pTau_Elecsys")
for (cmarker in markers){
  for (cage in seq(55,85,5))
  {
    tmp <- subset(wholedf, (APOE=="3-3"| APOE=="4-4") & !is.na(wholedf[,cmarker]) )
    tmp <- subset(tmp,Age>cage-5 & Age<cage+5)
    tmp$cbk <- tmp[,cmarker]
  
    p <- ggbetweenstats(tmp, x=APOE, y=cbk,
                        type = "np",
                        title = paste0("Bk>=:",cmarker))
    opath = "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed/stats_boxplot"
    saveimg <- paste0(opath,"/","Stats_",cmarker,"_age-",cage,"_byAPOE.png")
    ggsave(saveimg)
  }
}


sigamycsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamycsf) <- c('AGE',"pos", "BK")
sigamypet <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamypet) <- c('AGE',"pos", "BK")
sigtaucsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaucsf) <- c('AGE',"pos", "BK")
sigtaupl <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaupl) <- c('AGE',"pos", "BK")

sigamycsf[1,] = c(55,107,"CSF AB1-42")
sigamycsf[2,] = c(60,107,"CSF AB1-42")
sigamycsf[3,] = c(65,107,"CSF AB1-42")
sigamycsf[4,] = c(70,107,"CSF AB1-42")
sigamycsf[5,] = c(75,107,"CSF AB1-42")
sigamycsf[6,] = c(80,107,"CSF AB1-42")
sigamycsf[7,] = c(85,107,"CSF AB1-42")

sigamypet[1,] = c(55,113,"Centiloid")
sigamypet[2,] = c(60,113,"Centiloid")
sigamypet[3,] = c(65,113,"Centiloid")
sigamypet[4,] = c(70,113,"Centiloid")
sigamypet[5,] = c(75,113,"Centiloid")
sigamypet[6,] = c(80,113,"Centiloid")
sigamypet[7,] = c(85,113,"Centiloid")


sigtaucsf[1,] = c(60,107,"CSF pTau181")
sigtaucsf[2,] = c(65,107,"CSF pTau181")
sigtaucsf[3,] = c(70,107,"CSF pTau181")
sigtaucsf[4,] = c(75,107,"CSF pTau181")
sigtaucsf[5,] = c(80,107,"CSF pTau181")

sigtaupl[1,] = c(55,113,"Plasma pTau181")
sigtaupl[2,] = c(60,113,"Plasma pTau181")
sigtaupl[3,] = c(65,113,"Plasma pTau181")
sigtaupl[4,] = c(70,113,"Plasma pTau181")
sigtaupl[5,] = c(75,113,"Plasma pTau181")
sigtaupl[6,] = c(80,113,"Plasma pTau181")
sigtaupl[7,] = c(85,113,"Plasma pTau181")


cercle_utf =  enc2utf8('●')
tri_utf =  enc2utf8('▲')

## AT in-vivo biomarkers
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))

# amyloid
amypetdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Centiloid_pos))
amycsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_AB42_Elecsys_pos))

amyloidtable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(amyloidtable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subamypetdf <- subset(amypetdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subamycsfdf <- subset(amycsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqpet = (sum(subamypetdf$Centiloid_pos) / length(subamypetdf$Centiloid_pos))*100
    pospet = sum(subamypetdf$Centiloid_pos)
    negpet = length(subamypetdf$Centiloid_pos) - pospet
    freqcsf = (sum(subamycsfdf$CSF_AB42_Elecsys_pos) / length(subamycsfdf$CSF_AB42_Elecsys_pos))*100
    poscsf = sum(subamycsfdf$CSF_AB42_Elecsys_pos)
    megcsf =  length(subamycsfdf$CSF_AB42_Elecsys_pos) - poscsf
    
    amyloidtable[posdf,] <- c("Centiloid", cage, cage-2.5, cage+2.5, capoe, length(subamypetdf$Centiloid_pos),pospet,negpet,freqpet)
    posdf = posdf+1
    amyloidtable[posdf,] <- c("CSF AB1-42", cage, cage-2.5, cage+2.5, capoe, length(subamycsfdf$CSF_AB42_Elecsys_pos),poscsf,megcsf,freqcsf)
    posdf = posdf+1
  }
}

ggamyloid <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE), color=APOE, shape=BK), size=3, alpha=0.8) +
  geom_line(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("Centiloid", "CSF AB1-42")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("Centiloid", "CSF AB1-42")) +
  labs(
    title = paste0("(B) In-vivo markers"),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Amyloid markers') +
  geom_text(data=sigamypet, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigamycsf, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))



# Tau
tauplasmadf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Plasma_pTau_Simoa_pos))
taucsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_pTau_Elecsys_pos))

tautable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(tautable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subtauplasmadf <- subset(tauplasmadf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subtaucsfdf <- subset(taucsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqplasma = (sum(subtauplasmadf$Plasma_pTau_Simoa_pos) / length(subtauplasmadf$Plasma_pTau_Simoa_pos))*100
    posplasma = sum(subtauplasmadf$Plasma_pTau_Simoa_pos)
    negplasma = length(subtauplasmadf$Plasma_pTau_Simoa_pos) - posplasma
    freqcsf = (sum(subtaucsfdf$CSF_pTau_Elecsys_pos) / length(subtaucsfdf$CSF_pTau_Elecsys_pos))*100
    poscsf = sum(subtaucsfdf$CSF_pTau_Elecsys_pos)
    negcsf = length(subtaucsfdf$CSF_pTau_Elecsys_pos) - poscsf
    
    tautable[posdf,] <- c("Plasma pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtauplasmadf$Plasma_pTau_Simoa_pos), posplasma, negplasma,freqplasma)
    posdf = posdf+1
    tautable[posdf,] <- c("CSF pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtaucsfdf$CSF_pTau_Elecsys_pos), poscsf, negcsf, freqcsf)
    posdf = posdf+1
  }
}

ggtau <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK), color=as.factor(APOE), shape=BK), size=3, alpha=0.8, ) +
  geom_line(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("CSF pTau181", "Pl pTau181")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("CSF pTau181", "Pl pTau181")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Tau markers') +
  geom_text(data=sigtaucsf, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigtaupl, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw()+
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffinvivo <- ggarrange(ggamyloid, ggtau,
                      ncol=2, nrow=1, legend="bottom")


# ==========
# Panel Bottom - Predictavility
# ==========
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 8, nrow = 0))
colnames(onsetspan) <- c("GROUP", "MEAN", "lowSD", "hiSD", "lowPI", "hiPI", "PIrange","METRIC")

posdf = 1
for (cgroup in c("4-4","3-3")){
  ## Symptoms onset
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999)
  currage <- tmpdf[tmpdf$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowSD'] <- avg_symp - 2*sd_symp
  onsetspan[posdf, 'hiSD'] <- avg_symp + 2*sd_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_SYMPT"
  posdf = posdf + 1  # Update iter
  
  ## Age of MCI onset
  tmpdf <- subset(adnc, MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "MCIONSETAGE"]
  avg_mci <- mean(currage)
  sd_mci <- sd(currage)
  pi_mci <- sd_mci * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_mci
  onsetspan[posdf, 'lowSD'] <- avg_mci - 2*sd_mci
  onsetspan[posdf, 'hiSD'] <- avg_mci + 2*sd_mci
  onsetspan[posdf, 'lowPI'] <- avg_mci - pi_mci
  onsetspan[posdf, 'hiPI'] <- avg_mci + pi_mci
  onsetspan[posdf, 'PIrange'] <- round(2* pi_mci, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_MCI"
  posdf = posdf + 1  # Update iter
  
  
  ## Age of Dementia onset
  # ##########################
  # OJO !
  # NEED TO EXCLUDE THOSE THAT WERE NOT MCI BEFORE (!)
  # ##########################
  tmpdf <- subset(adnc, DEMENTONSETAGE != 0 &  MCIONSETAGE != 0 )
  currage <- tmpdf[tmpdf$APOE == cgroup, "DEMENTONSETAGE"]
  avg_dement <- mean(currage)
  sd_dement <- sd(currage)
  pi_dement <- sd_dement * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_dement
  onsetspan[posdf, 'lowSD'] <- avg_dement - 2*sd_dement
  onsetspan[posdf, 'hiSD'] <- avg_dement + 2*sd_dement
  onsetspan[posdf, 'lowPI'] <- avg_dement - pi_dement
  onsetspan[posdf, 'hiPI'] <- avg_dement + pi_dement
  onsetspan[posdf, 'PIrange'] <- round(2* pi_dement, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEMENT"
  posdf = posdf + 1  # Update iter
  
  ## Age of death
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999 & DEMENTONSETAGE != 0 & MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "NACCAGEDEATH"]
  unique(currage)
  avg_death <- mean(currage)
  sd_death <- sd(currage)
  pi_death <- sd_death * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_death
  onsetspan[posdf, 'lowSD'] <- avg_death - 2*sd_death
  onsetspan[posdf, 'hiSD'] <- avg_death + 2*sd_death
  onsetspan[posdf, 'lowPI'] <- avg_death - pi_death
  onsetspan[posdf, 'hiPI'] <- avg_death + pi_death
  onsetspan[posdf, 'PIrange'] <- round(2* pi_death, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEATH"
  posdf = posdf + 1  # Update iter
  
}

onsetspan$METRIC <- factor(onsetspan$METRIC,
                           levels=c("AGE_SYMPT","AGE_MCI","AGE_DEMENT","AGE_DEATH"))
onsetspan$GROUP <- factor(onsetspan$GROUP,
                          levels=c("4-4","3-3"))

ggpred <- ggplot(onsetspan, aes(x=GROUP, y=MEAN, ymin=lowSD, ymax=hiSD, linetype=METRIC, col=GROUP)) + 
  geom_linerange(position = position_dodge(width = 0.6),
                 linewidth=1, 
                 show.legend=F) +
  geom_linerange(inherit.aes = FALSE,     # Only to define correctly the legend
                 data=onsetspan,         # if not, lines goes vertical...
                 aes(x=GROUP, y=0,xmin=1,xmax=1,linetype=METRIC, col=GROUP), 
                 show.legend=T) +
  ylim(48.5,107) +                         # Remove the zeros from the fake 
  theme_bw() + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_linetype_manual(values=c("solid","longdash","dotdash","dotted"),
                        name="",
                        labels = c("Symptoms Onset", "MCI onset", "AD dementia onset", "Death")) +
  geom_point(aes(x=GROUP, y=MEAN, col=GROUP),
             position = position_dodge(width = 0.6),
             size=3,
             show.legend = F) + 
  labs(
    title = "(C) Age of Onset",
    x = "Groups",
    y = "Age") + 
    theme(axis.text=element_text(size=15),
          axis.title=element_text(size=15),
          legend.text=element_text(size=15),
          plot.title=element_text(size=20),
          plot.subtitle=element_text(size=15),
          legend.title=element_text(size=15),
          axis.text.x = element_blank())+ 
  xlab("")
ggpred


# PI range value
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4" &  DECAGE != 888  &  DECAGE != 999 &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 6, nrow = 0))
colnames(onsetspan) <- c("GROUP","IDX", "MEAN", "lowPI", "hiPI", "PIrange")

posdf = 1
for (cgroup in c("3-3","4-4")){
  ## Symptoms onset
  currage <- adnc[adnc$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'IDX'] <- posdf
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  posdf = posdf + 1  # Update iter
}

onsetspan[posdf, 'GROUP'] <- "DS"
onsetspan[posdf, 'IDX'] <- 3
onsetspan[posdf, 'MEAN'] <- 53
onsetspan[posdf, 'lowPI'] <- 37
onsetspan[posdf, 'hiPI'] <- 69
onsetspan[posdf, 'PIrange'] <- 32

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN1-E280A"
onsetspan[posdf, 'IDX'] <- 4
onsetspan[posdf, 'MEAN'] <- 38
onsetspan[posdf, 'lowPI'] <- 21.5
onsetspan[posdf, 'hiPI'] <- 54.5
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "APP-V717I"
onsetspan[posdf, 'IDX'] <- 5
onsetspan[posdf, 'MEAN'] <- 50.2
onsetspan[posdf, 'lowPI'] <- 33.4
onsetspan[posdf, 'hiPI'] <- 67.1
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN2-N141I"
onsetspan[posdf, 'IDX'] <- 6
onsetspan[posdf, 'MEAN'] <- 54.27
onsetspan[posdf, 'lowPI'] <- 39.6
onsetspan[posdf, 'hiPI'] <- 68.8
onsetspan[posdf, 'PIrange'] <- 29.24

onsetspan$GROUP <- factor(onsetspan$GROUP, levels=c("DS","PSEN1-E280A","APP-V717I","PSEN2-N141I","4-4","3-3" ))

ggpirange <- ggplot(onsetspan, aes(x=GROUP, y=PIrange, color=GROUP)) +
  geom_point(size = 7) + 
  geom_pointrange(data=onsetspan,aes(ymin = 30, ymax = PIrange), size=1.2) +
  scale_color_manual(values=c("#1b7be9","#0004e9","#008000","#800080","#bf080c","#bf820c","#04820c","#8949c5"),
                     labels = c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I","APOE-4/4", "APOE-3/3"),
                     name="") + 
  scale_x_discrete(labels= c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I", "APOE-4/4", "APOE-3/3")) +
  theme_bw() + 
  labs(
    title = "(E)",
    subtitle = "95% Prediction intervals",
    x = "Groups",
    y = "PI range") + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15),
        axis.text.x = element_blank())+
  xlab("")
ggpirange


# PI range horitzontal
gghoriz <- ggplot(onsetspan, aes(x=MEAN, y=GROUP, colour=GROUP)) + 
  geom_linerange(aes(xmin = lowPI, xmax = hiPI),
                 linewidth=3, 
                 show.legend=F) +
  xlim(20,98) +
  scale_color_manual(values=c("#1b7be9","#0004e9","#bf820c","#800080","#bf080c","#04820c","#04820c","#04820c"),
                     labels = c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I","APOE4-Homozygotes", "APOE-3/3"),
                     name="") +
  scale_y_discrete(labels= c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I", "APOE-4/4", "APOE-3/3")) +
  #scale_y_discrete(limits=rev) +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))+
  labs(
    title = "(D) 95% Prediction intervals") + 
  xlab("Age") +
  ylab("")
gghoriz


## Merge three panels predictivity
ffbottom <- ggarrange(ggpred, gghoriz,
                      ncol=2, nrow=1)
ffbottom


# ==========
# Merge Figure 1 v2
# ==========
ffmerge <- ggarrange(ffneuropath, ffinvivo, ffbottom,
                     ncol=1, nrow=3, heights = c(0.3,0.4,0.3))
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig1_penetrance_predictivity_v2.pdf")
#ggexport(ffmerge, filename = saveimg, width=20,height=12,pointsize = 55, device="cairo_pdf", params = list(family = "Arial Unicode MS"))
# use the GUI using cairo_pdf. If not, the circle and triangle wont export correctly

# ==========
# =====================================================================
#  FIGURE 2
#    K-M of neuropath data age symptoms and age death
# =====================================================================
# ==========
rm(list = ls())
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  DECAGE != 999)
adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE_AD <- adnc$APOE

apoe44ad <- subset(adnc, APOE == "4-4"  & (ADNC == "Intermediate-ADNC" | ADNC == "High-ADNC" ))
apoe44ad$APOE_AD <- "4-4_AD"

apoe34ad <- subset(adnc, APOE == "3-4"  & (ADNC == "Intermediate-ADNC" | ADNC == "High-ADNC" ))
apoe34ad$APOE_AD <- "3-4_AD"
apoe34noad <- subset(adnc, APOE == "3-4"  & ADNC != "Intermediate-ADNC" & ADNC != "High-ADNC" )
apoe34noad$APOE_AD <- "3-4_no-AD"

apoe33ad <- subset(adnc, APOE == "3-3"  & (ADNC == "Intermediate-ADNC" | ADNC == "High-ADNC" ))
apoe33ad$APOE_AD <- "3-3_AD"
apoe33noad <- subset(adnc, APOE == "3-3"  & ADNC != "Intermediate-ADNC" & ADNC != "High-ADNC" )
apoe33noad$APOE_AD <- "3-3_no-AD"

survdf <- rbind(apoe44ad,
                apoe34noad,apoe34ad,
                apoe33noad,apoe33ad)
survdf$APOE_AD <- factor(survdf$APOE_AD,
                         levels=c("3-4_AD","3-4_no-AD",
                                  "3-3_AD","3-3_no-AD",
                                  "4-4_AD"))

## Prepare event-based on symptoms onset
survdf$SYMPTOMS_thr <- 0
survdf["SYMPTOMS_thr"][survdf["NACCALZD"] == 1] = 1

## Run K-M age symptoms onset
km <- survfit(Surv(DECAGE, SYMPTOMS_thr) ~ APOE_AD, data=survdf)

## Plot results
ggsurvsymp <- ggsurvplot(km, data = survdf,
                     conf.int = TRUE,
                     palette = c("#ff9501","#ff9501",
                                 "#007701","#007701",
                                 "#9e0000"),
                     linetype = c("solid","dotdash",
                                  "solid","dotdash",
                                  "solid"),
                     surv.median.line = "hv",
                     risk.table = FALSE,              # Add risk table
                     cumevents = FALSE,
                     break.time.by = 5,
                     xlim=c(50,90),
                     legend.title="",
                     legend.labs = c("APOE-3/4 AD","APOE-3/4 no-AD",
                                     "APOE-3/3 AD","APOE-3/3 no-AD",
                                     "APOE-4/4 AD"))
ggkmsymp <- ggsurvsymp$plot +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))+
  labs(
    title = "Survival analysis (K-M)",
    subtitle = "Age of Symptoms onset") + 
  xlab("Age") +
  ylab("Survival Probability")

## Run K-M age symptoms onset
km <- survfit(Surv(NACCAGEDEATH, SYMPTOMS_thr) ~ APOE_AD, data=survdf)

## Plot results
ggsurvdeath <- ggsurvplot(km, data = survdf,
                     conf.int = TRUE,
                     palette = c("#ff9501","#ff9501",
                                 "#007701","#007701",
                                 "#9e0000"),
                     linetype = c("solid","dotdash",
                                  "solid","dotdash",
                                  "solid"),
                     surv.median.line = "hv",
                     risk.table = FALSE,              # Add risk table
                     cumevents = FALSE,
                     break.time.by = 5,
                     xlim=c(55,110),
                     legend.title="",
                     legend.labs = c("APOE-3/4 AD","APOE-3/4 no-AD",
                                     "APOE-3/3 AD","APOE-3/3 no-AD",
                                     "APOE-4/4 AD"))
ggkmdeath <- ggsurvdeath$plot +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))+
  labs(
    title = "",
    subtitle = "Age of Death") + 
  xlab("Age") +
  ylab("Survival Probability")

# ==========
# Merge KM Pannels
# ==========
ffkm <- ggarrange(ggkmsymp, ggkmdeath,
                  ncol=2, nrow=1,
                  common.legend = TRUE, legend = "bottom")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig2.pdf")
ggexport(ffkm, filename = saveimg, width=20, height=10, pointsize = 44)

# ==========
# =====================================================================
#  FIGURE 3
#    In-vivo biomarker LOESS with age
# =====================================================================
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 2500] = 2500

ggcsfab <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 2500) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(A) Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


# CSF pTau
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 50] = 50

ggcsfptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 50) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(B) Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=18),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Hippocampus volume
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 0.0065] = 0.0065
plotdf$cbk[plotdf$cbk < 0.0027] = 0.0027

gghippo <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.2, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(C) Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=18),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Centiloid
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"PET_Centiloid"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 120] = 120

ggcentiloid <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.3, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  ylim(-30,120)+
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Plasma pTau181
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 40] = 40

ggplasmaptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 40) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=18),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Plasma NfL
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Plasma_NfL"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit


# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 70] = 70

ggplasmanfl <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 70) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=18),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# ==========
# Merge Biomarkers Pannels
# ==========
ffbk <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggplasmanfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig2.pdf")
ggexport(ffbk, filename = saveimg, width=25, height=15, pointsize = 44)

# ==========
# =====================================================================
#  FIGURE 4
#    Biomarkers ADAD model
# =====================================================================
# ==========
modeldat <- subset(wholedf, !is.na(Age))
allbk <- c("CSF_AB42_Elecsys","PET_Centiloid",
           "CSF_pTau_Elecsys","Plasma_pTau_Simoa",
           "Hippo_normalized_icv","Plasma_NfL")

max_x <- max(modeldat$Age)
min_x <- min(modeldat$Age)
modelref <- expand.grid(Age = seq(min_x,max_x,by=0.1))
model44 <- expand.grid(Age = seq(min_x,max_x,by=0.1))
model34 <- expand.grid(Age = seq(min_x,max_x,by=0.1))

for (cbk in allbk){
  # Biomarker subset
  modeldat$marker <- modeldat[[cbk]]
  modeldat = subset(modeldat, !is.na(marker))
  refset = subset(modeldat, APOE == "3-3"  &  DX == "HC")
  apoe44 = subset(modeldat, APOE == "4-4")
  apoe34 = subset(modeldat, APOE == "3-4")
  
  # Loess fit
  family_loess <- "symmetric"
  reffit <- loess(marker ~ Age, data = refset, 
                  degree = 1, family = family_loess)
  apoe44fit <- loess(marker ~ Age, data = apoe44, 
                     degree = 1, family = family_loess)
  apoe34fit <- loess(marker ~ Age, data = apoe34, 
                     degree = 1, family = family_loess)
  
  # Loess predict
  refpredict <- predict(reffit, modelref, se=TRUE)
  apoe44predict <- predict(apoe44fit, model44, se=TRUE)
  apoe34predict <- predict(apoe34fit, model34, se=TRUE)
  
  # Alloc diff between reference and apoe-X/4
  model44[cbk] <- apoe44predict$fit - refpredict$fit
  model34[cbk] <- apoe34predict$fit - refpredict$fit
  
  # Option 1: Normalize by whole sample Std
  # Normalize by Std
  tonormapoe44 <- rbind(refset, apoe44)
  tonormapoe34 <- rbind(refset, apoe34)
  
  model44[cbk] <- model44[cbk] / sd(tonormapoe44[[cbk]])
  model34[cbk] <- model34[cbk] / sd(tonormapoe34[[cbk]])
  
  # Option 2: Normalize by loess prediction std
  # model44[cbk] <- model44[cbk] / refpredict$se.fit
  # model34[cbk] <- model34[cbk] / refpredict$se.fit
}

# Reshape for plotting
model44plot <- melt(model44)
model34plot <- melt(model34)

model44plot <- subset(model44plot, variable != "Age")
model44plot$Age <- seq(min_x,max_x,by=0.1)
model44plot$EYO <- model44plot$Age - 65
model34plot <- subset(model34plot, variable != "Age")
model34plot$Age <- seq(min_x,max_x,by=0.1)
model34plot$EYO <- model34plot$Age - 70

model44plot <- subset(model44plot, !is.na(value))
model34plot <- subset(model44plot, !is.na(value))

model44plot$variable <- factor(model44plot$variable, 
                               levels = c("CSF_AB42_Elecsys", "PET_Centiloid", "CSF_pTau_Elecsys",
                                          "Plasma_pTau_Simoa","Hippo_normalized_icv","Plasma_NfL"))
model34plot$variable <- factor(model34plot$variable, 
                               levels = c("CSF_AB42_Elecsys", "PET_Centiloid", "CSF_pTau_Elecsys",
                                          "Plasma_pTau_Simoa","Hippo_normalized_icv","Plasma_NfL"))
# Plot
ggapoe44<- ggplot(model44plot, aes(x=EYO, y=value, color=variable)) + 
  geom_line(linewidth=1, alpha =0.9) + 
  geom_hline(yintercept = 0, linetype='dashed', alpha = 0.9) +
  geom_vline(xintercept = 0, linetype='dashed', alpha = 0.9) +
  scale_color_manual(values=c("#015bff","#03018d",
                              "#037600","#03e000",
                              "#f9d564","#f75b00"),
                     name="",
                     labels = c("CSF AB1-42","amyloid-PET",
                                "CSF pTau", "Plasma pTau",
                                "Hippocampal Volume", "Plasma NfL")) +
  labs(
    title = paste0("ASDAD"),
    x = "Expected years of Onset",
    y = "Standarisd difference",
    subtitle='') +
  ylim(-2,2) + 
  scale_x_continuous(
    n.breaks = 5, limits = c(-20, 10),
    sec.axis = sec_axis(trans = ~ .x + 65,
                        name = "Age")) +
  theme_classic()
ggapoe44

outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig4_ASDAD_model.pdf")
ggexport(ggapoe44, filename = saveimg, width=15, height=10, pointsize = 24)



# ==========
# =====================================================================
#  FIGURE 5
#    Amyloid % andTau-PET in AD.
# =====================================================================
# ==========
# ==========
# Panel TOP - Streamplot amyloid positivity
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))

wholedf['Centiloid_pos'] = "A_neg"
wholedf['Centiloid_pos'][wholedf['PET_Centiloid'] > 24.4  ] = "A_pos"
wholedf['Centiloid_pos'][is.na(wholedf['PET_Centiloid'])] = NA

# Dementia Subset
gwdf <- subset(wholedf,  DX == "AD" )

# Amyloid-positivity ggstream apoe44 AD-dementia
apoe4 <- subset(gwdf, APOE == "4-4"  &  !is.na(Centiloid_pos))
apoe4$AGE_round <- round(apoe4$Age)

tostream4 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream4)<- c('AGE', 'PATH', 'COUNT')

thrs = c("A_neg","A_pos")
posdf = 1
for (cage in unique(apoe4$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream4[posdf,"AGE"] <- cage
    tostream4[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe4$Centiloid_pos == thrs[idx]  &  apoe4$AGE_round == cage)
    tostream4[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}

tostream4$PATH <- factor(tostream4$PATH, 
                         levels =c("A_neg","A_pos"))

path4 <- ggplot(tostream4, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"),c(.7,.9)),
                    name="",
                    labels=c("Amyloid-", "Amyloid+")) + 
  xlim(c(55,90)) + 
  xlab("Age") +
  ylab("Percentage (%)") + 
  labs(title='(A) Percentage of Amyloid positivity in AD dementia', 
       subtitle='APOE4-Homozygotes') +
  scale_y_continuous(name = "percentage", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Amyloid-positivity ggstream apoe33 AD-dementia
apoe3 <- subset(gwdf, APOE == "3-3"  &  !is.na(Centiloid_pos))
apoe3$AGE_round <- round(apoe3$Age)

tostream3 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream3)<- c('AGE', 'PATH', 'COUNT')

thrs = c("A_neg","A_pos")
posdf = 1
for (cage in unique(apoe3$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream3[posdf,"AGE"] <- cage
    tostream3[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe3$Centiloid_pos == thrs[idx]  &  apoe3$AGE_round == cage)
    tostream3[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}

tostream3$PATH <- factor(tostream3$PATH, 
                         levels =c("A_neg","A_pos"))

path3 <- ggplot(tostream3, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"),c(.7,.9)),
                    name="",
                    labels=c("Amyloid-", "Amyloid+")) +   
  xlim(c(55,90)) + 
  xlab("Age") +
  ylab("Percentage (%)") + 
  labs(title='', 
       subtitle='APOE3-Homozygotes') +
  scale_y_continuous(name = "percentage", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ggamyloid <- ggarrange(path4, path3,
                       ncol=2, nrow=1,
                       common.legend = TRUE, legend = "right")


# ==========
# Panel Middle - Bk by age in Ab+ symptomatic
# ==========
# Dementia Subset
gwdf <- subset(wholedf,  DX == "AD" )

# Amyloid Centiloid by age

gwdf$cbk <- gwdf[,"PET_Centiloid"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggcentiloidAD <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact), show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  labs(title='(B) Biomarkers in AD amyloid+') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("Centiloid") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggcentiloidAD, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA,
               show.legend = FALSE) +
  theme(legend.position="none") + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3"))

# merge main and marginal
ggcentiloidAD <- insert_yaxis_grob(ggcentiloidAD, ydens, grid::unit(.2, "null"), position = "right")

# tau-PET Braak 3-4 by age
gwdf$cbk <- gwdf[,"PET_tau_Bk34"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggtaupetAD <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact), show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("tau-PET Braak 3-4") +
  theme_bw()+
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggtaupetAD, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  theme(legend.position="none") + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3"))

# merge main and marginal
ggtaupetAD <- insert_yaxis_grob(ggtaupetAD, ydens, grid::unit(.2, "null"), position = "right")


# csf ptau181
gwdf$cbk <- gwdf[,"CSF_pTau_Elecsys"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggcsftauAD <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact), show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  labs(title='') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("CSF pTau181 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggcsftauAD, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  theme(legend.position="none") + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/3"))

# merge main and marginal
ggcsftauAD <- insert_yaxis_grob(ggcsftauAD, ydens, grid::unit(.2, "null"), position = "right")

# plasma NfL
gwdf$cbk <- gwdf[,"Plasma_NfL"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggplasmanflAD <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  labs(title='') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("Plasma NfL (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggplasmanflAD, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3"))

# merge main and marginal
ggplasmanflAD <- insert_yaxis_grob(ggplasmanflAD, ydens, grid::unit(.2, "null"), position = "right")


# Merge graphs
ggbk <- ggarrange(ggdraw(ggcentiloidAD), ggdraw(ggcsftauAD), ggdraw(ggplasmanflAD),
                  ncol=3, nrow=1,
                  widths = c(0.31, 0.31, 0.38),
                  common.legend = TRUE, legend = "right")

# ==========
# Panel Bottom - tau-PET by age in Ab+ symptomatic
# ==========
gwdf$cbk <- gwdf[,"PET_tau_Bk12"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggtaupetAD12 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact), show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  labs(title='(B) tau-PET in AD amyloid+') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("Braak 1-2") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggtaupetAD12, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  theme(legend.position="none") + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3"))

# merge main and marginal
ggtaupetAD12 <- insert_yaxis_grob(ggtaupetAD12, ydens, grid::unit(.2, "null"), position = "right")

# tau-PET Braak 3-4 by age in AD
gwdf$cbk <- gwdf[,"PET_tau_Bk34"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggtaupetAD34 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact), show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  labs(title='') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("Braak 3-4") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggtaupetAD34, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  theme(legend.position="none") + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/3"))

# merge main and marginal
ggtaupetAD34 <- insert_yaxis_grob(ggtaupetAD34, ydens, grid::unit(.2, "null"), position = "right")

# tau-PET Braak 5-6 by age in AD
gwdf$cbk <- gwdf[,"PET_tau_Bk56"]
sample44 <- subset(gwdf, APOE == "4-4"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))
sample33 <- subset(gwdf, APOE == "3-3"  &  Centiloid_pos == "A_pos"  & !is.na(cbk))

# LOESS compute
family_loess <- "symmetric"
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)
# LOESS predict
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-3'))

# Scatter plot
ggtaupetAD56 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact)) + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.2, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.2, inherit.aes = FALSE) +
  #ylim(0, 70) +
  theme(legend.position="none") + 
  labs(title='') + 
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  ylab("Braak 5-6") +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Marginal boxplot
ydens <- axis_canvas(ggtaupetAD56, axis = "y")+
  geom_boxplot(data =plotdf, aes(y = cbk, color=apoe_fact),
               alpha = 0.9, size = 0.2,
               outlier.shape = NA) +
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3"))

# merge main and marginal
ggtaupetAD56 <- insert_yaxis_grob(ggtaupetAD56, ydens, grid::unit(.2, "null"), position = "right")

ggtaup <- ggarrange(ggdraw(ggtaupetAD12), ggdraw(ggtaupetAD34), ggdraw(ggtaupetAD56),
                    ncol=3, nrow=1,
                    widths = c(0.31, 0.31, 0.38),
                    common.legend = TRUE, legend = "right")


# ==========
# Merge Pannels
# ==========
ggfig4 <- ggarrange(ggamyloid,ggbk, ggtaup,
                    ncol=1, nrow=3,
                    common.legend = FALSE)

outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig5.pdf")
ggexport(ggfig4, filename = saveimg, width=15,pointsize = 24)


# ==========
# =====================================================================
#  Supplementary Figures
#    Fig1 Penetrance by SEX
# =====================================================================
# ==========
## MALE
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 1)

# APOE-4/4
apoe44 <- subset(naccdb, APOE == "4-4"  & ADNC != "-4")
apoe44$AGE_round <- round(apoe44$NACCAGEDEATH)

tostream44 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream44)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe44$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream44[posdf,"AGE"] <- cage
    tostream44[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe44$ADNC == thrs[idx]  &  apoe44$AGE_round == cage)
    tostream44[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream44$PATH <- factor(tostream44$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path44 <- ggplot(tostream44, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +   
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='(E) ADNC pathology (Male)', 
       subtitle='APOE-4/4') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# APOE-3/3
apoe33 <- subset(naccdb, APOE == "3-3"  & ADNC != "-4")
apoe33$AGE_round <- round(apoe33$NACCAGEDEATH)

tostream33 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream33)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe33$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream33[posdf,"AGE"] <- cage
    tostream33[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe33$ADNC == thrs[idx]  &  apoe33$AGE_round == cage)
    tostream33[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream33$PATH <- factor(tostream33$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path33 <- ggplot(tostream33, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE-3/3') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffneuropathmale <- ggarrange(path44,path33,
                         ncol=2, nrow=1,
                         common.legend = TRUE, legend = "bottom")


sigamycsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamycsf) <- c('AGE',"pos", "BK")
sigamypet <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamypet) <- c('AGE',"pos", "BK")
sigtaucsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaucsf) <- c('AGE',"pos", "BK")
sigtaupl <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaupl) <- c('AGE',"pos", "BK")

sigamycsf[1,] = c(55,113,"CSF AB1-42")
sigamycsf[2,] = c(60,113,"CSF AB1-42")
sigamycsf[3,] = c(65,113,"CSF AB1-42")
sigamycsf[4,] = c(70,113,"CSF AB1-42")
sigamycsf[5,] = c(75,113,"CSF AB1-42")
sigamycsf[6,] = c(80,113,"CSF AB1-42")
sigamycsf[7,] = c(85,113,"CSF AB1-42")

sigamypet[1,] = c(60,107,"Centiloid")
sigamypet[2,] = c(65,107,"Centiloid")
sigamypet[3,] = c(70,107,"Centiloid")
sigamypet[4,] = c(75,107,"Centiloid")
sigamypet[5,] = c(80,107,"Centiloid")
sigamypet[6,] = c(85,107,"Centiloid")


sigtaucsf[1,] = c(65,107,"CSF pTau181")
sigtaucsf[2,] = c(70,107,"CSF pTau181")
sigtaucsf[4,] = c(75,107,"CSF pTau181")
sigtaucsf[5,] = c(80,107,"CSF pTau181")

sigtaupl[1,] = c(60,113,"Plasma pTau181")
sigtaupl[2,] = c(65,113,"Plasma pTau181")
sigtaupl[3,] = c(70,113,"Plasma pTau181")
sigtaupl[4,] = c(75,113,"Plasma pTau181")
sigtaupl[5,] = c(80,113,"Plasma pTau181")
sigtaupl[6,] = c(85,113,"Plasma pTau181")


cercle_utf =  enc2utf8('●')
tri_utf =  enc2utf8('▲')

## AT in-vivo biomarkers
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))
wholedf <- subset(wholedf, wholedf$Sex == "Male")

# amyloid
amypetdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Centiloid_pos))
amycsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_AB42_Elecsys_pos))

amyloidtable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(amyloidtable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subamypetdf <- subset(amypetdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subamycsfdf <- subset(amycsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqpet = (sum(subamypetdf$Centiloid_pos) / length(subamypetdf$Centiloid_pos))*100
    pospet = sum(subamypetdf$Centiloid_pos)
    negpet = length(subamypetdf$Centiloid_pos) - pospet
    freqcsf = (sum(subamycsfdf$CSF_AB42_Elecsys_pos) / length(subamycsfdf$CSF_AB42_Elecsys_pos))*100
    poscsf = sum(subamycsfdf$CSF_AB42_Elecsys_pos)
    megcsf =  length(subamycsfdf$CSF_AB42_Elecsys_pos) - poscsf
    
    amyloidtable[posdf,] <- c("Centiloid", cage, cage-2.5, cage+2.5, capoe, length(subamypetdf$Centiloid_pos),pospet,negpet,freqpet)
    posdf = posdf+1
    amyloidtable[posdf,] <- c("CSF AB1-42", cage, cage-2.5, cage+2.5, capoe, length(subamycsfdf$CSF_AB42_Elecsys_pos),poscsf,megcsf,freqcsf)
    posdf = posdf+1
  }
}

ggamyloid <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE), color=APOE, shape=BK), size=3, alpha=0.8) +
  geom_line(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("Centiloid", "CSF AB1-42")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("Centiloid", "CSF AB1-42")) +
  labs(
    title = paste0("(F) In-vivo markers (Male)"),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Amyloid markers') +
  geom_text(data=sigamycsf, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigamypet, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))



# Tau
tauplasmadf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Plasma_pTau_Simoa_pos))
taucsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_pTau_Elecsys_pos))

tautable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(tautable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subtauplasmadf <- subset(tauplasmadf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subtaucsfdf <- subset(taucsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqplasma = (sum(subtauplasmadf$Plasma_pTau_Simoa_pos) / length(subtauplasmadf$Plasma_pTau_Simoa_pos))*100
    posplasma = sum(subtauplasmadf$Plasma_pTau_Simoa_pos)
    negplasma = length(subtauplasmadf$Plasma_pTau_Simoa_pos) - posplasma
    freqcsf = (sum(subtaucsfdf$CSF_pTau_Elecsys_pos) / length(subtaucsfdf$CSF_pTau_Elecsys_pos))*100
    poscsf = sum(subtaucsfdf$CSF_pTau_Elecsys_pos)
    negcsf = length(subtaucsfdf$CSF_pTau_Elecsys_pos) - poscsf
    
    tautable[posdf,] <- c("Plasma pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtauplasmadf$Plasma_pTau_Simoa_pos), posplasma, negplasma,freqplasma)
    posdf = posdf+1
    tautable[posdf,] <- c("CSF pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtaucsfdf$CSF_pTau_Elecsys_pos), poscsf, negcsf, freqcsf)
    posdf = posdf+1
  }
}

ggtau <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK), color=as.factor(APOE), shape=BK), size=3, alpha=0.8, ) +
  geom_line(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("CSF pTau181", "Pl pTau181")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("CSF pTau181", "Pl pTau181")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Tau markers') +
  geom_text(data=sigtaucsf, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigtaupl, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw()+
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffinvivomale <- ggarrange(ggamyloid, ggtau,
                      ncol=2, nrow=1, legend="bottom")

ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 1)

adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 8, nrow = 0))
colnames(onsetspan) <- c("GROUP", "MEAN", "lowSD", "hiSD", "lowPI", "hiPI", "PIrange","METRIC")

posdf = 1
for (cgroup in c("4-4","3-3")){
  ## Symptoms onset
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999)
  currage <- tmpdf[tmpdf$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowSD'] <- avg_symp - 2*sd_symp
  onsetspan[posdf, 'hiSD'] <- avg_symp + 2*sd_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_SYMPT"
  posdf = posdf + 1  # Update iter
  
  ## Age of MCI onset
  tmpdf <- subset(adnc, MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "MCIONSETAGE"]
  avg_mci <- mean(currage)
  sd_mci <- sd(currage)
  pi_mci <- sd_mci * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_mci
  onsetspan[posdf, 'lowSD'] <- avg_mci - 2*sd_mci
  onsetspan[posdf, 'hiSD'] <- avg_mci + 2*sd_mci
  onsetspan[posdf, 'lowPI'] <- avg_mci - pi_mci
  onsetspan[posdf, 'hiPI'] <- avg_mci + pi_mci
  onsetspan[posdf, 'PIrange'] <- round(2* pi_mci, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_MCI"
  posdf = posdf + 1  # Update iter
  
  
  ## Age of Dementia onset
  # ##########################
  # OJO !
  # SI NO SE EXCLUYEN LOS QUE NO ERAN MCI, EL VALOR DE DEMENTIA ES MAS BAJO
  # QUE EL VALOR DE MCI
  # ##########################
  tmpdf <- subset(adnc, DEMENTONSETAGE != 0 &  MCIONSETAGE != 0 )
  currage <- tmpdf[tmpdf$APOE == cgroup, "DEMENTONSETAGE"]
  avg_dement <- mean(currage)
  sd_dement <- sd(currage)
  pi_dement <- sd_dement * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_dement
  onsetspan[posdf, 'lowSD'] <- avg_dement - 2*sd_dement
  onsetspan[posdf, 'hiSD'] <- avg_dement + 2*sd_dement
  onsetspan[posdf, 'lowPI'] <- avg_dement - pi_dement
  onsetspan[posdf, 'hiPI'] <- avg_dement + pi_dement
  onsetspan[posdf, 'PIrange'] <- round(2* pi_dement, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEMENT"
  posdf = posdf + 1  # Update iter
  
  ## Age of death
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999 & DEMENTONSETAGE != 0 & MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "NACCAGEDEATH"]
  unique(currage)
  avg_death <- mean(currage)
  sd_death <- sd(currage)
  pi_death <- sd_death * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_death
  onsetspan[posdf, 'lowSD'] <- avg_death - 2*sd_death
  onsetspan[posdf, 'hiSD'] <- avg_death + 2*sd_death
  onsetspan[posdf, 'lowPI'] <- avg_death - pi_death
  onsetspan[posdf, 'hiPI'] <- avg_death + pi_death
  onsetspan[posdf, 'PIrange'] <- round(2* pi_death, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEATH"
  posdf = posdf + 1  # Update iter
  
}

onsetspan$METRIC <- factor(onsetspan$METRIC,
                           levels=c("AGE_SYMPT","AGE_MCI","AGE_DEMENT","AGE_DEATH"))
onsetspan$GROUP <- factor(onsetspan$GROUP,
                          levels=c("4-4","3-3"))

ggpred <- ggplot(onsetspan, aes(x=GROUP, y=MEAN, ymin=lowSD, ymax=hiSD, linetype=METRIC, col=GROUP)) + 
  geom_linerange(position = position_dodge(width = 0.6),
                 linewidth=1, 
                 show.legend=F) +
  geom_linerange(inherit.aes = FALSE,     # Only to define correctly the legend
                 data=onsetspan,         # if not, lines goes vertical...
                 aes(x=GROUP, y=0,xmin=1,xmax=1,linetype=METRIC, col=GROUP), 
                 show.legend=T) +
  ylim(47.7,107) +                         # Remove the zeros from the fake 
  theme_bw() + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_linetype_manual(values=c("solid","longdash","dotdash","dotted"),
                        name="",
                        labels = c("Symptoms Onset", "MCI onset", "AD dementia onset", "Death")) +
  geom_point(aes(x=GROUP, y=MEAN, col=GROUP),
             position = position_dodge(width = 0.6),
             size=3,
             show.legend = F) + 
  labs(
    title = "(G) Age of Onset (Male)",
    x = "Groups",
    y = "Age") + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15),
        axis.text.x = element_blank())+ 
  xlab("")
ggpred


# PI range value
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4" &  DECAGE != 888  &  DECAGE != 999 &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 6, nrow = 0))
colnames(onsetspan) <- c("GROUP","IDX", "MEAN", "lowPI", "hiPI", "PIrange")

posdf = 1
for (cgroup in c("3-3","4-4")){
  ## Symptoms onset
  currage <- adnc[adnc$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'IDX'] <- posdf
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  posdf = posdf + 1  # Update iter
}

onsetspan[posdf, 'GROUP'] <- "DS"
onsetspan[posdf, 'IDX'] <- 3
onsetspan[posdf, 'MEAN'] <- 53
onsetspan[posdf, 'lowPI'] <- 37
onsetspan[posdf, 'hiPI'] <- 69
onsetspan[posdf, 'PIrange'] <- 32

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN1-E280A"
onsetspan[posdf, 'IDX'] <- 4
onsetspan[posdf, 'MEAN'] <- 38
onsetspan[posdf, 'lowPI'] <- 21.5
onsetspan[posdf, 'hiPI'] <- 54.5
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "APP-V717I"
onsetspan[posdf, 'IDX'] <- 5
onsetspan[posdf, 'MEAN'] <- 50.2
onsetspan[posdf, 'lowPI'] <- 33.4
onsetspan[posdf, 'hiPI'] <- 67.1
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN2-N141I"
onsetspan[posdf, 'IDX'] <- 6
onsetspan[posdf, 'MEAN'] <- 54.27
onsetspan[posdf, 'lowPI'] <- 39.6
onsetspan[posdf, 'hiPI'] <- 68.8
onsetspan[posdf, 'PIrange'] <- 29.24

onsetspan$GROUP <- factor(onsetspan$GROUP, levels=c("DS","PSEN1-E280A","APP-V717I","PSEN2-N141I","4-4","3-3" ))

ggpirange <- ggplot(onsetspan, aes(x=GROUP, y=PIrange, color=GROUP)) +
  geom_point(size = 7) + 
  geom_pointrange(data=onsetspan,aes(ymin = 30, ymax = PIrange), size=1.2) +
  scale_color_manual(values=c("#1b7be9","#0004e9","#008000","#800080","#bf080c","#bf820c","#04820c","#8949c5"),
                     labels = c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I","APOE-4/4", "APOE-3/3"),
                     name="") + 
  scale_x_discrete(labels= c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I", "APOE-4/4", "APOE-3/3")) +
  theme_bw() + 
  labs(
    title = "()",
    subtitle = "95% Prediction intervals",
    x = "Groups",
    y = "PI range") + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15),
        axis.text.x = element_blank())+
  xlab("")
ggpirange


# PI range horitzontal
gghoriz <- ggplot(onsetspan, aes(x=MEAN, y=GROUP, colour=GROUP)) + 
  geom_linerange(aes(xmin = lowPI, xmax = hiPI),
                 linewidth=3, 
                 show.legend=F) +
  xlim(20,98) +
  scale_color_manual(values=c("#1b7be9","#0004e9","#bf820c","#800080","#bf080c","#04820c","#04820c","#04820c"),
                     labels = c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I","APOE4-Homozygotes", "APOE-3/3"),
                     name="") +
  scale_y_discrete(labels= c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I", "APOE-4/4", "APOE-3/3")) +
  #scale_y_discrete(limits=rev) +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))+
  labs(
    title = "(H) 95% Prediction intervals (Male)") + 
  xlab("Age") +
  ylab("")
gghoriz


ffbottommale <- ggarrange(ggpred, gghoriz,
                      ncol=2, nrow=1)

ffmergemale <- ggarrange(ffneuropathmale, ffinvivomale, ffbottommale,
                     ncol=1, nrow=3, heights = c(0.3,0.4,0.3))
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Neuropath_Bk_penetrance_predictivity_MALE.pdf")
#ggexport(ffmerge, filename = saveimg, width=20,height=12,pointsize = 55, device="cairo_pdf", params = list(family = "Arial Unicode MS"))
# use the GUI using cairo_pdf. If not, the circle and triangle wont export correctly

## Female
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 2)

# APOE-4/4
apoe44 <- subset(naccdb, APOE == "4-4"  & ADNC != "-4")
apoe44$AGE_round <- round(apoe44$NACCAGEDEATH)

tostream44 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream44)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe44$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream44[posdf,"AGE"] <- cage
    tostream44[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe44$ADNC == thrs[idx]  &  apoe44$AGE_round == cage)
    tostream44[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream44$PATH <- factor(tostream44$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path44 <- ggplot(tostream44, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +   
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='(A) ADNC pathology (Female)', 
       subtitle='APOE-4/4') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# APOE-3/3
apoe33 <- subset(naccdb, APOE == "3-3"  & ADNC != "-4")
apoe33$AGE_round <- round(apoe33$NACCAGEDEATH)

tostream33 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream33)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe33$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream33[posdf,"AGE"] <- cage
    tostream33[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe33$ADNC == thrs[idx]  &  apoe33$AGE_round == cage)
    tostream33[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream33$PATH <- factor(tostream33$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path33 <- ggplot(tostream33, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE-3/3') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffneuropathfemale <- ggarrange(path44,path33,
                             ncol=2, nrow=1,
                             common.legend = TRUE, legend = "bottom")

sigamycsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamycsf) <- c('AGE',"pos", "BK")
sigamypet <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigamypet) <- c('AGE',"pos", "BK")
sigtaucsf <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaucsf) <- c('AGE',"pos", "BK")
sigtaupl <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(sigtaupl) <- c('AGE',"pos", "BK")

sigamycsf[1,] = c(55,113,"CSF AB1-42")
sigamycsf[2,] = c(60,113,"CSF AB1-42")
sigamycsf[3,] = c(65,113,"CSF AB1-42")
sigamycsf[4,] = c(70,113,"CSF AB1-42")
sigamycsf[5,] = c(75,113,"CSF AB1-42")
sigamycsf[6,] = c(80,113,"CSF AB1-42")

sigamypet[1,] = c(60,107,"Centiloid")
sigamypet[2,] = c(65,107,"Centiloid")
sigamypet[3,] = c(70,107,"Centiloid")
sigamypet[4,] = c(75,107,"Centiloid")
sigamypet[5,] = c(80,107,"Centiloid")


sigtaucsf[1,] = c(60,107,"CSF pTau181")
sigtaucsf[2,] = c(65,107,"CSF pTau181")
sigtaucsf[3,] = c(70,107,"CSF pTau181")
sigtaucsf[4,] = c(75,107,"CSF pTau181")
sigtaucsf[5,] = c(80,107,"CSF pTau181")

sigtaupl[1,] = c(65,113,"Plasma pTau181")
sigtaupl[2,] = c(70,113,"Plasma pTau181")
sigtaupl[3,] = c(75,113,"Plasma pTau181")
sigtaupl[4,] = c(80,113,"Plasma pTau181")


cercle_utf =  enc2utf8('●')
tri_utf =  enc2utf8('▲')

## AT in-vivo biomarkers
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))
wholedf <- subset(wholedf, wholedf$Sex == "Female")

# amyloid
amypetdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Centiloid_pos))
amycsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_AB42_Elecsys_pos))

amyloidtable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(amyloidtable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subamypetdf <- subset(amypetdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subamycsfdf <- subset(amycsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqpet = (sum(subamypetdf$Centiloid_pos) / length(subamypetdf$Centiloid_pos))*100
    pospet = sum(subamypetdf$Centiloid_pos)
    negpet = length(subamypetdf$Centiloid_pos) - pospet
    freqcsf = (sum(subamycsfdf$CSF_AB42_Elecsys_pos) / length(subamycsfdf$CSF_AB42_Elecsys_pos))*100
    poscsf = sum(subamycsfdf$CSF_AB42_Elecsys_pos)
    megcsf =  length(subamycsfdf$CSF_AB42_Elecsys_pos) - poscsf
    
    amyloidtable[posdf,] <- c("Centiloid", cage, cage-2.5, cage+2.5, capoe, length(subamypetdf$Centiloid_pos),pospet,negpet,freqpet)
    posdf = posdf+1
    amyloidtable[posdf,] <- c("CSF AB1-42", cage, cage-2.5, cage+2.5, capoe, length(subamycsfdf$CSF_AB42_Elecsys_pos),poscsf,megcsf,freqcsf)
    posdf = posdf+1
  }
}

ggamyloid <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE), color=APOE, shape=BK), size=3, alpha=0.8) +
  geom_line(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("Centiloid", "CSF AB1-42")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("Centiloid", "CSF AB1-42")) +
  labs(
    title = paste0("(B) In-vivo markers (Female)"),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Amyloid markers') +
  geom_text(data=sigamycsf, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigamypet, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))



# Tau
tauplasmadf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(Plasma_pTau_Simoa_pos))
taucsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3") &  !is.na(CSF_pTau_Elecsys_pos))

tautable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(tautable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3"))
  {
    subtauplasmadf <- subset(tauplasmadf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subtaucsfdf <- subset(taucsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqplasma = (sum(subtauplasmadf$Plasma_pTau_Simoa_pos) / length(subtauplasmadf$Plasma_pTau_Simoa_pos))*100
    posplasma = sum(subtauplasmadf$Plasma_pTau_Simoa_pos)
    negplasma = length(subtauplasmadf$Plasma_pTau_Simoa_pos) - posplasma
    freqcsf = (sum(subtaucsfdf$CSF_pTau_Elecsys_pos) / length(subtaucsfdf$CSF_pTau_Elecsys_pos))*100
    poscsf = sum(subtaucsfdf$CSF_pTau_Elecsys_pos)
    negcsf = length(subtaucsfdf$CSF_pTau_Elecsys_pos) - poscsf
    
    tautable[posdf,] <- c("Plasma pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtauplasmadf$Plasma_pTau_Simoa_pos), posplasma, negplasma,freqplasma)
    posdf = posdf+1
    tautable[posdf,] <- c("CSF pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtaucsfdf$CSF_pTau_Elecsys_pos), poscsf, negcsf, freqcsf)
    posdf = posdf+1
  }
}

ggtau <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK), color=as.factor(APOE), shape=BK), size=3, alpha=0.8, ) +
  geom_line(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("CSF pTau181", "Pl pTau181")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("CSF pTau181", "Pl pTau181")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Tau markers') +
  geom_text(data=sigtaucsf, aes(y=as.double(pos), x=AGE), label=cercle_utf, size=5, show.legend=FALSE) +
  geom_text(data=sigtaupl, aes(y=as.double(pos), x=AGE), label=tri_utf, size=5, show.legend=FALSE) +
  scale_color_manual(values=c("#04820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-4/4")) +
  theme_bw()+
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffinvivofemale <- ggarrange(ggamyloid, ggtau,
                          ncol=2, nrow=1, legend="bottom")

ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 2)

adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 8, nrow = 0))
colnames(onsetspan) <- c("GROUP", "MEAN", "lowSD", "hiSD", "lowPI", "hiPI", "PIrange","METRIC")

posdf = 1
for (cgroup in c("4-4","3-3")){
  ## Symptoms onset
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999)
  currage <- tmpdf[tmpdf$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowSD'] <- avg_symp - 2*sd_symp
  onsetspan[posdf, 'hiSD'] <- avg_symp + 2*sd_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_SYMPT"
  posdf = posdf + 1  # Update iter
  
  ## Age of MCI onset
  tmpdf <- subset(adnc, MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "MCIONSETAGE"]
  avg_mci <- mean(currage)
  sd_mci <- sd(currage)
  pi_mci <- sd_mci * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_mci
  onsetspan[posdf, 'lowSD'] <- avg_mci - 2*sd_mci
  onsetspan[posdf, 'hiSD'] <- avg_mci + 2*sd_mci
  onsetspan[posdf, 'lowPI'] <- avg_mci - pi_mci
  onsetspan[posdf, 'hiPI'] <- avg_mci + pi_mci
  onsetspan[posdf, 'PIrange'] <- round(2* pi_mci, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_MCI"
  posdf = posdf + 1  # Update iter
  
  
  ## Age of Dementia onset
  # ##########################
  # OJO !
  # SI NO SE EXCLUYEN LOS QUE NO ERAN MCI, EL VALOR DE DEMENTIA ES MAS BAJO
  # QUE EL VALOR DE MCI
  # ##########################
  tmpdf <- subset(adnc, DEMENTONSETAGE != 0 &  MCIONSETAGE != 0 )
  currage <- tmpdf[tmpdf$APOE == cgroup, "DEMENTONSETAGE"]
  avg_dement <- mean(currage)
  sd_dement <- sd(currage)
  pi_dement <- sd_dement * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_dement
  onsetspan[posdf, 'lowSD'] <- avg_dement - 2*sd_dement
  onsetspan[posdf, 'hiSD'] <- avg_dement + 2*sd_dement
  onsetspan[posdf, 'lowPI'] <- avg_dement - pi_dement
  onsetspan[posdf, 'hiPI'] <- avg_dement + pi_dement
  onsetspan[posdf, 'PIrange'] <- round(2* pi_dement, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEMENT"
  posdf = posdf + 1  # Update iter
  
  ## Age of death
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999 & DEMENTONSETAGE != 0 & MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "NACCAGEDEATH"]
  unique(currage)
  avg_death <- mean(currage)
  sd_death <- sd(currage)
  pi_death <- sd_death * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_death
  onsetspan[posdf, 'lowSD'] <- avg_death - 2*sd_death
  onsetspan[posdf, 'hiSD'] <- avg_death + 2*sd_death
  onsetspan[posdf, 'lowPI'] <- avg_death - pi_death
  onsetspan[posdf, 'hiPI'] <- avg_death + pi_death
  onsetspan[posdf, 'PIrange'] <- round(2* pi_death, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEATH"
  posdf = posdf + 1  # Update iter
  
}

onsetspan$METRIC <- factor(onsetspan$METRIC,
                           levels=c("AGE_SYMPT","AGE_MCI","AGE_DEMENT","AGE_DEATH"))
onsetspan$GROUP <- factor(onsetspan$GROUP,
                          levels=c("4-4","3-3"))

ggpred <- ggplot(onsetspan, aes(x=GROUP, y=MEAN, ymin=lowSD, ymax=hiSD, linetype=METRIC, col=GROUP)) + 
  geom_linerange(position = position_dodge(width = 0.6),
                 linewidth=1, 
                 show.legend=F) +
  geom_linerange(inherit.aes = FALSE,     # Only to define correctly the legend
                 data=onsetspan,         # if not, lines goes vertical...
                 aes(x=GROUP, y=0,xmin=1,xmax=1,linetype=METRIC, col=GROUP), 
                 show.legend=T) +
  ylim(47.7,112) +                         # Remove the zeros from the fake 
  theme_bw() + 
  scale_color_manual(values=c("#bf080c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_linetype_manual(values=c("solid","longdash","dotdash","dotted"),
                        name="",
                        labels = c("Symptoms Onset", "MCI onset", "AD dementia onset", "Death")) +
  geom_point(aes(x=GROUP, y=MEAN, col=GROUP),
             position = position_dodge(width = 0.6),
             size=3,
             show.legend = F) + 
  labs(
    title = "(C) Age of Onset (Female)",
    x = "Groups",
    y = "Age") + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15),
        axis.text.x = element_blank())+ 
  xlab("")
ggpred


# PI range value
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4" &  DECAGE != 888  &  DECAGE != 999 &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 6, nrow = 0))
colnames(onsetspan) <- c("GROUP","IDX", "MEAN", "lowPI", "hiPI", "PIrange")

posdf = 1
for (cgroup in c("3-3","4-4")){
  ## Symptoms onset
  currage <- adnc[adnc$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'IDX'] <- posdf
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  posdf = posdf + 1  # Update iter
}

onsetspan[posdf, 'GROUP'] <- "DS"
onsetspan[posdf, 'IDX'] <- 3
onsetspan[posdf, 'MEAN'] <- 53
onsetspan[posdf, 'lowPI'] <- 37
onsetspan[posdf, 'hiPI'] <- 69
onsetspan[posdf, 'PIrange'] <- 32

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN1-E280A"
onsetspan[posdf, 'IDX'] <- 4
onsetspan[posdf, 'MEAN'] <- 38
onsetspan[posdf, 'lowPI'] <- 21.5
onsetspan[posdf, 'hiPI'] <- 54.5
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "APP-V717I"
onsetspan[posdf, 'IDX'] <- 5
onsetspan[posdf, 'MEAN'] <- 50.2
onsetspan[posdf, 'lowPI'] <- 33.4
onsetspan[posdf, 'hiPI'] <- 67.1
onsetspan[posdf, 'PIrange'] <- 33

posdf = posdf + 1
onsetspan[posdf, 'GROUP'] <- "PSEN2-N141I"
onsetspan[posdf, 'IDX'] <- 6
onsetspan[posdf, 'MEAN'] <- 54.27
onsetspan[posdf, 'lowPI'] <- 39.6
onsetspan[posdf, 'hiPI'] <- 68.8
onsetspan[posdf, 'PIrange'] <- 29.24

onsetspan$GROUP <- factor(onsetspan$GROUP, levels=c("DS","PSEN1-E280A","APP-V717I","PSEN2-N141I","4-4","3-3" ))


# PI range horitzontal
gghoriz <- ggplot(onsetspan, aes(x=MEAN, y=GROUP, colour=GROUP)) + 
  geom_linerange(aes(xmin = lowPI, xmax = hiPI),
                 linewidth=3, 
                 show.legend=F) +
  xlim(20,102) +
  scale_color_manual(values=c("#1b7be9","#0004e9","#bf820c","#800080","#bf080c","#04820c","#04820c","#04820c"),
                     labels = c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I","APOE4-Homozygotes", "APOE-3/3"),
                     name="") +
  scale_y_discrete(labels= c("Down Syndrome", "PSEN1-E280A", "APP-V717I","PSEN2-N141I", "APOE-4/4", "APOE-3/3")) +
  #scale_y_discrete(limits=rev) +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))+
  labs(
    title = "(D) 95% Prediction intervals (Female)") + 
  xlab("Age") +
  ylab("")
gghoriz


ffbottomfemale <- ggarrange(ggpred, gghoriz,
                          ncol=2, nrow=1)

ffmergefemale <- ggarrange(ffneuropathfemale, ffinvivofemale, ffbottomfemale,
                         ncol=1, nrow=3, heights = c(0.3,0.4,0.3))
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed"
saveimg <- paste0(outprfx,"/","Suppl_Neuropath_Bk_penetrance_predictivity_FEMALE.pdf")

# ==========
# Merge Female and Male
# ==========
ffmerge <- ggarrange(ffmergefemale, ffmergemale,
                     ncol=1, nrow=2)
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Fig1_penetrance_predictivity_v2.pdf")

# ==========
# =====================================================================
#  Supplementary Figures
#    Fig4 Biomarkers by SEX
# =====================================================================
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                        degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                            degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                            degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                        degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                            degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

ggcsfab <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit, color=APOE, linetype=Sex), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a", "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                    name="",
                    labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(A) Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

# CSF pTau
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                            degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                              degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                              degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                            degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                              degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

ggcsfptau <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a", "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                        name="",
                        labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(B) Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

## Hippocampus volume
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]

sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                            degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                              degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                              degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                            degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                              degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

gghippo <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a", "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4",  "APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                        name="",
                        labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(C) Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

# Centiloid
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"PET_Centiloid"]

sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                            degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                              degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                              degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                            degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                              degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

ggcentiloid <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a",  "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                        name="",
                        labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

## Plasma pTau181
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]

sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                            degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                              degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                              degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                            degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                              degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

ggplasmaptau <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a",  "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4",  "APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                        name="",
                        labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

## Plasma NfL
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_NfL"]

sample44male <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample44female <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample34male <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample34female <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")
sample33male <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Male")
sample33female <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX) & Sex == "Female")

sample44male$group <- "4-4 Male"
sample44female$group <- "4-4 Female"
sample34male$group <- "3-4 Male"
sample34female$group <- "3-4 Female"
sample33male$group <- "3-3 Male"
sample33female$group <- "3-3 Female"


# Loess fit
sample44male_loess <- loess(cbk ~ Age, data = sample44male, 
                            degree = 1, family = family_loess)
sample44female_loess <- loess(cbk ~ Age, data = sample44female, 
                              degree = 1, family = family_loess)
sample34male_loess <- loess(cbk ~ Age, data = sample34male, 
                            degree=1, family = family_loess)
sample34female_loess <- loess(cbk ~ Age, data = sample34female, 
                              degree=1, family = family_loess)
sample33male_loess <- loess(cbk ~ Age, data = sample33male, 
                            degree=1, family = family_loess)
sample33female_loess <- loess(cbk ~ Age, data = sample33female, 
                              degree=1, family = family_loess)

# Predit LOESS vals
sample44male_predict <- predict(sample44male_loess, sample44male, se=TRUE)
sample44female_predict <- predict(sample44female_loess, sample44female, se=TRUE)
sample34male_predict <- predict(sample34male_loess, sample34male, se=TRUE)
sample34female_predict <- predict(sample34female_loess, sample34female, se=TRUE)
sample33male_predict <- predict(sample33male_loess, sample33male, se=TRUE)
sample33female_predict <- predict(sample33female_loess, sample33female, se=TRUE)

# Save SE-intervals
sample44male$fit <- sample44male_predict$fit
sample44male$lwl <- sample44male_predict$fit - 1.96*sample44male_predict$se.fit
sample44male$upl <- sample44male_predict$fit + 1.96*sample44male_predict$se.fit
sample44female$fit <- sample44female_predict$fit
sample44female$lwl <- sample44female_predict$fit - 1.96*sample44female_predict$se.fit
sample44female$upl <- sample44female_predict$fit + 1.96*sample44female_predict$se.fit

sample34male$fit <- sample34male_predict$fit
sample34male$lwl <- sample34male_predict$fit - 1.96*sample34male_predict$se.fit
sample34male$upl <- sample34male_predict$fit + 1.96*sample34male_predict$se.fit
sample34female$fit <- sample34female_predict$fit
sample34female$lwl <- sample34female_predict$fit - 1.96*sample34female_predict$se.fit
sample34female$upl <- sample34female_predict$fit + 1.96*sample34female_predict$se.fit

sample33male$fit <- sample33male_predict$fit
sample33male$lwl <- sample33male_predict$fit - 1.96*sample33male_predict$se.fit
sample33male$upl <- sample33male_predict$fit + 1.96*sample33male_predict$se.fit
sample33female$fit <- sample33female_predict$fit
sample33female$lwl <- sample33female_predict$fit - 1.96*sample33female_predict$se.fit
sample33female$upl <- sample33female_predict$fit + 1.96*sample33female_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44male, sample44female, sample33male, sample33female)
plotdf$APOE <- factor(plotdf$APOE, levels=c("4-4","3-3"))
plotdf$Sex <- factor(plotdf$Sex, levels=c("Male","Female"))

ggnfl <- ggplot(plotdf, aes(x=Age, y=cbk, color=APOE, linetype=Sex)) +
  geom_line(aes(x = Age, y = fit), 
            linewidth=1.5) + 
  geom_ribbon(aes(x=Age, ymin = lwl, ymax=upl), alpha=0.2) +
  scale_color_manual(values=c("#cc0d0a", "#1d7f07"),
                     name="",
                     labels = c("APOE-4/4",  "APOE-3/3")) +
  scale_linetype_manual(values=c("dotdash", "solid"),
                        name="",
                        labels = c("Male", "Female")) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15))

ffbk <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggnfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig2.pdf")
ggexport(ffbk, filename = saveimg, width=25, height=15, pointsize = 44)



# ==========

# ==========
# =====================================================================
#  Suppl Fig 2
#    NACC neuropath info 
# =====================================================================
# ==========
# Panel TOP - Barplot percentage
# ==========
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

# Whole cohort
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4")
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))
apoenames <- c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3", "APOE-2/x")
names(apoenames) <- c("4-4","3-4","3-3","2-x")

adnc["AGE_GROUP"] = "All"
tmpage = subset(adnc, NACCAGEDEATH >= 65)
tmpage["AGE_GROUP"] = "Older65"
adnc <- rbind(adnc,tmpage)
adnc["APOE_AGE"] = paste0(adnc$APOE,"_",adnc$AGE_GROUP)

fg <-adnc %>% dplyr::group_by(APOE, AGE_GROUP, pathologyAD) %>% tally %>% dplyr::mutate(pct= signif(n/sum(n)*100, digits=4))
fg <- data.frame(fg)
fg$percentage <- paste0(fg$pct, "%")
fg <- subset(fg, pathologyAD == "ADNC+")

apoecount <- adnc %>% dplyr::group_by(APOE,AGE_GROUP) %>% tally  %>% dplyr::mutate(sum = n)
apoecount <- data.frame(apoecount)

ggpathwhole<- ggplot(adnc, aes(x=as.factor(AGE_GROUP), fill=pathologyAD) ) + 
  geom_bar(position="fill") +
  geom_text(inherit.aes = FALSE, 
            data=apoecount,
            aes(x=AGE_GROUP, y=1.05, label=paste0("N=",sum))) +
  geom_label(data=fg,
             aes(x=AGE_GROUP, y=pct/100, fill=pathologyAD, label=percentage),
             size=5,
             show.legend = F) +
  facet_grid( .~APOE,
              switch = "x",
              labeller = labeller(APOE = apoenames)) + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"), 0.85), 
                    name="AD Pathology",
                    labels = c("ADNC-","ADNC+")) + 
  labs(
    title = paste0("(A) Frequency AD pathology"),
    x = "APOE",
    y = "Percentage",
    subtitle='Whole Sample') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(panel.spacing = unit(0, "cm"),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white",colour ="white"),
        plot.background = element_rect(fill = "white",colour ="black"),
        strip.background.x = element_rect(fill = "white",colour ="white"),
        strip.text.x = element_text(size=12))



# AD dementia
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 1)
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))
apoenames <- c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3", "APOE-2/x")
names(apoenames) <- c("4-4","3-4","3-3","2-x")

adnc["AGE_GROUP"] = "All"
tmpage = subset(adnc, NACCAGEDEATH >= 65)
tmpage["AGE_GROUP"] = "Older65"
adnc <- rbind(adnc,tmpage)
adnc["APOE_AGE"] = paste0(adnc$APOE,"_",adnc$AGE_GROUP)

fg <-adnc %>% dplyr::group_by(APOE, AGE_GROUP, pathologyAD) %>% tally %>% dplyr::mutate(pct= signif(n/sum(n)*100, digits=4))
fg <- data.frame(fg)
fg$percentage <- paste0(fg$pct, "%")
fg <- subset(fg, pathologyAD == "ADNC+")

apoecount <- adnc %>% dplyr::group_by(APOE,AGE_GROUP) %>% tally  %>% dplyr::mutate(sum = n)
apoecount <- data.frame(apoecount)

ggpathad<- ggplot(adnc, aes(x=as.factor(AGE_GROUP), fill=pathologyAD) ) + 
  geom_bar(position="fill") +
  geom_text(inherit.aes = FALSE, 
            data=apoecount,
            aes(x=AGE_GROUP, y=1.05, label=paste0("N=",sum))) +
  geom_label(data=fg,
             aes(x=AGE_GROUP, y=pct/100, fill=pathologyAD, label=percentage),
             size=5,
             show.legend = F) +
  facet_grid( .~APOE,
              switch = "x",
              labeller = labeller(APOE = apoenames)) + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"), 0.85), 
                    name="AD Pathology",
                    labels = c("ADNC-","ADNC+")) + 
  labs(
    title = paste0(""),
    x = "APOE",
    y = "Percentage",
    subtitle='AD Dementia') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(panel.spacing = unit(0, "cm"),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white",colour ="white"),
        plot.background = element_rect(fill = "white",colour ="black"),
        strip.background.x = element_rect(fill = "white",colour ="white"),
        strip.text.x = element_text(size=12))



# Non-AD dementia
adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 0)
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))
apoenames <- c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3", "APOE-2/x")
names(apoenames) <- c("4-4","3-4","3-3","2-x")

adnc["AGE_GROUP"] = "All"
tmpage = subset(adnc, NACCAGEDEATH >= 65)
tmpage["AGE_GROUP"] = "Older65"
adnc <- rbind(adnc,tmpage)
adnc["APOE_AGE"] = paste0(adnc$APOE,"_",adnc$AGE_GROUP)

fg <-adnc %>% dplyr::group_by(APOE, AGE_GROUP, pathologyAD) %>% tally %>% dplyr::mutate(pct= signif(n/sum(n)*100, digits=4))
fg <- data.frame(fg)
fg$percentage <- paste0(fg$pct, "%")
fg <- subset(fg, pathologyAD == "ADNC+")

apoecount <- adnc %>% dplyr::group_by(APOE,AGE_GROUP) %>% tally  %>% dplyr::mutate(sum = n)
apoecount <- data.frame(apoecount)


ggpathnoad<- ggplot(adnc, aes(x=as.factor(AGE_GROUP), fill=pathologyAD) ) + 
  geom_bar(position="fill") +
  geom_text(inherit.aes = FALSE, 
            data=apoecount,
            aes(x=AGE_GROUP, y=1.05, label=paste0("N=",sum))) +
  geom_label(data=fg,
             aes(x=AGE_GROUP, y=pct/100, fill=pathologyAD, label=percentage),
             size=5,
             show.legend = F) +
  facet_grid( .~APOE,
              switch = "x",
              labeller = labeller(APOE = apoenames)) + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"), 0.85), 
                    name="AD Pathology",
                    labels = c("ADNC-","ADNC+")) + 
  labs(
    title = paste0(""),
    x = "APOE",
    y = "Percentage",
    subtitle='Non-AD Dementia') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent()) +
  theme(panel.spacing = unit(0, "cm"),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white",colour ="white"),
        plot.background = element_rect(fill = "white",colour ="black"),
        strip.background.x = element_rect(fill = "white",colour ="white"),
        strip.text.x = element_text(size=12))


fftoprow <- ggarrange(ggpathwhole,ggpathad,ggpathnoad,
                      ncol=3, nrow=1,
                      common.legend = TRUE, legend = "right")
fftoprow


# ==========
# Panel Middle - ADNC score along age Whole sample
# ==========
# APOE-4/4
apoe44 <- subset(naccdb, APOE == "4-4"  & ADNC != "-4")
apoe44$AGE_round <- round(apoe44$NACCAGEDEATH)

tostream44 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream44)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe44$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream44[posdf,"AGE"] <- cage
    tostream44[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe44$ADNC == thrs[idx]  &  apoe44$AGE_round == cage)
    tostream44[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream44$PATH <- factor(tostream44$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path44 <- ggplot(tostream44, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +   
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='(B) ADNC pathology in Whole Sample', 
       subtitle='APOE4 - Homozygotes') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

# APOE-3/4
apoe34 <- subset(naccdb, APOE == "3-4"  & ADNC != "-4")
apoe34$AGE_round <- round(apoe34$NACCAGEDEATH)

tostream34 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream34)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe34$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream34[posdf,"AGE"] <- cage
    tostream34[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe34$ADNC == thrs[idx]  &  apoe34$AGE_round == cage)
    tostream34[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream34$PATH <- factor(tostream34$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path34 <- ggplot(tostream34, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE4 - Heterozygotes') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

# APOE-3/3
apoe33 <- subset(naccdb, APOE == "3-3"  & ADNC != "-4")
apoe33$AGE_round <- round(apoe33$NACCAGEDEATH)

tostream33 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream33)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe33$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream33[posdf,"AGE"] <- cage
    tostream33[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe33$ADNC == thrs[idx]  &  apoe33$AGE_round == cage)
    tostream33[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream33$PATH <- factor(tostream33$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path33 <- ggplot(tostream33, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE-3/3') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

ffmiddlerow <- ggarrange(path44,path34,path33,
                         ncol=3, nrow=1,
                         common.legend = TRUE, legend = "right")
ffmiddlerow


# ==========
# Panel Bottom - ADNC score along age AD-dementia
# ==========
apoe44 <- subset(naccdb, APOE == "4-4"  & ADNC != "-4" &  NACCALZD == 1)
apoe44$AGE_round <- round(apoe44$NACCAGEDEATH)

tostream44 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream44)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe44$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream44[posdf,"AGE"] <- cage
    tostream44[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe44$ADNC == thrs[idx]  &  apoe44$AGE_round == cage)
    tostream44[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream44$PATH <- factor(tostream44$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path44 <- ggplot(tostream44, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +   
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='(C) ADNC pathology in AD dementia', 
       subtitle='APOE4 - Homozygotes') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

# APOE-3/4
apoe34 <- subset(naccdb, APOE == "3-4"  & ADNC != "-4" &  NACCALZD == 1)
apoe34$AGE_round <- round(apoe34$NACCAGEDEATH)

tostream34 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream34)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe34$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream34[posdf,"AGE"] <- cage
    tostream34[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe34$ADNC == thrs[idx]  &  apoe34$AGE_round == cage)
    tostream34[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream34$PATH <- factor(tostream34$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path34 <- ggplot(tostream34, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE4 - Heterozygotes') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

# APOE-3/3
apoe33 <- subset(naccdb, APOE == "3-3"  & ADNC != "-4" &  NACCALZD == 1)
apoe33$AGE_round <- round(apoe33$NACCAGEDEATH)

tostream33 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream33)<- c('AGE', 'PATH', 'COUNT')

thrs = c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC")
posdf = 1
for (cage in unique(apoe33$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream33[posdf,"AGE"] <- cage
    tostream33[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe33$ADNC == thrs[idx]  &  apoe33$AGE_round == cage)
    tostream33[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}
tostream33$PATH <- factor(tostream33$PATH, 
                          levels =c("not-AD","Low-ADNC", "Intermediate-ADNC","High-ADNC"))

path33 <- ggplot(tostream33, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#c22d87", "#FEB24C", "#FC4E2A"),c(.7,.8,.9,.9)),
                    name="ADNC score",
                    labels =c("None","Low", "Intermediate","High")) +  
  xlim(c(50,90)) + 
  xlab("Age of Death") +
  labs(title='', 
       subtitle='APOE-3/3') +
  scale_y_continuous(name = "", 
                     labels = scales::label_percent())

ffbottomrow <- ggarrange(path44,path34,path33,
                         ncol=3, nrow=1,
                         common.legend = TRUE, legend = "right")
ffbottomrow

# ==========
# Merge all pannels
# ==========
ff1 <- ggarrange(fftoprow,ffmiddlerow,ffbottomrow,
                 ncol=1, nrow=3,
                 common.legend = FALSE, legend = "right")
ff1

outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig3.pdf")
ggexport(ff1, filename = saveimg, width=15,height=18,pointsize = 24)




# =====================================================================
#  Supplementary Figure 5
#    AT biomarkers + age(s) sympt death etc with 3/4
# =====================================================================
# ==========
## AT in-vivo biomarkers
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))

# amyloid
amypetdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3" | APOE == "3-4") &  !is.na(Centiloid_pos))
amycsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3" | APOE == "3-4") &  !is.na(CSF_AB42_Elecsys_pos))

amyloidtable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(amyloidtable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3", "3-4"))
  {
    subamypetdf <- subset(amypetdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subamycsfdf <- subset(amycsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqpet = (sum(subamypetdf$Centiloid_pos) / length(subamypetdf$Centiloid_pos))*100
    pospet = sum(subamypetdf$Centiloid_pos)
    negpet = length(subamypetdf$Centiloid_pos) - pospet
    freqcsf = (sum(subamycsfdf$CSF_AB42_Elecsys_pos) / length(subamycsfdf$CSF_AB42_Elecsys_pos))*100
    poscsf = sum(subamycsfdf$CSF_AB42_Elecsys_pos)
    megcsf =  length(subamycsfdf$CSF_AB42_Elecsys_pos) - poscsf
    
    amyloidtable[posdf,] <- c("Centiloid", cage, cage-2.5, cage+2.5, capoe, length(subamypetdf$Centiloid_pos),pospet,negpet,freqpet)
    posdf = posdf+1
    amyloidtable[posdf,] <- c("CSF AB1-42", cage, cage-2.5, cage+2.5, capoe, length(subamycsfdf$CSF_AB42_Elecsys_pos),poscsf,megcsf,freqcsf)
    posdf = posdf+1
  }
}

ggamyloid <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE), color=APOE, shape=BK), size=3, alpha=0.8) +
  geom_line(data=amyloidtable, aes(x=AGE, y=as.double(FREQ), group=interaction(BK, APOE),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("Centiloid", "CSF AB1-42")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("Centiloid", "CSF AB1-42")) +
  labs(
    title = paste0("(A) In-vivo markers"),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Amyloid markers') +
    scale_color_manual(values=c("#04820c","#bf820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-3/4","APOE-4/4")) +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))



# Tau
tauplasmadf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3" | APOE == "3-4") &  !is.na(Plasma_pTau_Simoa_pos))
taucsfdf <- subset(wholedf, (APOE == "4-4" | APOE == "3-3" | APOE == "3-4") &  !is.na(CSF_pTau_Elecsys_pos))

tautable <- data.frame(matrix(ncol = 9, nrow = 0))
colnames(tautable) <- c('BK',"AGE", "low-age", "high-age", "APOE", "Sample","pos","neg","FREQ")

posdf = 1
for (cage in seq(55,85,5))
{
  for (capoe in c("4-4", "3-3", "3-4"))
  {
    subtauplasmadf <- subset(tauplasmadf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    subtaucsfdf <- subset(taucsfdf, (Age > (cage-2.5)  &  Age < (cage+2.5)) & APOE==capoe)
    
    freqplasma = (sum(subtauplasmadf$Plasma_pTau_Simoa_pos) / length(subtauplasmadf$Plasma_pTau_Simoa_pos))*100
    posplasma = sum(subtauplasmadf$Plasma_pTau_Simoa_pos)
    negplasma = length(subtauplasmadf$Plasma_pTau_Simoa_pos) - posplasma
    freqcsf = (sum(subtaucsfdf$CSF_pTau_Elecsys_pos) / length(subtaucsfdf$CSF_pTau_Elecsys_pos))*100
    poscsf = sum(subtaucsfdf$CSF_pTau_Elecsys_pos)
    negcsf = length(subtaucsfdf$CSF_pTau_Elecsys_pos) - poscsf
    
    tautable[posdf,] <- c("Plasma pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtauplasmadf$Plasma_pTau_Simoa_pos), posplasma, negplasma,freqplasma)
    posdf = posdf+1
    tautable[posdf,] <- c("CSF pTau181", cage, cage-2.5, cage+2.5, capoe, length(subtaucsfdf$CSF_pTau_Elecsys_pos), poscsf, negcsf, freqcsf)
    posdf = posdf+1
  }
}

ggtau <- ggplot(NULL, aes(x=AGE, y=as.double(FREQ))) +
  geom_point(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK), color=as.factor(APOE), shape=BK), size=3, alpha=0.8, ) +
  geom_line(data=tautable, aes(x=AGE, y=as.double(FREQ), group=interaction(APOE,BK),linetype=BK, color=APOE)) +
  scale_shape_manual(values=c(16,17),
                     name="",
                     labels = c("CSF pTau181", "Pl pTau181")) +
  scale_linetype_manual(values=c(17,1),
                        name="",
                        labels = c("CSF pTau181", "Pl pTau181")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Frequency Positivity (%)",
    subtitle='Tau markers') +
    scale_color_manual(values=c("#04820c","#bf820c","#aa2525"),
                     name="",
                     labels = c("APOE-3/3","APOE-3/4","APOE-4/4")) +
  theme_bw()+
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffinvivo <- ggarrange(ggamyloid, ggtau,
                      ncol=2, nrow=1, legend="bottom")

# Ages of onset
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

adnc <- subset(naccdb, ADNC != "-4"  &  APOE !="2-4"  &  NACCALZD == 1)

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc$APOE <- factor(adnc$APOE, levels=c("4-4","3-4","3-3","2-x"))


onsetspan <- data.frame(matrix(ncol = 8, nrow = 0))
colnames(onsetspan) <- c("GROUP", "MEAN", "lowSD", "hiSD", "lowPI", "hiPI", "PIrange","METRIC")

posdf = 1
for (cgroup in c("4-4","3-4","3-3")){
  ## Symptoms onset
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999)
  currage <- tmpdf[tmpdf$APOE == cgroup, "DECAGE"]
  avg_symp <- mean(currage)
  sd_symp <- sd(currage)
  pi_symp <- sd_symp * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_symp
  onsetspan[posdf, 'lowSD'] <- avg_symp - 2*sd_symp
  onsetspan[posdf, 'hiSD'] <- avg_symp + 2*sd_symp
  onsetspan[posdf, 'lowPI'] <- avg_symp - pi_symp
  onsetspan[posdf, 'hiPI'] <- avg_symp + pi_symp
  onsetspan[posdf, 'PIrange'] <- round(2* pi_symp, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_SYMPT"
  posdf = posdf + 1  # Update iter
  
  ## Age of MCI onset
  tmpdf <- subset(adnc, MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "MCIONSETAGE"]
  avg_mci <- mean(currage)
  sd_mci <- sd(currage)
  pi_mci <- sd_mci * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_mci
  onsetspan[posdf, 'lowSD'] <- avg_mci - 2*sd_mci
  onsetspan[posdf, 'hiSD'] <- avg_mci + 2*sd_mci
  onsetspan[posdf, 'lowPI'] <- avg_mci - pi_mci
  onsetspan[posdf, 'hiPI'] <- avg_mci + pi_mci
  onsetspan[posdf, 'PIrange'] <- round(2* pi_mci, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_MCI"
  posdf = posdf + 1  # Update iter
  
  
  ## Age of Dementia onset
  # ##########################
  # OJO !
  # NEED TO EXCLUDE THOSE THAT WERE NOT MCI BEFORE (!)
  # ##########################
  tmpdf <- subset(adnc, DEMENTONSETAGE != 0 &  MCIONSETAGE != 0 )
  currage <- tmpdf[tmpdf$APOE == cgroup, "DEMENTONSETAGE"]
  avg_dement <- mean(currage)
  sd_dement <- sd(currage)
  pi_dement <- sd_dement * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_dement
  onsetspan[posdf, 'lowSD'] <- avg_dement - 2*sd_dement
  onsetspan[posdf, 'hiSD'] <- avg_dement + 2*sd_dement
  onsetspan[posdf, 'lowPI'] <- avg_dement - pi_dement
  onsetspan[posdf, 'hiPI'] <- avg_dement + pi_dement
  onsetspan[posdf, 'PIrange'] <- round(2* pi_dement, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEMENT"
  posdf = posdf + 1  # Update iter
  
  ## Age of death
  tmpdf <- subset(adnc, DECAGE != 888  &  DECAGE != 999 & DEMENTONSETAGE != 0 & MCIONSETAGE != 0)
  currage <- tmpdf[tmpdf$APOE == cgroup, "NACCAGEDEATH"]
  unique(currage)
  avg_death <- mean(currage)
  sd_death <- sd(currage)
  pi_death <- sd_death * 1.96 
  
  onsetspan[posdf, 'GROUP'] <- cgroup
  onsetspan[posdf, 'MEAN'] <- avg_death
  onsetspan[posdf, 'lowSD'] <- avg_death - 2*sd_death
  onsetspan[posdf, 'hiSD'] <- avg_death + 2*sd_death
  onsetspan[posdf, 'lowPI'] <- avg_death - pi_death
  onsetspan[posdf, 'hiPI'] <- avg_death + pi_death
  onsetspan[posdf, 'PIrange'] <- round(2* pi_death, digits=2)
  onsetspan[posdf, 'METRIC'] <- "AGE_DEATH"
  posdf = posdf + 1  # Update iter
  
}

onsetspan$METRIC <- factor(onsetspan$METRIC,
                           levels=c("AGE_SYMPT","AGE_MCI","AGE_DEMENT","AGE_DEATH"))
onsetspan$GROUP <- factor(onsetspan$GROUP,
                          levels=c("4-4","3-4","3-3"))

ggpred <- ggplot(onsetspan, aes(x=GROUP, y=MEAN, ymin=lowSD, ymax=hiSD, linetype=METRIC, col=GROUP)) + 
  geom_linerange(position = position_dodge(width = 0.6),
                 linewidth=1, 
                 show.legend=F) +
  geom_linerange(inherit.aes = FALSE,     # Only to define correctly the legend
                 data=onsetspan,         # if not, lines goes vertical...
                 aes(x=GROUP, y=0,xmin=1,xmax=1,linetype=METRIC, col=GROUP), 
                 show.legend=T) +
  ylim(48.5,107) +                         # Remove the zeros from the fake 
  theme_bw() + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4", "APOE-3/4","APOE-3/3")) +
  scale_linetype_manual(values=c("solid","longdash","dotdash","dotted"),
                        name="",
                        labels = c("Symptoms Onset", "MCI onset", "AD dementia onset", "Death")) +
  geom_point(aes(x=GROUP, y=MEAN, col=GROUP),
             position = position_dodge(width = 0.6),
             size=3,
             show.legend = F) + 
  labs(
    title = "(B) Age of Onset",
    x = "Groups",
    y = "Age") + 
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=15),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15),
        axis.text.x = element_blank())+ 
  xlab("")

# ==========
# Merge all pannels
# ==========
ffmerge <- ggarrange(ffinvivo, ggpred,
                      ncol=1, nrow=2, legend="bottom")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig4.pdf")
ggexport(ffmerge, filename = saveimg, width=15, height=10, pointsize = 44)


# ==========
# =====================================================================
#  Supplementary Figure 6
#    Bk along age APOE44 , APOE34, APOE44
# =====================================================================
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 2500] = 2500

ggcsfab <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 2500) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(A) Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)",
    subtitle='') +
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


# CSF pTau
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 50] = 50

ggcsfptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 50) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(B) Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Hippocampus volume
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 0.0065] = 0.0065
plotdf$cbk[plotdf$cbk < 0.0027] = 0.0027

gghippo <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.2, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("(C) Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume",
    subtitle='') +
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Centiloid
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"PET_Centiloid"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 120] = 120

ggcentiloid <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.3, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  ylim(-30,120)+
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Plasma pTau181
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 40] = 40

ggplasmaptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 40) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Plasma NfL
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"Plasma_NfL"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit


# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 70] = 70

ggplasmanfl <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE-4/4","APOE-3/4", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0, 70) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw()  +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# ==========
# Merge Biomarkers Pannels
# ==========
ffbk <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggplasmanfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig5.pdf")
ggexport(ffbk, filename = saveimg, width=25, height=15, pointsize = 24)

# ==========
# =====================================================================
#  Supplementary Figure 7
#    In-vivo biomarker LOESS with age by site (4/4, 3/4, 3/3)
# =====================================================================
# ==========
# APOE-4/4
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# Define cohort colors
#  ALFA   :  #C74F13
#  ADNI   :  #75C713  
#  WRAP   :  #136AC7 
#  OASIS  :  #8813C7
#  A4-bl  :  #13C7BC
#

## CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 1500] = 1500

ggcsfab <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 1500) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = "(A) APOE-4/4",
    subtitle = paste0("Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## CSF pTau
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 50] = 50

ggcsfptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 50) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Hippocampus volume
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 0.0065] = 0.0065
plotdf$cbk[plotdf$cbk < 0.0027] = 0.0027

gghippo <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX)) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid") +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed") +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Centiloid
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"PET_Centiloid"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 120] = 120

ggcentiloid <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  ylim(-30,120)+
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))
ggcentiloid

## Plasma pTau181
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 40] = 40

ggplasmaptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') + 
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Plasma NfL
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_NfL"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

# Loess fit - by Site
sample44$fit_site = 0    # init
cohorts = unique(sample44$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample44, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample44[sample44$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample44
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 70] = 70

ggplasmanfl <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffbk44 <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggplasmanfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")


# ==========
# APOE-3/4
# ==========
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# Define cohort colors
#  ALFA   :  #C74F13
#  ADNI   :  #75C713  
#  WRAP   :  #136AC7 
#  OASIS  :  #8813C7
#  A4-bl  :  #13C7BC
#

## CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 1500] = 1500

ggcsfab <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 1500) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="(B) APOE-3/4",
    subtitle = paste0("Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)") +
  theme_bw()+
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## CSF pTau
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 50] = 50

ggcsfptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 50) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Hippocampus volume
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 0.0065] = 0.0065
plotdf$cbk[plotdf$cbk < 0.0027] = 0.0027

gghippo <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX)) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid") +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed") +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Centiloid
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"PET_Centiloid"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 120] = 120

ggcentiloid <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  ylim(-30,120)+
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))


## Plasma pTau181
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 40] = 40

ggplasmaptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Plasma NfL
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_NfL"]
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

# Loess fit - by Site
sample34$fit_site = 0    # init
cohorts = unique(sample34$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample34, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample34[sample34$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample34
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-4'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 70] = 70

ggplasmanfl <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffbk34 <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggplasmanfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")

# ==========
# APOE-3/3
# ==========
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# Define cohort colors
#  ALFA   :  #C74F13
#  ADNI   :  #75C713  
#  WRAP   :  #136AC7 
#  OASIS  :  #8813C7
#  A4-bl  :  #13C7BC
#

## CSF AB1-42
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"CSF_AB42_Elecsys"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 1500] = 1500

ggcsfab <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 1500) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="(C) APOE-3/3",
    subtitle = paste0("Amyloid markers"),
    x = "Age",
    y = "CSF AB1-42 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## CSF pTau
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"CSF_pTau_Elecsys"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 50] = 50

ggcsfptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.8, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  ylim(0, 50) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Tau markers"),
    x = "Age",
    y = "CSF pTau-181 (pg/mL)") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Hippocampus volume
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Hippo_normalized_icv"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 0.0065] = 0.0065
plotdf$cbk[plotdf$cbk < 0.0027] = 0.0027

gghippo <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX)) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid") +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed") +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title="",
    subtitle = paste0("Neurodegeneration markers"),
    x = "Age",
    y = "(Normalized) hippocampus volume") +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Centiloid
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"PET_Centiloid"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 120] = 120

ggcentiloid <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Centiloid",
    subtitle='') +
  ylim(-30,120)+
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))
ggcentiloid

## Plasma pTau181
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_pTau_Simoa"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 40] = 40

ggplasmaptau <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma pTau-181 (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

## Plasma NfL
family_loess <- "symmetric"
wholedf$cbk <- wholedf[,"Plasma_NfL"]
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
# Loess fit - ALL
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree = 1, family = family_loess)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE)
sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Loess fit - by Site
sample33$fit_site = 0    # init
cohorts = unique(sample33$Cohort)

for (csite in cohorts){
  tmpsite = subset(sample33, Cohort == csite)
  tmpsite_loess = loess(cbk ~ Age, data = tmpsite, degree = 1, family = family_loess)
  tmpsite_predict = predict(tmpsite_loess, tmpsite, se=TRUE)
  tmpsite_fit = tmpsite_predict$fit
  sample33[sample33$Cohort ==csite,]["fit_site"] = tmpsite_fit
}

# Plot LOESS
plotdf <- sample33
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('3-3'))
plotdf$cohort_fact <- factor(plotdf$Cohort, levels = c("ALFA", "ADNI","WRAP","A4-bl","OASIS"))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 70] = 70

ggplasmanfl <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.7, aes(color=cohort_fact, shape=DX), show.legend = FALSE) + 
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit_site, color=cohort_fact), 
            linewidth=1.5, 
            alpha=1, linetype="solid",
            show.legend = FALSE) +
  scale_color_manual(values=c("#C74F13","#75C713","#13C7BC","#8813C7","#136AC7"),
                     name="",
                     labels = c("ALFA+","ADNI","WRAP","A4","OASIS")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=plotdf,
            inherit.aes = FALSE,
            aes(x = Age, y = fit), 
            color = "#6D6B6A", linewidth=1.5, 
            alpha=0.7, linetype="dashed",
            show.legend = FALSE) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0(""),
    x = "Age",
    y = "Plasma NfL (pg/mL)",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=18),
        axis.title=element_text(size=18),
        legend.text=element_text(size=20),
        plot.title=element_text(size=23),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

ffbk33 <- ggarrange(ggcsfab, ggcsfptau, gghippo,
                  ggcentiloid, ggplasmaptau,ggplasmanfl,
                  ncol=3, nrow=2,
                  common.legend = TRUE, legend = "right")

#
# Merge figures
#
ffbk <- ggarrange(ffbk44, ffbk34, ffbk33,
                    ncol=1, nrow=3, legend = "right")
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig5.pdf")
ggexport(ffbk, filename = saveimg, width=25, height=25, pointsize = 24)


# ==========
# =====================================================================
#  Supplementary Figure 3
#    tau-PET by groups
# =====================================================================
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)
# ==========
# Top Pannel
# ==========
AAO <- 65
wholedf$EYO <- wholedf$Age - AAO

# Braak 1/2
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"PET_tau_Bk12"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 2.2] = 2.2

ggbraak12 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0.7, 2.2) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("tau-PET Braak 1/2"),
    x = "Age",
    y = "tau-PET SUVr",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Braak 3/4
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"PET_tau_Bk34"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 2.2] = 2.2

ggbraak34 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0.7, 2.2) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("tau-PET Braak 3/4"),
    x = "Age",
    y = "tau-PET SUVr",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# Braak 5/6
family_loess <- "symmetric"

wholedf$cbk <- wholedf[,"PET_tau_Bk56"]
sample44 <- subset(wholedf, APOE == "4-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample34 <- subset(wholedf, APOE == "3-4" & !is.na(cbk) & DX != "Other"  & !is.na(DX))
sample33 <- subset(wholedf, APOE == "3-3" & !is.na(cbk) & DX != "Other"  & !is.na(DX))

# Loess fit
sample44_loess <- loess(cbk ~ Age, data = sample44, 
                        degree = 1, family = family_loess)
sample34_loess <- loess(cbk ~ Age, data = sample34, 
                        degree = 1, family = family_loess)
sample33_loess <- loess(cbk ~ Age, data = sample33, 
                        degree=1, family = family_loess)

# Predit LOESS vals
sample44_predict <- predict(sample44_loess, sample44, se=TRUE)
sample34_predict <- predict(sample34_loess, sample34, se=TRUE)
sample33_predict <- predict(sample33_loess, sample33, se=TRUE) 

# Save SE-intervals
sample44$fit <- sample44_predict$fit
sample44$lwl <- sample44_predict$fit - 1.96*sample44_predict$se.fit
sample44$upl <- sample44_predict$fit + 1.96*sample44_predict$se.fit

sample34$fit <- sample34_predict$fit
sample34$lwl <- sample34_predict$fit - 1.96*sample34_predict$se.fit
sample34$upl <- sample34_predict$fit + 1.96*sample34_predict$se.fit

sample33$fit <- sample33_predict$fit
sample33$lwl <- sample33_predict$fit - 1.96*sample33_predict$se.fit
sample33$upl <- sample33_predict$fit + 1.96*sample33_predict$se.fit

# Plot LOESS
plotdf <- rbind(sample44, sample33, sample34)
plotdf$apoe_fact <- factor(plotdf$APOE, levels = c('4-4','3-4','3-3'))

# Filter for plotting
plotdf$cbk[plotdf$cbk > 2.2] = 2.2

ggbraak56 <- ggplot(NULL, aes(x=Age, y=cbk)) +
  geom_point(data =plotdf, size=2, alpha=0.4, aes(color=apoe_fact, shape=DX)) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="",
                     labels = c("APOE4-Homozygotes","APOE4-Heterozygotes", "APOE-3/3")) +
  scale_shape_manual(values=c(17,16,15),
                     name="",
                     labels = c("AD","HC", "MCI")) +
  geom_line(data=sample44, 
            aes(x = Age, y = fit), 
            color = "#bf080c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample44, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf080c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample34, 
            aes(x = Age, y = fit), 
            color = "#bf820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample34, aes(x=Age, ymin = lwl, ymax=upl), 
              fill="#bf820c", alpha=0.5, inherit.aes = FALSE) +
  geom_line(data=sample33, 
            aes(x = Age, y = fit), 
            color = "#04820c", linewidth=1.5, inherit.aes = FALSE) +
  geom_ribbon(data=sample33, 
              aes(x=Age, ymin=lwl,ymax=upl),
              fill="#04820c", alpha=0.5, inherit.aes = FALSE) +
  ylim(0.7, 2.2) +
  scale_x_continuous(
    sec.axis = sec_axis(trans = ~ .x - 65,
                        name = "EYO")) +
  labs(
    title = paste0("tau-PET Braak 5/6"),
    x = "Age",
    y = "tau-PET SUVr",
    subtitle='') +
  theme_bw() +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))

# ==========
# Bottom Pannel
# ==========
wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA")
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "4-2"] <- "2-x"
wholedf['APOE'] <- factor(wholedf$APOE, levels=c("4-4", "3-4", "3-3"))

wholedf['CDR_group'] = 'CDR=0'
wholedf['CDR_group'][wholedf['CDR'] == 0.5] <- 'CDR=0.5'
wholedf['CDR_group'][wholedf['CDR'] == 1  | wholedf['CDR'] == 1.5] <- 'CDR=1-1.5'
wholedf['CDR_group'][wholedf['CDR'] > 1.5] <- 'CDR>=2'
wholedf['CDR_group'] <- factor(wholedf$CDR_group, levels=c('CDR=0','CDR=0.5','CDR=1-1.5', 'CDR>=2'))

# Braak 1/2
wholedf$cbk <- wholedf[,"PET_tau_Bk12"]
tosample <- subset(wholedf, !is.na(cbk)  & APOE != "2-x")

tosample$cbk[tosample$cbk > 2.2] = 2.2
boxbraak12 <- ggplot(tosample, aes(x=CDR_group, y=cbk, color=APOE)) + 
  geom_boxplot(show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="") +
  geom_point(position=position_jitterdodge(0.1),
             alpha = 0.7,
             show.legend = FALSE) +
  ylim(0.7, 2.2) +
  theme_bw() +
  labs(
    title ="",
    x = "",
    y = "tau-PET SUVr",
    subtitle='') +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))
boxbraak12

# Braak 3/4
wholedf$cbk <- wholedf[,"PET_tau_Bk34"]
tosample <- subset(wholedf, !is.na(cbk)  & APOE != "2-x")

tosample$cbk[tosample$cbk > 2.2] = 2.2
boxbraak34 <- ggplot(tosample, aes(x=CDR_group, y=cbk, color=APOE)) + 
  geom_boxplot(show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="") +
  geom_point(position=position_jitterdodge(0.1),
             alpha = 0.7,
             show.legend = FALSE) +
  ylim(0.7, 2.2) +
  theme_bw() +
  labs(
    title ="",
    x = "",
    y = "tau-PET SUVr",
    subtitle='') +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))
boxbraak34

# Braak 5/6
wholedf$cbk <- wholedf[,"PET_tau_Bk56"]
tosample <- subset(wholedf, !is.na(cbk)  & APOE != "2-x")

tosample$cbk[tosample$cbk > 2.2] = 2.2
boxbraak56 <- ggplot(tosample, aes(x=CDR_group, y=cbk, color=APOE)) + 
  geom_boxplot(show.legend = FALSE) + 
  scale_color_manual(values=c("#bf080c","#bf820c","#04820c"),
                     name="") +
  geom_point(position=position_jitterdodge(0.1),
             alpha = 0.7,
             show.legend = FALSE) +
  ylim(0.7, 2.2) +
  theme_bw() +
  labs(
    title ="",
    x = "",
    y = "tau-PET SUVr",
    subtitle='') +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=13),
        legend.text=element_text(size=15),
        plot.title=element_text(size=20),
        plot.subtitle=element_text(size=15),
        legend.title=element_text(size=15))
boxbraak56

# ==========
# Merge Pannel
# ==========
tauloess <- ggarrange(ggbraak12, ggbraak34, ggbraak56,
                      ncol=3, nrow=1,
                      common.legend = TRUE,
                      legend = "bottom")

tauboxplot <- ggarrange(boxbraak12, boxbraak34, boxbraak56,
                        ncol=3, nrow=1,
                        common.legend = FALSE)

supptaubraak <- ggarrange(tauloess, tauboxplot,
                          ncol=1, nrow=2,
                          common.legend = TRUE)
supptaubraak

outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/NatMed_edits_version/Figures"
saveimg <- paste0(outprfx,"/","Suppl_Fig7.pdf")
ggexport(supptaubraak, filename = saveimg, width=25, height=15, pointsize = 24)



# ==========
# Fig positivity amyloid 
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)

wholedf <- subset(wholedf, APOE != "2-4"  &  CDR != "NA"  & !is.na(Age))
wholedf["APOE"][wholedf["APOE"] == "2-2"] <- "2-x"
wholedf["APOE"][wholedf["APOE"] == "2-3"] <- "2-x"
wholedf$APOE <- factor(wholedf$APOE, levels=c("4-4","3-4","3-3","2-x"))

wholedf['Centiloid_pos'] = "A_neg"
wholedf['Centiloid_pos'][wholedf['PET_Centiloid'] > 24.4  ] = "A_pos"
wholedf['Centiloid_pos'][is.na(wholedf['PET_Centiloid'])] = NA

# Dementia Subset
gwdf <- subset(wholedf,  DX == "AD" )

# Amyloid-positivity ggstream apoe44 AD-dementia
apoe4 <- subset(gwdf, APOE == "4-4"  &  !is.na(Centiloid_pos))
apoe4$AGE_round <- round(apoe4$Age)

tostream4 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream4)<- c('AGE', 'PATH', 'COUNT')

thrs = c("A_neg","A_pos")
posdf = 1
for (cage in unique(apoe4$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream4[posdf,"AGE"] <- cage
    tostream4[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe4$Centiloid_pos == thrs[idx]  &  apoe4$AGE_round == cage)
    tostream4[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}

tostream4$PATH <- factor(tostream4$PATH, 
                         levels =c("A_neg","A_pos"))

path4 <- ggplot(tostream4, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"),c(.7,.9)),
                    name="",
                    labels=c("Amyloid Negative", "Amyloid Positive")) + 
  xlim(c(55,90)) + 
  xlab("Age") +
  ylab("Percentage (%)") + 
  labs(title='Percentage of Amyloid positivity along age in AD dementia', 
       subtitle='APOE4-Homozygotes - AD Dementia') +
  scale_y_continuous(name = "percentage", 
                     labels = scales::label_percent()) 


# Amyloid-positivity ggstream apoe34 AD-dementia
apoe34 <- subset(gwdf, APOE == "3-4"  &  !is.na(Centiloid_pos))
apoe34$AGE_round <- round(apoe34$Age)

tostream34 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream34)<- c('AGE', 'PATH', 'COUNT')

thrs = c("A_neg","A_pos")
posdf = 1
for (cage in unique(apoe34$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream34[posdf,"AGE"] <- cage
    tostream34[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe34$Centiloid_pos == thrs[idx]  &  apoe34$AGE_round == cage)
    tostream34[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}

tostream34$PATH <- factor(tostream34$PATH, 
                          levels =c("A_neg","A_pos"))

path34 <- ggplot(tostream34, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"),c(.7,.9)),
                    name="",
                    labels=c("Amyloid Negative", "Amyloid Positive")) + 
  xlim(c(55,90)) + 
  xlab("Age") +
  ylab("Percentage (%)") + 
  labs(title='', 
       subtitle='APOE4-Heterozygotes - AD Dementia') +
  scale_y_continuous(name = "percentage", 
                     labels = scales::label_percent()) 


# Amyloid-positivity ggstream apoe33 AD-dementia
apoe3 <- subset(gwdf, APOE == "3-3"  &  !is.na(Centiloid_pos))
apoe3$AGE_round <- round(apoe3$Age)

tostream3 <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(tostream3)<- c('AGE', 'PATH', 'COUNT')

thrs = c("A_neg","A_pos")
posdf = 1
for (cage in unique(apoe3$AGE_round)){
  for (idx in 1:length(thrs)){
    tostream3[posdf,"AGE"] <- cage
    tostream3[posdf,"PATH"] <-thrs[idx]
    count <- sum(apoe3$Centiloid_pos == thrs[idx]  &  apoe3$AGE_round == cage)
    tostream3[posdf,'COUNT'] <- count
    
    posdf = posdf+1
  }
}

tostream3$PATH <- factor(tostream3$PATH, 
                         levels =c("A_neg","A_pos"))

path3 <- ggplot(tostream3, aes(x = AGE, y = COUNT, fill = PATH)) +
  geom_stream(type = "proportional", bw = 0.9) + 
  theme_minimal() + 
  scale_fill_manual(values=alpha(c("#88419D","#FC4E2A"),c(.7,.9)),
                    name="",
                    labels=c("Amyloid Negative", "Amyloid Positive")) +   
  xlim(c(55,90)) + 
  xlab("Age") +
  ylab("Percentage (%)") + 
  labs(title='', 
       subtitle='APOE-3/3 - AD Dementia') +
  scale_y_continuous(name = "percentage", 
                     labels = scales::label_percent()) 

ggamyloid <- ggarrange(path4,path34, path3,
                       ncol=3, nrow=1,
                       common.legend = TRUE, legend = "right")


# ==========
# =====================================================================
#  TABLES paper
# =====================================================================
# ==========
# NACC
# ==========
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

# Whole cohort
adnc <- subset(naccdb, ADNC != "-4")
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-4"] <- "2-x"
adnc$APOE <- factor(adnc$APOE,
                    levels=c("4-4","3-4","3-3","2-x"),
                    labels=c('APOE4-Homozygotes','APOE4-Heterozygotes','APOE-3/3','APOE-2/X'))

# Subset table
adnc_subset <- adnc %>% select(SEX,ADNC, APOE, NACCALZD,NACCAGEDEATH)
adnc_subset$NACCALZD[adnc_subset$NACCALZD == 8] <- 0
adnc_subset$SEX[adnc_subset$SEX==2] <- 'Female'
adnc_subset$SEX[adnc_subset$SEX==1] <- 'Male'
adnc_subset$SEX <- as.factor(adnc_subset$SEX)
colnames(adnc_subset) <- c('Sex','ADNC','APOE','Alzheimer Dementia', 'Age Death')
# Generate table
table_nacc <- 
  tbl_summary(
    adnc_subset,
    by=APOE,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),
    missing="no"
  ) %>%
  add_overall() %>%
  bold_labels()
# Export
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES"
savetable <- paste0(outprfx,"/","Table1_NACC_demogaphics.html")
table_nacc   
table_nacc %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)


# NACC male
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 1)

# Whole cohort
adnc <- subset(naccdb, ADNC != "-4")
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-4"] <- "2-x"
adnc$APOE <- factor(adnc$APOE,
                    levels=c("4-4","3-4","3-3","2-x"),
                    labels=c('APOE4-Homozygotes','APOE4-Heterozygotes','APOE-3/3','APOE-2/X'))

# Subset table
adnc_subset <- adnc %>% select(SEX,ADNC, APOE, NACCALZD,NACCAGEDEATH)
adnc_subset$NACCALZD[adnc_subset$NACCALZD == 8] <- 0
adnc_subset$SEX[adnc_subset$SEX==2] <- 'Female'
adnc_subset$SEX[adnc_subset$SEX==1] <- 'Male'
adnc_subset$SEX <- as.factor(adnc_subset$SEX)
colnames(adnc_subset) <- c('Sex','ADNC','APOE','Alzheimer Dementia', 'Age Death')
# Generate table
table_nacc <- 
  tbl_summary(
    adnc_subset,
    by=APOE,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),
    missing="no"
  ) %>%
  add_overall() %>%
  bold_labels()
# Export
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed"
savetable <- paste0(outprfx,"/","Suppl_Table1_NACC_demogaphics_male.html")
table_nacc   
table_nacc %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)

# Nacc female
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)
naccdb <- subset(naccdb, naccdb$SEX == 2)

# Whole cohort
adnc <- subset(naccdb, ADNC != "-4")
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-4"] <- "2-x"
adnc$APOE <- factor(adnc$APOE,
                    levels=c("4-4","3-4","3-3","2-x"),
                    labels=c('APOE4-Homozygotes','APOE4-Heterozygotes','APOE-3/3','APOE-2/X'))

# Subset table
adnc_subset <- adnc %>% select(SEX,ADNC, APOE, NACCALZD,NACCAGEDEATH)
adnc_subset$NACCALZD[adnc_subset$NACCALZD == 8] <- 0
adnc_subset$SEX[adnc_subset$SEX==2] <- 'Female'
adnc_subset$SEX[adnc_subset$SEX==1] <- 'Male'
adnc_subset$SEX <- as.factor(adnc_subset$SEX)
colnames(adnc_subset) <- c('Sex','ADNC','APOE','Alzheimer Dementia', 'Age Death')
# Generate table
table_nacc <- 
  tbl_summary(
    adnc_subset,
    by=APOE,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),
    missing="no"
  ) %>%
  add_overall() %>%
  bold_labels()
# Export
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed"
savetable <- paste0(outprfx,"/","Suppl_Table1_NACC_demogaphics_female.html")
table_nacc   
table_nacc %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)

# Both sex but splitted
ifile <- '/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/NACC/neuropath_dataframe_nacc.csv'
naccdb <- read.table(ifile, sep=',', header = TRUE)

# Whole cohort
adnc <- subset(naccdb, ADNC != "-4")
adnc$pathologyAD <- "ADNC-"
adnc$pathologyAD[adnc$ADNC == "High-ADNC"  | adnc$ADNC == "Intermediate-ADNC" ] <- "ADNC+"
adnc$pathologyAD <- factor(adnc$pathologyAD, levels=c("ADNC-", "ADNC+"))

adnc["APOE"][adnc["APOE"] == "2-2"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-3"] <- "2-x"
adnc["APOE"][adnc["APOE"] == "2-4"] <- "2-x"
adnc$APOE <- factor(adnc$APOE,
                    levels=c("4-4","3-4","3-3","2-x"),
                    labels=c('APOE4-Homozygotes','APOE4-Heterozygotes','APOE-3/3','APOE-2/X'))

# Subset table
adnc_subset <- adnc %>% select(SEX,ADNC, APOE, NACCALZD,NACCAGEDEATH)
adnc_subset$NACCALZD[adnc_subset$NACCALZD == 8] <- 0
adnc_subset$SEX[adnc_subset$SEX==2] <- 'Female'
adnc_subset$SEX[adnc_subset$SEX==1] <- 'Male'
adnc_subset$SEX <- as.factor(adnc_subset$SEX)
colnames(adnc_subset) <- c('Sex','ADNC','APOE','Alzheimer Dementia', 'Age Death')
# Generate table
table_nacc <- 
  tbl_strata(adnc_subset, 
    strata = APOE,
    ~.x %>% 
  tbl_summary(
    by=Sex,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    )
    ),
    missing="no"
  ) %>%
  bold_labels()
# Export
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed"
savetable <- paste0(outprfx,"/","Suppl_Table1_NACC_demogaphics_bySex.docx")
table_nacc   
table_nacc %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)

# ==========
# Clinical
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)    

# Subset table
wholedf_filt <- wholedf %>% select(Age, Sex, Cohort,DX,APOE,
                                   CSF_AB42_Elecsys,CSF_pTau_Elecsys,Hippo_normalized_icv,
                                   PET_Centiloid,Plasma_pTau_Simoa,Plasma_NfL,
                                   PET_tau_Bk12,PET_tau_Bk34,PET_tau_Bk56)

wholedf_filt$APOE <- factor(wholedf_filt$APOE,
                            levels=c("4-4","3-4","3-3","2-3", "2-2","2-4"),
                            labels=c('APOE4/4','APOE3/4','APOE-3/3','APOE-2/3','APOE-2/2','APOE-2/4'))

wholedf_filt$DX[wholedf_filt$DX=="Other"] <- NA
wholedf_filt$DX <- factor(wholedf_filt$DX, levels=c('HC','MCI','AD'))

table_clinic <- 
  wholedf_filt %>% 
  tbl_strata(
    strata=Cohort,
    ~.x %>%
      tbl_summary(
        by=DX,
        missing="no"
      ) %>%
      add_n() %>%
      bold_labels()
  ) 

#Export
table_clinic
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES"
savetable <- paste0(outprfx,"/","Table2_Clinic_demogaphics.html")
table_clinic %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)


# ==========
# Clinical to merge with NACC
# ==========
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)    

# Subset table
wholedf_filt <- wholedf %>% select(Age, Sex, APOE, DX,
                                   CSF_AB42_Elecsys,CSF_pTau_Elecsys,Hippo_normalized_icv,
                                   PET_Centiloid,Plasma_pTau_Simoa,Plasma_NfL,
                                   PET_tau_Bk12,PET_tau_Bk34,PET_tau_Bk56)

wholedf_filt$DX[wholedf_filt$DX=="Other"] <- NA
wholedf_filt$DX <- factor(wholedf_filt$DX, levels=c('HC','MCI','AD'))

wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-2"] <- "2-x"
wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-3"] <- "2-x"
wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-4"] <- "2-x"
wholedf_filt$APOE <- factor(wholedf_filt$APOE,
                            levels=c("4-4","3-4","3-3","2-x"),
                            labels=c('APOE4/4','APOE3/4','APOE-3/3','APOE-2/X'))


table_clinic <- 
  tbl_summary(
    wholedf_filt,
    by=APOE,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),
    missing="no",
    
  ) %>%
  add_overall() %>%
  add_n() %>%
  bold_labels()

#Export
table_clinic
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1"
savetable <- paste0(outprfx,"/","Table2_Clinic_demogaphics_to_merge_NACC.html")
table_clinic %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)


# Split by sex
rm(list = ls())
indata <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/data/Table-main-2AGUST2022.csv"
wholedf <- read.table(indata, sep=',', header = TRUE)
wholedf[wholedf==""]<-NA
wholedf <- subset(wholedf, Sex != "")
wholedf <- subset(wholedf, !is.na(APOE))
wholedf <- wholedf[!is.na(wholedf$APOE),]
wholedf$CSF_AB42_Elecsys <- as.numeric(wholedf$CSF_AB42_Elecsys)
wholedf$CSF_tTau <- as.numeric(wholedf$CSF_tTau)
wholedf$CSF_pTau_Elecsys <- as.numeric(wholedf$CSF_pTau_Elecsys)    

# Subset table
wholedf_filt <- wholedf %>% select(Age, Sex, APOE, DX,
                                   CSF_AB42_Elecsys,CSF_pTau_Elecsys,Hippo_normalized_icv,
                                   PET_Centiloid,Plasma_pTau_Simoa,Plasma_NfL,
                                   PET_tau_Bk12,PET_tau_Bk34,PET_tau_Bk56)

wholedf_filt$DX[wholedf_filt$DX=="Other"] <- NA
wholedf_filt$DX <- factor(wholedf_filt$DX, levels=c('HC','MCI','AD'))

wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-2"] <- "2-x"
wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-3"] <- "2-x"
wholedf_filt["APOE"][wholedf_filt["APOE"] == "2-4"] <- "2-x"
wholedf_filt["APOE"][wholedf_filt["APOE"] == "4-2"] <- "2-x"
wholedf_filt$APOE <- factor(wholedf_filt$APOE,
                            levels=c("4-4","3-4","3-3","2-x"),
                            labels=c('APOE4/4','APOE3/4','APOE-3/3','APOE-2/X'))

table_clinic <- 
  tbl_strata(wholedf_filt, 
             strata = APOE,
             ~.x %>% 
  tbl_summary(
    by=Sex,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),  missing="no"
    ),
    missing="no",
    
  ) %>%
  bold_labels()


#Export
table_clinic
outprfx <- "/media/slieped/TheShire/WORK/HSP/Projects/APOE-ARAD/analyses/FIGURES_rev1_NatMed"
savetable <- paste0(outprfx,"/","Table_Clinic_demogaphics_to_merge_NACC_bySex.html")
table_clinic %>%
  as_gt() %>%
  gt::gtsave(filename=savetable)





# ==========