---
title: "ODC-TBI paper"
output: html_notebook
---

# Load Libraries
```{r loading}
rm(list=ls())

#### Load libraries ============================================================
libraries = c("tidyverse",
              #"aws.s3",
              "data.table",
              #"tableone",
              #"janitor",
              #"kableExtra",
              #"knitr",
              #"DT",
              #"lubridate",
              "naniar",#,
              "syndRomics",
              # "BaylorEdPsych",
              "mice",
              "GGally",
              "RColorBrewer",
              "colorRamps"
              #"summarytools"
)

invisible(lapply(libraries, library, character.only=TRUE))

#### Other parameters ==========================================================
save_flag <- FALSE
pca_pdf_flag <- FALSE
print_out_flag <- FALSE

#### Special function for ggpair plotting ======================================
ggpair_dens_mod <- function(data, mapping, ...) {
  ggplot(data = data, mapping=mapping) +
    geom_density(..., alpha = 0.7) 
}
ggpair_scatter_mod <- function(data, mapping, ...) {
  ggplot(data = data, mapping=mapping) +
    geom_point(..., alpha = 0.5) 
}
```

# Fig 2. Summary Plots
```{r}
#### Select file ===============================================================
input_file  <- file.choose() # Load DOI: 10.34945/F51P49

df.all <- read.csv(input_file,
                   header = TRUE,
                   stringsAsFactors = FALSE,
                   check.names = FALSE)

df.all <- df.all %>%
  rowwise() %>%
  mutate(Study = strsplit(GUID, split = "_") %>%
           unlist() %>%
           .[1]) %>%
  ungroup()

df <- df.all %>%
  as.data.frame() %>%
  select(GUID, Study, Study_ID, AnimalSpeciesTyp, AnimalSpeciesBreedTyp, AnimalSexTyp,
         TBIModel, AnimalInjuryGroupAssignTyp, AnimalGenotype, AnimalInjuryAge) %>%
  distinct() 

print(paste("Number of Unique Subjects:", nrow(df)))
```

## 2A. Animal Species
```{r}
#### Animal Species ============================================================
species <- df %>%
  group_by(AnimalSpeciesTyp) %>%
  summarise(Observations = n()) %>%
  mutate(percentage = round(Observations/sum(Observations) * 100, digits=2)) %>%
  ungroup() %>%
  rename("Species" = "AnimalSpeciesTyp") %>%
  mutate(Species = paste0(Species, ": ",
                          Observations, 
                          " (", percentage, "%)"))

p.species <- ggplot(species,
                    aes(x = "",
                        y = percentage,
                        fill = Species)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start=0) +
  theme_void() +
  # scale_fill_manual(values =c("#76B4DB", "#3E83D1")) +
  scale_fill_manual(values =c("#08519C", "#C6DBEF")) +
  # scale_fill_brewer(palette = "Blues", direction = -1) +
  ggtitle("Species") +
  theme(legend.title = element_blank())

print(p.species)
```

## 2B. Animal Sex
```{r}
#### SEX =======================================================================
sex <- df %>%
  mutate(AnimalSexTyp = case_when(AnimalSexTyp == "Male" ~ "M",
                                  AnimalSexTyp == "" ~ NA_character_,
                                  TRUE ~ AnimalSexTyp)) %>%
  group_by(AnimalSexTyp) %>%
  summarise(Observations = n()) %>%
  mutate(percentage = round(Observations/sum(Observations) * 100, digits=2)) %>%
  ungroup() %>%
  rename("Sex" = "AnimalSexTyp") %>%
  mutate(Sex = paste0(Sex, ": ",
                      Observations, 
                      " (", percentage, "%)"))

p.sex <- ggplot(sex,
                aes(x = "",
                    y = percentage,
                    fill = Sex)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start=0) +
  theme_void() +
  scale_fill_manual(values =c("#EFF3FF","#08519C", "#9ECAE1")) +
  # scale_fill_brewer(palette = "Blues") +
  ggtitle("Sex") +
  theme(legend.title = element_blank())

print(p.sex)
```

## 2C. Injury Model
```{r}
#### Injury Model ==============================================================
model <- df %>%
  group_by(TBIModel) %>%
  summarise(Observations = n()) %>%
  mutate(percentage = round(Observations/sum(Observations) * 100, digits=2)) %>%
  ungroup() %>%
  mutate(TBIModel = case_when(TBIModel == "fluid percussion injury model" ~ "Fluid Percussion Injury",
                              TBIModel == "CHIMERA repeated closed-head injuries" ~
                                "CHIMERA Repeated Closed-head Injury",
                              TRUE ~ TBIModel)) %>%
  mutate(TBIModel = paste0(TBIModel, ": ",
                           Observations,
                           " (", percentage, "%)")) 

p.model <- ggplot(model,
                  aes(x = "",
                      y = percentage,
                      fill = TBIModel)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start=0) +
  theme_void() +
  scale_fill_brewer(palette = "Blues") +
  ggtitle("TBI Models") +
  theme(legend.title = element_blank())

print(p.model)
```

## 2D. Mouse Genotype
```{r}
#### GENOTYPE ==================================================================
# Convert CCR2+/-/rfp to CCR2(rfp/+)
gen <- df %>%
  mutate(AnimalGenotype = ifelse(AnimalGenotype == "CCR2+/-/rfp",
                                 "CCR2(rfp/+)",
                                 AnimalGenotype),
         AnimalGenotype = ifelse(AnimalGenotype == "CX3CR1gfp/+,CCR2rfp/+",
                                 "CX3CR1(+/gfp), CCR2(+/rfp)",
                                 AnimalGenotype))

gen <- gen %>%
  filter(AnimalSpeciesTyp == "Mouse") %>%
  group_by(AnimalGenotype) %>%
  summarise(Observations = n()) %>%
  mutate(percentage = round(Observations/sum(Observations) * 100, digits=2)) %>%
  ungroup() %>%
  rename("Genotype" = "AnimalGenotype") %>%
  mutate(Genotype = paste0(Genotype, ": ",
                           Observations,
                           " (", percentage, "%)"))

p.gen <- ggplot(gen,
                aes(x = "",
                    y = percentage,
                    fill = Genotype)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y", start=0) +
  theme_void() +
  scale_fill_brewer(palette = "Blues") +
  ggtitle("Genotypes (Mouse only)") +
  theme(legend.title = element_blank())

print(p.gen)
```

## 2E. Mouse Age
```{r}
#### Age =======================================================================
print(df[df$AnimalSpeciesTyp == "Mouse", "AnimalInjuryAge"] %>% unique())

# Convert each study to months
df$AnimalInjuryAge_a <- df$AnimalInjuryAge #converted age

# Chou et al 2018 ==============================================================
# Convert 13-26 to 4 mo (4-7 mo)
df[df$Study == "AC.IntJMolSci.2018" & df$AnimalInjuryAge == "13-26", "AnimalInjuryAge_a"] <- 4

# Convert 86-108 to 22 mo (21.5-27 mo)
df[df$Study == "AC.IntJMolSci.2018" & df$AnimalInjuryAge == "86-108", "AnimalInjuryAge_a"] <- 22

# Convert 3-4 to 3 mo
df[df$Study == "AC.IntJMolSci.2018" & df$AnimalInjuryAge == "3-4", "AnimalInjuryAge_a"] <- 3

# Convert 22-24 to 22 mo
df[df$Study == "AC.IntJMolSci.2018" & df$AnimalInjuryAge == "22-24", "AnimalInjuryAge_a"] <- 22

# Chou, Krukowski et al 2017 ===================================================
df[df$Study == "ACKK.PNAS.2017" & df$AnimalInjuryAge == "12", "AnimalInjuryAge_a"] <- 3

# Chou et al 2016 ==============================================================
df[df$Study == "AC.PLoSOne.2016" & df$AnimalInjuryAge == "12", "AnimalInjuryAge_a"] <- 3

# Guglielmetti 2017 ============================================================
# Convert 12-to-15-weeks to 3 mo (3-4 mo)
df[df$Study == "CG.SciRep.2017" & df$AnimalInjuryAge == "12-to-15-weeks", "AnimalInjuryAge_a"] <- 3

# Krukowski 2018 ===============================================================
df[df$Study == "KK.IntJMolSci.2018" & df$AnimalInjuryAge == "19 months", "AnimalInjuryAge_a"] <- 19

# Morganti 2016 ================================================================
# 92 to 23 mo ; 12 to 3 mo ; 6-7 to 6 mo
df[df$Study == "JMM.JNeuroinflammation.2016" & df$AnimalInjuryAge == "92", "AnimalInjuryAge_a"] <- 23
df[df$Study == "JMM.JNeuroinflammation.2016" & df$AnimalInjuryAge == "12", "AnimalInjuryAge_a"] <- 3

# Morganti 2015 ================================================================
df[df$Study == "JMM.JNeurosci.2015" & df$AnimalInjuryAge == "6-7", "AnimalInjuryAge_a"] <- 6

# Morganti PlosOne 2016 ========================================================
df[df$Study == "JMM.PLoSOne.2016" & df$AnimalInjuryAge == "12", "AnimalInjuryAge_a"] <- 3

# Nolan 2018 ===================================================================
# 8 to 2 mo
df[df$Study == "AN.JNeurotrauma.2018" & df$AnimalInjuryAge == "8", "AnimalInjuryAge_a"] <- 2

# Lee (rat dataset) ============================================================
## EXCLUDED ##

# Lee et al. 2016 ==============================================================
df[df$Study == "SML.JNeuroinflammation.20166" & df$AnimalInjuryAge == "3 months", "AnimalInjuryAge_a"] <- 3

print(df[df$AnimalSpeciesType == "Mouse", "AnimalInjuryAge_a"] %>% unique())

p.age <- ggplot(df %>%
                  filter(AnimalSpeciesTyp == "Mouse") %>%
                  mutate(AnimalInjuryAge_a = as.numeric(AnimalInjuryAge_a)),
                aes(x = AnimalInjuryAge_a)) +
  geom_histogram(stat="count", fill = "#3E83D1", binwidth = 1) +
  ggtitle("Distribution of Animal Age (Mouse only)") +
  xlab("Animal Age (months)") +
  ylab("Number of Animals") +
  scale_x_continuous(breaks = seq(0,25,2)) +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank()) +
  ylim(0,500)

print(p.age)
```

## 2F. Mouse Days Post-Injury
```{r}
#### DAYS POST INJURY ==========================================================
hrs <- c("0", "3h", "6h", "12h") # Front timepoints for arranging

# Convert formats to days
dpi.conv <- df.all %>%
  filter(AnimalSpeciesTyp == "Mouse") %>%
  mutate(TimePostInjury = 
           case_when(grepl(pattern = "d", TimePostInjury) ~ gsub(pattern = "d",
                                                                 replacement = "",
                                                                 x = TimePostInjury),
                     grepl(pattern = "\\+", TimePostInjury) ~ gsub(pattern = "\\+",
                                                                   replacement = "",
                                                                   x = TimePostInjury),
                     grepl(pattern = "Baseline", TimePostInjury) ~ "0",
                     # grepl(pattern = "0", TimePostInjury) ~ "Baseline",
                     grepl(pattern = "24h", TimePostInjury) ~ "1",
                     grepl(pattern = "48h", TimePostInjury) ~ "2",
                     TimePostInjury == "" ~ NA_character_,
                     TRUE ~ TimePostInjury)) 

#Create new column to avoid issue with implicit NA factor later
dpi.conv$`Time Post-Injury` <- factor(dpi.conv$TimePostInjury,
                                      levels = c(hrs,
                                                 df.all$TimePostInjury[! df.all$TimePostInjury %in% hrs] %>%
                                                   unique() %>%
                                                   as.numeric() %>%
                                                   sort(na.last = TRUE)))
x = table1::table1(~ `Time Post-Injury`, data = dpi.conv)
print(x)


# Histogram
p.dpi <- ggplot(dpi.conv %>%
                  filter(AnimalSpeciesTyp == "Mouse"),
                aes(x = `Time Post-Injury`)) +
  geom_bar(stat="count", fill = "#3E83D1", width = 0.8, position = position_dodge(width = 1)) +
  ggtitle("Distribution of Observations: Days Post-Injury (Mouse only)") +
  scale_y_continuous(expand = expansion(add = 0), limits = c(0,450)) +
  scale_x_discrete(expand = expansion(add = 1)) +
  xlab("Days Post-Injury") +
  ylab("Number of Observations") +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

print(p.dpi)
```

## Save
```{r}
#### Save Plots ================================================================
if (save_flag) {
  png(paste0(Sys.Date(),
             ' - UCSF ODC Metadata.png')
      , width = 8, height = 8, units = 'in', res=300)
  gridExtra::grid.arrange(p.species, p.sex, p.model, p.gen, ncol=1)
  dev.off()
  
  png(paste0(Sys.Date(),
             ' - UCSF ODC Metadata - Age only.png'),
      width = 6, height = 4, units = 'in', res = 300)
  print(p.age)
  dev.off()
  
  png(paste0(Sys.Date(),
             ' - UCSF ODC Metadata - DPI only.png'),
      width = 11, height = 5, units = "in", res = 300)
  print(p.dpi)
  dev.off()
}
```

# Fig. 3

## 3A. Standard MVA
```{r}
# General MD Visualization -----------------------------------------------------
x.missing = file.choose() # Load DOI: 10.34945/F5T595
x = read.csv(x.missing,header = TRUE,stringsAsFactors = FALSE,check.names = FALSE)
colnames(x)[1] = "Animal.ID"
x[x==""] <- NA

p.x <- naniar::vis_miss(x) +
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.x=element_blank())
print(p.x)

if (save_flag) {
  png('Chou 2018 - Missing Data vis.png', width = 8, height = 5, units = 'in', res = 300)
  print(p.x)
  dev.off()
}
```

## 3B. Missing Values Types
```{r}
x.labeled_missing = file.choose() # Modified version of DOI: 10.34945/F5T595 that labeled reasons for missingness
x = read.csv(x.labeled_missing, header = TRUE, stringsAsFactors = FALSE, check.names = FALSE)
colnames(x)[1] = "Animal.ID"
x[x == ""] <- NA
row_order_index <- seq_len(nrow(x))
col_order_index <- names(x)

#### Convert missingness types to integers ####
x <- apply(x,2,FUN = function(x) case_when(is.na(x) ~ 0,
                                           x == "Missing record" ~ 1,
                                           x == "N/A" ~ 2,
                                           x == "Technical issues" ~ 3,
                                           TRUE ~ 4) %>%
             as.character())

dat_pre <- as.data.frame(x[row_order_index , ]) #Just convert x to dataframe

#### Transform dataframe for visualization ####
d <- dat_pre %>%
  dplyr::mutate(rows = dplyr::row_number()) %>%
  tidyr::gather_(key_col = "variable",
                 value_col = "valueType",
                 gather_cols = names(.)[-length(.)]) %>%
  dplyr::mutate(value = tidyr::gather_(dat_pre,
                                       "variable",
                                       "value",
                                       names(x))$value) # For plotly mouseover

#### Plot ####
p <- ggplot2::ggplot(data = d,
                     ggplot2::aes_string(x = "variable",
                                         y = "rows",
                                         # text assists with plotly mouseover
                                         text = "value")) +
  ggplot2::geom_raster(ggplot2::aes_string(fill = "valueType")) +
  ggplot2::theme_minimal() +
  ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45,
                                                     vjust = 1,
                                                     hjust = 1)) +
  ggplot2::labs(x = "",
                y = "Observations") +
  # flip the axes
  ggplot2::scale_y_reverse() +
  ggplot2::theme(axis.text.x = ggplot2::element_text(hjust = 0.5)) +
  
  # post vis_create_
  ggplot2::scale_fill_manual(name = "", 
                             values = c("white",
                                        "#5F6ED9", 
                                        "#B00000", 
                                        "#009B1C", 
                                        "grey80"), 
                             labels = c("Not Collected (Planned)", 
                                        "Missing record",
                                        "Not applicable",
                                        "Removed for technical reasons",
                                        "Present")) + 
  ggplot2::guides(fill = ggplot2::guide_legend(reverse = TRUE)) + 
  ggplot2::theme(legend.position = "bottom") + 
  ggplot2::theme(axis.text.x = ggplot2::element_text(hjust = 0)) +
  # reorder col
  ggplot2::scale_x_discrete(position = "top", 
                            limits = col_order_index) +
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.x=element_blank())
print(p)

if (save_flag) {
  png('Chou 2018 - Missing Data Types vis.png', width = 8, height = 5, units = 'in', res = 300)
  print(p)
  dev.off()
}
```

# Fig. 4

Further analysis combines data from 3 experiments: 1 from Chou et al and 2 from Morganti et al.
```{r}
#### Select data file ==========================================================
input_file  <- file.choose() # Combine IL-1B, TNF-a, iNOS, Ym1, CD206, and TGF-B columns from DOI 10.34945/F5T595 and DOI 10.34945/F5PC77. Note that some column headers were updated for dataset publication; code may reference previous spellings of cytokines.

df.og <- read.csv(input_file,
                  header = TRUE,
                  stringsAsFactors = FALSE,
                  check.names = FALSE)
colnames(df.og)[1] <- "GUID"
df.og[df.og == ""] <- NA

df.og <- df.og %>%
  mutate(Study = case_when(grepl("AC.IntJMolSci.2018", GUID) ~ 1,
                           grepl("JMM.JNeurosci.2015", GUID) & is.na(TreatmentGroupAssignTyp) ~ 2,
                           TRUE ~ 3)) %>%
  mutate(AnimalAgeGroup = case_when(Study == 2 | Study == 3 ~ "Adult",
                                    TRUE ~ AnimalAgeGroup))
```

Figures 4A, 4C, 4D are manually generated or pulled from figure 6.

## 4B. MVA
```{r MDA}
#### Generate MV visualization =================================================
#### MVA for just cytokine columns ####
# Select cytokine columns
cyt <- c("IL-1B", "TNF-a", "iNOS", "Ym1", "CD206", "TGF-B")
df.cyt <- df.og[,cyt]

# MVA
p <- naniar::vis_miss(df.cyt, show_perc_col = FALSE) +
  geom_abline(aes(intercept= -(df.og[df.og$Study == 2,] %>% # Add line delineating study 2
                                 row.names() %>%
                                 .[1] %>%
                                 as.numeric()),
                  slope=0),
              color="#4472C4",
              size=1) +
  geom_abline(aes(intercept= -(df.og[df.og$Study == 3,] %>% # Add line delineating study 3
                                 row.names() %>%
                                 .[1] %>%
                                 as.numeric()),
                  slope=0),
              color="#4472C4",
              size=1) +
  ggtitle("Aggregated Dataset - Cytokine variables only")
print(p)

if (save_flag) {
  png('Aggregated Missing Data vis.png', width = 5, height = 5, units = 'in', res = 300)
  print(p)
  dev.off()
}
```


## Intermediary analyses

First, we remove rows that are completely missing and validate the process with another MVA. We also run Little's test to determine whether the data is not missing at random.
```{r}
#### Remove row with all NA ====================================================
na.ind <- apply(df.cyt, 1, function(x) all(is.na(x)))
df.og <- df.og[!na.ind,]
rownames(df.og) <- NULL
df.cyt <- df.og[,cyt]

p <- naniar::vis_miss(df.cyt) +
  ggtitle("MDA after removing rows with all NA")
print(p)

cat("Little's test")
littles <- BaylorEdPsych::LittleMCAR(df.cyt)
# littles <- naniar::mcar_test(df.cyt)
print(littles$p.value)
```


# Fig. 6

Figure 6 analysis comes first in this script so we can obtain the PCA results for PC Space mapping (Fig 5).

## Standardize by Study (within-study z-score standardization)
```{r}
#### Z-score standardization ===================================================
df.conv <- df.og
for (c in cyt) {
  c_a = paste0(c,"_a")
  
  df.conv <- df.conv %>%
    dplyr::group_by(Study) %>%
    dplyr::mutate(!!c_a := (!!sym(c) - mean(!!sym(c), na.rm=TRUE))/sd(!!sym(c), na.rm=TRUE)) %>%
    # dplyr::mutate(!!paste0(c_a,"_avg") := mean(!!sym(c), na.rm = T)) %>% #Just testing grouping
    ungroup() %>%
    dplyr::select(-!!sym(c))
}

p <- naniar::vis_miss(df.conv)
print(p)

df.id <- df.conv %>%
  select("GUID",
         "Study_ID",
         "Study",
         "AnimalSpeciesTyp",
         "AnimalSpeciesBreedTyp",
         "AnimalSexTyp",
         "AnimalGenotype",
         "AnimalInjuryAge",
         "AnimalAgeGroup",
         "TBIModel",
         "AnimalInjuryGroupAssignTyp",
         "TimePostInjury",
         "Timepoint_Group",
         "TreatmentGroupAssignTyp")

df.cyt_a <- df.conv %>%
  select(colnames(df.conv)[!colnames(df.conv) %in% colnames(df.id)])

df.cyt_a <- df.cyt_a %>%
  rename("IL1B" = "IL-1B_a",
         "TNFa" = "TNF-a_a",
         "iNOS" = "iNOS_a",
         "Ym1" = "Ym1_a",
         "CD206" = "CD206_a",
         "TGFB" = "TGF-B_a")
```

## Data Imputation
```{r}
##### PMM Imputation (Mice) ====================================================
df.pmm <- mice::mice(data = df.cyt_a,
                     m = 10,
                     method = "pmm",
                     seed = 200)
# Final imputation using mean imputed ym1 values
ym1.pmm.mean <- apply(df.pmm$imp$Ym1, 1, mean)


# # Imputed Ym1 histogram for diagnostics
# transpose.ym1.pmm <- transpose(df.pmm$imp$Ym1)
# colnames(transpose.ym1.pmm) <- c("r9","r19")
# ggplot(transpose.ym1.pmm, aes(x=r9)) +
#   geom_histogram() +
#   geom_vline(xintercept = mean(transpose.ym1.pmm$r9), color = "blue")
# ggplot(transpose.ym1.pmm, aes(x=r19)) +
#   geom_histogram() +
#   geom_vline(xintercept = mean(transpose.ym1.pmm$r19), color = "blue")

df.cyt_a.pmm_mean <- df.cyt_a
df.cyt_a.pmm_mean[9,"Ym1"] <- ym1.pmm.mean[1]
df.cyt_a.pmm_mean[19,"Ym1"] <- ym1.pmm.mean[2]

# MDA to verify permutation
p <- naniar::vis_miss(df.cyt_a.pmm_mean) +
  ggtitle("Post-permutation MDA")
print(p)
```

## PCA
```{r pca}
# Run PCA: set center and scale to false since we have already normalized into z scores
# df.pmm_mean.pca = prcomp(df.cyt_a.pmm_mean, center = FALSE, scale. = FALSE)
df.pmm_mean.pca = prcomp(df.cyt_a.pmm_mean, center = T, scale. = T)

# Flip PC3 signs
df.pmm_mean.pca$rotation[,3] <- df.pmm_mean.pca$rotation[,3] * -1
df.pmm_mean.pca$x[,3] <- df.pmm_mean.pca$x[,3] * -1
```

## 6A. Scree Plot
```{r}
###### Scree plot #####
cat("Scree Plot")
pmm.pca_scree <- df.pmm_mean.pca$sdev^2/sum(df.pmm_mean.pca$sdev^2)
pmm.pca_scree <- data.frame("PC" = 1:length(pmm.pca_scree),
                           "Var" = pmm.pca_scree)

pmm.scree <- ggplot(pmm.pca_scree, aes(x=PC, y=Var)) + 
  geom_point(size=3) + 
  geom_line() +
  # geom_text(aes(label=Var %>%
  #                 round(digits=3)),nudge_x = .2,nudge_y=.05) +
  xlab("Principal Component") +
  ylab("Proportion of Variance Explained") +
  scale_y_continuous(breaks = seq(0,1,0.1), #For unlabeled version
                     limits = c(0,0.525),
                     expand = c(0,0)) +
  scale_x_continuous(breaks = seq(0,6,1)) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_blank(),
        axis.line = element_line(color = "black"),
        axis.ticks = element_line(color = "black"))
print(pmm.scree)

if (save_flag) {
  png("Scree Plot - unlabeled.png",
      width = 1200,
      height = 1200,
      res = 300)
  print(pmm.scree)
  dev.off()
}
```
## PCA Stability
```{r stability}
# Start with PMM imputation
# df.pmm$imp$Ym1: columns = each imputation, row = row to impute

# Create a list, where each list element is a complete dataframe with the imputed values

pca_list <- list()
for (imp in col(df.pmm$imp$Ym1)) {
  current_imp <- df.pmm$imp$Ym1[[imp]]
  df.cyt_a.single_imp <- df.cyt_a
  df.cyt_a.single_imp[9,"Ym1"] <- current_imp[1]
  df.cyt_a.single_imp[19, "Ym1"] <- current_imp[2]
  
  current_pca = prcomp(df.cyt_a.single_imp, 
                       center = FALSE,
                       scale. = FALSE)
  
  pca_list[[imp]] <- current_pca$rotation
}

imputed_sim <- syndRomics::component_similarity(pca_list, ndim = 6, s_cut_off = 0.2)
colnames(imputed_sim$index_all)[colnames(imputed_sim$index_all) == "Factor"] <- "PC"
colnames(imputed_sim$index_mean)[colnames(imputed_sim$index_mean) == "Factor"] <- "PC"
colnames(imputed_sim$index_sd)[colnames(imputed_sim$index_sd) == "Factor"] <- "PC"

cat("PC Stability - mean")
imputed_sim$index_mean
cat("PC Stability - sd")
imputed_sim$index_sd
```


## 6B. Syndromics
```{r syndromics}
##### Syndromic plots #####
cat("Syndromic plot")
pmm.syn <- syndRomics::syndromic_plot(pca = df.pmm_mean.pca,
                                      pca_data = df.cyt_a.pmm_mean, 
                                      cutoff = 0.2,
                                      arrow_size_multi = 4, 
                                      text_size = 6)
print(pmm.syn$PC1)
print(pmm.syn$PC2)
print(pmm.syn$PC3)

#### SAVE PDF OUTPUTS ####
if (save_flag) {
  pdf(paste0("PC1 syndromics ", format(Sys.Date(), '%Y-%m-%d'), '.pdf'),
      width = 8,
      height = 8)
  print(pmm.syn$PC1)
  dev.off()
  
  pdf(paste0("PC2 syndromics ", format(Sys.Date(), '%Y-%m-%d'), '.pdf'),
      width = 8,
      height = 8)
  print(pmm.syn$PC2)
  dev.off()
  
  pdf(paste0("PC3 syndromics ", format(Sys.Date(), '%Y-%m-%d'), '.pdf'),
      width = 8,
      height = 8)
  print(pmm.syn$PC3)
  dev.off()
}

if (save_flag) {
  demo.pmm.syn <- syndRomics::syndromic_plot(pca = df.pmm_mean.pca,
                                             pca_data = df.cyt_a.pmm_mean, 
                                             cutoff = 0.2,
                                             arrow_size_multi = 2, 
                                             text_size = 2,
                                             ndim = 1)
  ggsave(filename = "Demo syndromics.png",
         plot = demo.pmm.syn$PC1,
         width = 2,
         height = 2,
         device = "png")
}
```

## 6C. Barmap
```{r}
##### Barmap #####
cat("Bar map")
pmm.bmap <- syndRomics::barmap_loading(pca = df.pmm_mean.pca,
                                       pca_data = df.cyt_a.pmm_mean, 
                                       cutoff = 0.2)+
  ylim(-1,1)
print(pmm.bmap)

if (save_flag) {
  ggsave(filename = "Demo barmap.png",
         plot = pmm.bmap,
         device = "png",
         width = 6, 
         height = 2)
}

if (save_flag) {
  pmm.bmap.for_print <- syndRomics::barmap_loading(pca = df.pmm_mean.pca,
                                                   pca_data = df.cyt_a.pmm_mean, 
                                                   cutoff = 0.2, 
                                                   ndim = 3) +
    ylim(-1,1)
  
  pdf(paste0("PC Barmap ", format(Sys.Date(), '%Y-%m-%d'), '.pdf'),
      width = 12,
      height = 8)
  print(pmm.bmap.for_print)
  dev.off()
}
```

# SFig 2. Heatmap of PCA
```{r}
##### Heatmap ####
pmm.hmap <- syndRomics::heatmap_loading(pca = df.pmm_mean.pca,
                                        pca_data = df.cyt_a.pmm_mean)
print(pmm.hmap)

if (save_flag) {
  png(paste0("PC Heatmap ", format(Sys.Date(), '%Y-%m-%d'), '.png'),
      width = 6,
      height = 6,
      units = 'in',
      res = 300)
  print(pmm.hmap)
  dev.off()
}
```

# Fig. 5

## No standardization version

Perform full PCA workflow but WITHOUT the within-study z-score standardization step prior to analysis.

### Data Imputation
```{r}
#### Data Imputation ===========================================================
df.cyt.full_col.nostd <- df.og
df.id.nostd <- df.cyt.full_col.nostd %>%
  select("GUID",
         "Study_ID",
         "Study",
         "AnimalSpeciesTyp",
         "AnimalSpeciesBreedTyp",
         "AnimalSexTyp",
         "AnimalGenotype",
         "AnimalInjuryAge",
         "AnimalAgeGroup",
         "TBIModel",
         "AnimalInjuryGroupAssignTyp",
         "TimePostInjury",
         "Timepoint_Group",
         "TreatmentGroupAssignTyp")


df.cyt.nostd <- df.cyt.full_col.nostd %>%
  select(colnames(df.cyt.full_col.nostd)[!colnames(df.cyt.full_col.nostd) %in% colnames(df.id.nostd)]) %>%
  rename(IL1B = `IL-1B`,
         TNFa = `TNF-a`,
         TGFB = `TGF-B`)

p <- naniar::vis_miss(df.cyt.nostd)
print(p)

###### PMM Imputation (Mice) #####
df.pmm.nostd <- mice::mice(data = df.cyt.nostd,
                           m = 10,
                           method = "pmm",
                           seed = 100)

# Final imputation using mean imputed ym1 values
ym1.pmm.mean.nostd <- apply(df.pmm.nostd$imp$Ym1, 1, mean)

# # Imputed Ym1 histogram for diagnostics
# transpose.ym1.pmm <- transpose(df.pmm$imp$Ym1)
# colnames(transpose.ym1.pmm) <- c("r9","r19")
# ggplot(transpose.ym1.pmm, aes(x=r9)) +
#   geom_histogram() +
#   geom_vline(xintercept = mean(transpose.ym1.pmm$r9), color = "blue")
# ggplot(transpose.ym1.pmm, aes(x=r19)) +
#   geom_histogram() +
#   geom_vline(xintercept = mean(transpose.ym1.pmm$r19), color = "blue")

df.cyt.pmm_mean.nostd <- df.cyt
df.cyt.pmm_mean.nostd[9,"Ym1"] <- ym1.pmm.mean.nostd[1]
df.cyt.pmm_mean.nostd[19,"Ym1"] <- ym1.pmm.mean.nostd[2]

# MDA to verify permutation
p <- naniar::vis_miss(df.cyt.pmm_mean.nostd) +
  ggtitle("Post-permutation MDA")
print(p)
```

### PCA
```{r}
#### PCA =======================================================================
# Run PCA: Center/Scale = T to create correlation matrix
df.pmm_mean.pca.nostd = prcomp(df.cyt.pmm_mean.nostd, 
                               center = T, 
                               scale. = T)

# Flip PC2 and PC3 signs
df.pmm_mean.pca.nostd$rotation[,2] <- df.pmm_mean.pca.nostd$rotation[,2] * -1
df.pmm_mean.pca.nostd$rotation[,3] <- df.pmm_mean.pca.nostd$rotation[,3] * -1
df.pmm_mean.pca.nostd$x[,2] <- df.pmm_mean.pca.nostd$x[,2] * -1
df.pmm_mean.pca.nostd$x[,3] <- df.pmm_mean.pca.nostd$x[,3] * -1

###### Scree plot #####
cat("Scree Plot")
pmm.pca_scree.nostd <- df.pmm_mean.pca.nostd$sdev^2/sum(df.pmm_mean.pca.nostd$sdev^2)
pmm.pca_scree.nostd <- data.frame("PC" = 1:length(pmm.pca_scree),
                                  "Var" = pmm.pca_scree)

pmm.scree <- ggplot(pmm.pca_scree.nostd, aes(x=PC, y=Var)) + 
  geom_point(size=3) + 
  geom_line() +
  geom_text(aes(label=Var %>%
                  round(digits=3)),nudge_x = .2,nudge_y=.05)+
  xlab("Principal Component") +
  ylab("Proportion of Variance Explained")
print(pmm.pca_scree.nostd)
```

### Map to PCA space
```{r pc_space}
##### Mapping to PCA Space =====================================================
pc_space.nostd <- df.pmm_mean.pca.nostd$x[,1:3] %>%
  as.data.frame() %>%
  merge(x = df.og %>% 
          select("GUID",
         "Study_ID",
         "Study",
         "AnimalSpeciesTyp",
         "AnimalSpeciesBreedTyp",
         "AnimalSexTyp",
         "AnimalGenotype",
         "AnimalInjuryAge",
         "AnimalAgeGroup",
         "TBIModel",
         "AnimalInjuryGroupAssignTyp",
         "TimePostInjury",
         "Timepoint_Group",
         "TreatmentGroupAssignTyp"),
        y = .,
        by = "row.names") %>%
  mutate(Injury = AnimalInjuryGroupAssignTyp,
         Treatment = TreatmentGroupAssignTyp)

#### All ####
p.pc_all <- ggplot(pc_space.nostd, aes(x = PC1,
                                       y = PC2,
                                       color = factor(Study),
                                       shape = Injury)) +
  geom_point(size = 5, stroke = 2) +
  ggtitle("All Studies Mapped to PC Space") +
  xlab("PC1") +
  ylab("PC2") +
  scale_shape_manual(values = c(1, 16)) +
  scale_color_manual(values = c("forestgreen","orange2","royalblue3")) +
  scale_y_continuous(breaks=seq(-3,5,1)) +
  scale_x_continuous(breaks=seq(-4,7,1)) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color="grey70"))
print(p.pc_all)

if (save_flag) {
  png("IntER-norm PC Scores plot.png",
      width=3000,height=2400,res=300)
  print(p.pc_all)
  dev.off()
}

#### 7 days post-injury ####
d7 <- pc_space.nostd %>%
  filter(Study == 1 |
           (Study == 2 & TimePostInjury == "7d") |
           (Study == 2 & Injury == "Sham") |
           (Study == 3 & Treatment == "Vehicle" & Injury == "Sham")) %>%
  mutate(Study = as.character(Study))

p.pc_d7 <- ggplot(d7, aes(x = PC1,
                          y = PC2,
                          color = factor(Study),
                          shape = Injury)) +
  geom_point(size = 5, stroke = 2) +
  ggtitle("Sham and 7dpi in PC Space") +
  xlab("PC1") +
  ylab("PC2") +
  scale_shape_manual(values = c(1, 16))  +
  scale_color_manual(values = c("forestgreen","orange2","royalblue3")) +
  scale_y_continuous(breaks=seq(-3,5,1)) +
  scale_x_continuous(breaks=seq(-4,7,1),
                     limits = c(-2,1)) + 
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color="grey70"))
print(p.pc_d7)

if (save_flag) {
  png("IntER-norm 7dpi PC Scores plot.png",
      width=3000,height=2400,res=300)
  print(p.pc_d7)
  dev.off()
}
```

## With within-study standardization
```{r}
##### Mapping to PCA Space =====================================================
pc_space <- df.pmm_mean.pca$x[,1:3] %>%
  as.data.frame() %>%
  merge(x = df.og %>% 
          select("GUID",
         "Study_ID",
         "Study",
         "AnimalSpeciesTyp",
         "AnimalSpeciesBreedTyp",
         "AnimalSexTyp",
         "AnimalGenotype",
         "AnimalInjuryAge",
         "AnimalAgeGroup",
         "TBIModel",
         "AnimalInjuryGroupAssignTyp",
         "TimePostInjury",
         "Timepoint_Group",
         "TreatmentGroupAssignTyp"),
        y = .,
        by = "row.names") %>%
  mutate(Injury = AnimalInjuryGroupAssignTyp,
         Treatment = TreatmentGroupAssignTyp)

#### All ####
p.pc_all <- ggplot(pc_space, aes(x = PC1,
                                 y = PC2,
                                 color = factor(Study),
                                 shape = Injury)) +
  geom_point(size = 5, stroke = 2) +
  ggtitle("All Studies Mapped to PC Space") +
  xlab("PC1") +
  ylab("PC2") +
  scale_shape_manual(values = c(1, 16)) +
  scale_color_manual(values = c("forestgreen","orange2","royalblue3")) +
  scale_y_continuous(breaks=seq(-3,5,1)) +
  scale_x_continuous(breaks=seq(-4,7,1)) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color="grey70"))
print(p.pc_all) 

if (print_out_flag) {
  png("Intra-norm PC Scores plot.png",
      width=3000,height=2400,res=300)
  print(p.pc_all)
  dev.off()
}

#### 7 days post-injury ####
d7 <- pc_space %>%
  filter(Study == 1 |
           (Study == 2 & TimePostInjury == "7d") |
           (Study == 2 & Injury == "Sham") |
           (Study == 3 & Treatment == "Vehicle" & Injury == "Sham")) %>%
  mutate(Study = as.character(Study))

p.pc_d7 <- ggplot(d7, aes(x = PC1,
                          y = PC2,
                          color = factor(Study),
                          shape = Injury)) +
  geom_point(size = 5, stroke = 2) +
  ggtitle("Sham and 7dpi in PC Space") +
  xlab("PC1") +
  ylab("PC2") +
  scale_shape_manual(values = c(1, 16)) +
  scale_color_manual(values = c("forestgreen","orange2","royalblue3")) +
  scale_y_continuous(breaks=seq(-3,5,1)) +
  scale_x_continuous(breaks=seq(-4,7,1)) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color="grey70"))
print(p.pc_d7) 

if (print_out_flag) {
  png("Intra-norm 7dpi PC Scores plot.png",
      width=3000,height=2400,res=300)
  print(p.pc_d7)
  dev.off()
}
```

# Fig. 7

Test aging trends from Chou et al but adding additional data from other studies.
```{r}
#### Chou ####
#### Adult vs Aged, 7 dpi ####
chou <- pc_space %>%
  filter(Injury == "Sham" | 
            (TimePostInjury == 7 | TimePostInjury == "7d")) %>%
  filter(Treatment == "Vehicle" | is.na(Treatment)) %>%
  mutate(Group = paste0(AnimalAgeGroup,", ", Injury))


p.chou <- ggplot(chou, aes(x = PC1, 
                           y = PC2, 
                           shape = Injury,
                           color = AnimalAgeGroup)) +
  geom_point(size = 5, stroke = 2) +
  scale_shape_manual(values = c(1, 16)) +
  scale_color_manual(values = c("blue3", "red3")) +
  scale_x_continuous(breaks = seq(-3,6,1)) +
  scale_y_continuous(breaks = seq(-3,6,1)) +
  theme_minimal() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color="grey70"))
print(p.chou)

if (save_flag) {
  png("Age vs Adult 7 dpi pc scores.png",
      width=3000,height=2400,res=300)
  print(p.chou)
  dev.off()
}
```

```{r}
#### 7 dpi Injury x Age analysis ===============================================
#### PC1 ####
cat("PC1\n")
aov(PC1 ~ Injury*Age_Category, data = chou %>%
      rename("Age_Category" = AnimalAgeGroup)) %>%
  summary()
cat("\n\n")

#### PC2 ####
cat("PC2\n")
aov(PC2 ~ Injury*Age_Category, data = chou %>%
      rename("Age_Category" = AnimalAgeGroup)) %>%
  summary()
cat("\n\n")
```


# Study Effect
```{r}
#### ANOVA after within-study z-score standardization ####
cat("No study standardization\n")
pc_space.nostd$Study <- factor(pc_space.nostd$Study,
                               levels = pc_space.nostd$Study %>% unique())

aov(PC1 ~ Study + Injury + Study*Injury, data = pc_space.nostd) %>%
  summary()
aov(PC2 ~ Study + Injury + Study*Injury, data = pc_space.nostd) %>%
  summary()
cat("\n\n")
```

```{r}
#### ANOVA after within-study z-score standardization ####
cat("With within-study z-score standardization\n")
pc_space$Study <- factor(pc_space$Study,
                         levels = pc_space$Study %>% unique())

aov(PC1 ~ Study + Injury + Study*Injury, data = pc_space) %>%
  summary()
aov(PC2 ~ Study + Injury + Study*Injury, data = pc_space) %>%
  summary()
cat("\n\n")
```

# Effect size analysis

Determine whether PCA has higher power for each univariate measure from Chou et al 2018.

```{r}
#### Function for partial eta squared conversion ===============================
convert_partial_e2 <- function(x, N, k) {
  ### Converts the partial eta squared (sumsq[effect] / (sumsq[effect] + sumsq[residual]))
  #      to the partial eta squared used for observed power calculation
  # Input:
  #   x = partial eta squared (e.g. as returned by SPSS)
  #   N = total samples
  #   k = total number of groups in the design
  # Output:
  #   partial eta squared for power calculation as per G*Power program
  
  p_et2 <- x * (N - k) / (N - k * x)
  return(p_et2)
}
```


```{r}
#### Select animals ============================================================
##### Isolating Chou 2018 cohort #####
# chou <- pc_space %>%
#   filter(grepl("Chou", Paper)) %>%
#   mutate(Group = paste0(`Age Category`,", ", Injury))
# chou <- chou %>%
#   rename("Age_Category" = `Age Category`)

#### Isolating all Sham/7dpi animals (i.e. Fig 7) ####
chou <- pc_space %>%
  filter(Injury == "Sham" | 
            (TimePostInjury == 7 | TimePostInjury == "7d")) %>%
  filter(Treatment == "Vehicle" | is.na(Treatment)) %>%
  mutate(Group = paste0(AnimalAgeGroup,", ", Injury))
chou <- chou %>%
  rename("Age_Category" = AnimalAgeGroup)

#### ANOVAs ====================================================================
chou.pc1.aov <- aov(PC1 ~ Injury + Age_Category + Injury:Age_Category,
                    data = chou)
# chou.pc1.aov %>%
#   summary()

chou.pc2.aov <- aov(PC2 ~ Injury + Age_Category + Injury:Age_Category, 
                    data = chou)
# chou.pc2.aov %>%
#   summary()

chou.pc3.aov <- aov(PC3 ~ Injury + Age_Category + Injury:Age_Category, 
                    data = chou)
# chou.pc3.aov %>%
#   summary()
```

```{r}
#### Manual eta sq calculation =================================================

#### PC1 ####
# Convert ANOVA output to a dataframe 
chou_pc1.stats <- broom::tidy(chou.pc1.aov)

#### Manual calculation of eta sq (Effect SumSq / Total SumSq) ####
chou_pc1.total_sumsq <- chou_pc1.stats$sumsq %>% sum()
chou_pc1.res_sumsq <- chou_pc1.stats %>%
  filter(term == "Residuals") %>%
  .$sumsq

chou_pc1.stats <- chou_pc1.stats %>%
  mutate(eta_sq = sumsq/chou_pc1.total_sumsq) %>%
  mutate(partial_eta_sq = sumsq/(sumsq+chou_pc1.res_sumsq)) %>%
  mutate(N = sum(df)+1,
         k = 4,
         power_p_et2 = convert_partial_e2(partial_eta_sq, N, k)) %>%
  select(-N, -k)
print(chou_pc1.stats)

#### PC2 ####
# Convert ANOVA output to a dataframe 
chou_pc2.stats <- broom::tidy(chou.pc2.aov)

#### Manual calculation of eta sq (Effect SumSq / Total SumSq) ####
chou_pc2.total_sumsq <- chou_pc2.stats$sumsq %>% sum()
chou_pc2.res_sumsq <- chou_pc2.stats %>%
  filter(term == "Residuals") %>%
  .$sumsq

chou_pc2.stats <- chou_pc2.stats %>%
  mutate(eta_sq = sumsq/chou_pc2.total_sumsq) %>%
  mutate(partial_eta_sq = sumsq/(sumsq + chou_pc2.res_sumsq)) %>%
  mutate(N = sum(df)+1,
         k = 4,
         power_p_et2 = convert_partial_e2(partial_eta_sq, N, k)) %>%
  select(-N, -k)
print(chou_pc2.stats)

# EtaSq(chou.pc2.aov) #BaylorEdPsych package has a etasq calculator; can use for validation
# EtaSq(cyt.aov)

#### PC3 ####
# Convert ANOVA output to a dataframe 
chou_pc3.stats <- broom::tidy(chou.pc3.aov)

#### Manual calculation of eta sq (Effect SumSq / Total SumSq) ####
chou_pc3.total_sumsq <- chou_pc3.stats$sumsq %>% sum()
chou_pc3.res_sumsq <- chou_pc3.stats %>%
  filter(term == "Residuals") %>%
  .$sumsq

chou_pc3.stats <- chou_pc3.stats %>%
  mutate(eta_sq = sumsq/chou_pc3.total_sumsq) %>%
  mutate(partial_eta_sq = sumsq/(sumsq + chou_pc3.res_sumsq)) %>%
  mutate(N = sum(df)+1,
         k = 4,
         power_p_et2 = convert_partial_e2(partial_eta_sq, N, k)) %>%
  select(-N, -k)
print(chou_pc3.stats)
```

We also then calculate the eta squared for each univariate measure in Chou et al 2016
```{r}
cyt <- c("IL-1B", "TNF-a", "iNOS", "Ym1", "CD206", "TGF-B")

#### Prepare Chou dataset for univariate analysis ####
df.chou <- df.og %>%
  filter(grepl("AC.IntJMolSci.2018", GUID)) %>%
  rename("Age_Category" = AnimalAgeGroup) %>%
  rename("Injury" = AnimalInjuryGroupAssignTyp) %>%
  select(GUID, Age_Category, Injury, all_of(cyt)) %>%
  rename(IL1B = `IL-1B`,
         TNFa = `TNF-a`,
         TGFB = `TGF-B`)

cyt <- c("IL1B", "TNFa", "iNOS", "Ym1", "CD206", "TGFB")

#### Aggregate univariate analysis ####
# Iterate through each cytokine of interest
all_cyt.stats <- data.frame()
for (c in cyt) {
  # Run ANOVA
  cyt.aov <- aov(eval(as.name(c)) ~ Injury*Age_Category,
                 data = df.chou)
  cyt.df <- broom::tidy(cyt.aov) # Convert anova summary to dataframe
  
  # Calculate eta_sq
  total_sumsq <- cyt.df$sumsq %>%
    sum()
  res_sumsq <- cyt.df %>%
    filter(term == "Residuals") %>%
    .$sumsq
  
  cyt.df <- cyt.df %>%
    mutate(eta_sq = sumsq/total_sumsq) %>%
    mutate(partial_eta_sq = sumsq/(sumsq + res_sumsq))  %>%
    mutate(N = sum(df)+1,
           k = 4,
           power_p_et2 = convert_partial_e2(partial_eta_sq, N, k)) %>%
    select(-N, -k) %>%
    mutate(Cytokine = c) %>%
    relocate(Cytokine)
  
  # Aggregate
  all_cyt.stats <- rbind(all_cyt.stats,
                         cyt.df)
}

# Aggregate with the PC calculations
all_cyt.stats <- rbind(chou_pc1.stats %>%
                         mutate(Cytokine = "PC1") %>%
                         relocate(Cytokine),
                       chou_pc2.stats %>%
                         mutate(Cytokine = "PC2") %>%
                         relocate(Cytokine)) %>%
  rbind(chou_pc3.stats %>%
          mutate(Cytokine = "PC3") %>%
          relocate(Cytokine)) %>%
  rbind(all_cyt.stats)
```

G*Power manual for power calculation:
https://www.psychologie.hhu.de/fileadmin/redaktion/Fakultaeten/Mathematisch-Naturwissenschaftliche_Fakultaet/Psychologie/AAP/gpower/GPowerManual.pdf

See page 26


Relationship between partial eta sq to the partial eta sq used by G Power is:

True_eta_sq = et2 * N / (N + k*et2 - k)

or

et2 = true_eta_sq * (N - k) / (N - k * true_eta_sq)

where N = total samples and k = total groups
```{r}
#### Calculate power ===========================================================
#### via f = eta2/(1-eta2) ####
all_cyt.stats <- all_cyt.stats %>%
  # Calculate GPower f = sqrt(power_p_eta2 / (1 - power_p_eta2))
  mutate(f = sqrt(power_p_et2/(1-power_p_et2))) %>%
  # Calculate power
  ## u is always = 1; v (the degrees of freedom of the anova denominator) changes, so let's propagate it
  group_by(Cytokine) %>%
  mutate(v = ifelse(term == "Residuals",
                    df,
                    NA)) %>%
  fill(v, .direction = "updown") %>%
  ungroup() %>%
  ## calculate power
  mutate(power.stdev = pwr::pwr.f2.test(u = 1,
                                        v = v, 
                                        f2 = f^2,
                                        sig.level = 0.05) %>%
           .$power) %>%
  select(-v)

# Restructuring/Renaming #
eta_and_power.output <- all_cyt.stats %>%
  rename("F.statistic" = statistic,
         "Effect" = term,
         "Variable" = Cytokine) %>%
  # Rename Age_Category as Age
  mutate(Effect = gsub(pattern = "Age_Category",
                       replacement = "Age", 
                       Effect)) %>%
  select(Effect, Variable, eta_sq, power.stdev) %>%
  rename("Effect_Size" = eta_sq,
         "Power" = power.stdev) %>%
  filter(Effect != "Residuals") %>%
  arrange(match(Effect, c("Injury", "Age", "Injury:Age")),
          match(Variable, c("PC1", "PC2", "PC3", cyt))) #%>%
# mutate_at(c("sumsq", "meansq", "statistic", "p.value", "eta_sq", "partial_eta_sq"),
#           function(x) round(x, digits = 3))

eta_and_power.output <- eta_and_power.output %>%
  arrange(match(Effect, c("Injury", "Age", "Injury:Age")),
          desc(Effect_Size))

write.csv(x = eta_and_power.output, file = "Chou observed power analysis.csv", row.names = F)
```

# Session info
```{r}
sessionInfo()
```

