---
title: "Astrocyte ALS A1 meta-analysis"
author: "Oliver Ziff"
date: "`r format(Sys.time(), '%d %h %Y %H:%M')`"
output:
  html_document:
    fig_width: 7
    fig_height: 6
    toc_depth: 3
    theme: simplex
    dev: jpeg
editor_options:
  chunk_output_type: console
---

```{r setup, include=FALSE}
load("/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/astrocyte_a1_als_meta.RData")
source("/camp/home/ziffo/home/scripts/functions/all_r_functions.R")
# source("/camp/lab/luscomben/home/users/ziffo/projects/astrocyte-a1-als-meta/scripts/ALS_reactive_astrocytes_meta/astrocyte_a1_als_meta_functions.R")

# Update git / github
library(usethis) # usethis & gert https://jeroen.github.io/gert2019 https://www.garrickadenbuie.com/blog/pull-request-flow-usethis/?interactive=1&steps=
library(gert)
setwd("/Volumes/lab-luscomben/home/users/ziffo/projects/astrocyte-a1-als-meta/scripts/ALS_reactive_astrocytes_meta") # setwd then dont need to specify repo argument
git_commit_all("update") # stage all files & commit in one command - implies git_add(".")
# pr_init("figures_and_tables") # initialise a new branch
pr_push() # this will open github in chrome > pull request > merge

git_sitrep() # print git and github info
git_config()
git_info()
git_ls() # list git tree
git_log() # check recent commits
git_status() # check which files are modified
# pr_resume("figures_and_tables") # resume a branch
# git_add(".") #stage the files you want to commmit - "." indicates all files.
# git_commit("update") # commit with comment
# pr_pull()
```

# DESeq2 objects

Create sym links so that all Salmon results accessible in /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon

```{bash}
cd /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/astrocyte-fractionation-bulk-rnaseq/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-c9orf72-ipsc-birger-2019/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-sod1-ipsc-tyzack-2017/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-fus-ipsc-neyrinck-2021/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/purified-cortex-human-zhang-2016/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/regional-astrocytes-ipsc-bradley-2019/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/reactive-astrocyte-barbar-2020/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/reactive-astrocyte-ipsc-leng-2021/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-sod1-mouse-bacTRAP-cleveland-2015/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-membralin-mouse-jiang-2019/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-tdp43-mouse-peng-2020/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-sci-mouse-anderson-2017/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/reactive-astrocyte-mouse-guttenplan-2020/nfcore/star_salmon/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/alignment/salmon

cd /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/astrocyte-fractionation-bulk-rnaseq/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-c9orf72-ipsc-birger-2019/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-sod1-ipsc-tyzack-2017/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-fus-ipsc-neyrinck-2021/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/reactive-astrocyte-ipsc-leng-2021/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-membralin-mouse-jiang-2019/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-tdp43-mouse-peng-2020/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/astrocyte-sci-mouse-anderson-2017/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/
ln -s /camp/lab/luscomben/home/shared/projects/patani-collab/public-data/reactive-astrocyte-mouse-guttenplan-2020/splicing/irfinder/* /camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/


find . -xtype l -delete # remove only broken soft links
```

Run the script to create the DESeq2 objects to create ac_comparison.RData. Takes ~ 1 hour mins

```{bash}
cd /camp/lab/luscomben/home/users/ziffo/projects/astrocyte-a1-als-meta/scripts
mls
sar
sbatch -N 1 -c 8 --mem=30G -t 6:00:00 --wrap="Rscript /camp/lab/luscomben/home/users/ziffo/projects/astrocyte-a1-als-meta/scripts/ALS_reactive_astrocytes_meta/astrocyte_a1_als_meta_objects.R" --mail-type=ALL,ARRAY_TASKS --mail-user=oliver.ziff@crick.ac.uk --job-name=DESeq2objects
```


# Fig S1 PCA & Dendrogram

hiPSC & cortex clustering

```{r}
zhang_bradley_patani_tyzack_birger_neyrinck.pcaData <- plotPCA(zhang_bradley_patani_tyzack_birger_neyrinck$vsd, intgroup=c("group", "region", "replicate", "celltype_source", "sample", "dataset", "name"), returnData=TRUE) #  
zhang_bradley_patani_tyzack_birger_neyrinck.percentVar <- round(100 * attr(zhang_bradley_patani_tyzack_birger_neyrinck.pcaData, "percentVar"))
zhang_bradley_patani_tyzack_birger_neyrinck.pca <- ggplot(zhang_bradley_patani_tyzack_birger_neyrinck.pcaData, aes(PC1, PC2, color=celltype_source, shape = region)) + 
  scale_color_manual( values = c(astrocyte_adult  = "#FF7F00",
astrocyte_fetal  = "#FDBF6F",
neuron_adult = "#6A3D9A",
myeloid_adult          = "#F0E442",
oligodendrocyte_adult   = "#CAB2D6",
This_study        = "#A6CEE3",    
Tyzack_ipsc   = "#1F78B4",
Birger_ipsc    = "#B2DF8A", 
Neyrinck_ipsc   = "#33A02C", 
Bradley_SC_ipsc  = "#FB9A99",
Bradley_FB_ipsc   = "#E31A1C")) +
  theme_bw() + theme(panel.grid = element_blank(), legend.title = element_blank(), legend.text=element_text(size=8), legend.position = "none", legend.box = "vertical", legend.spacing = unit(0.1, 'cm')) + geom_point(size=2) + 
  xlab(paste0("PC1: ",zhang_bradley_patani_tyzack_birger_neyrinck.percentVar[1],"% variance")) +  ylab(paste0("PC2: ",zhang_bradley_patani_tyzack_birger_neyrinck.percentVar[2],"% variance")) + #coord_fixed() + 
  # geom_text_repel(data = filter(zhang_bradley_patani_tyzack_birger_neyrinck.pcaData, dataset == "neyrinck"), aes(x = PC1, y = PC2, label = sample), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +
  ggforce::geom_mark_ellipse(aes(label = celltype_source), label.fontsize = 8, label.fontface = "plain", con.type = "straight", con.cap = 0.5, show.legend = FALSE)
# zhang_bradley_patani_tyzack_birger_neyrinck.pca
# ggsave(zhang_bradley_patani_tyzack_birger_neyrinck.pca, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/zhang_bradley_patani_tyzack_birger_neyrinck.pca.png", height = 7, width = 9)


# Dendrogram
zhang_bradley_patani_tyzack_birger_neyrinck.sampleDists <- dist(t(assay(zhang_bradley_patani_tyzack_birger_neyrinck$vsd)))
zhang_bradley_patani_tyzack_birger_neyrinck.hc <- hclust(zhang_bradley_patani_tyzack_birger_neyrinck.sampleDists, method = "ward.D2")
zhang_bradley_patani_tyzack_birger_neyrinck.hc$labels <- gsub("_cortex", "", zhang_bradley_patani_tyzack_birger_neyrinck.hc$labels) %>% gsub("_temporal_lobe", "", .) %>% gsub("CD49", "barbar", .) %>% 
  gsub("dorsal_forebrain", "Bradley_ipsc_DFB", .) %>% gsub("ventral_forebrain", "Bradley_ipsc_VFB", .) %>% gsub("ventral_spinalcord", "Bradley_ipsc_VSC", .) %>% gsub("dorsal_spinalcord", "Bradley_ipsc_DSC", .) %>%   
  gsub("ac_tyz_astrocyte", "Tyzack", .) %>% gsub("ac_bir_astrocyte", "Birger", .)  %>% gsub("ac_ney_astrocyte", "Neyrinck", .) %>% gsub("astrocyte_ipsc", "This_study_ipsc", .) %>% gsub("_R", "_", .)
display.brewer.pal(n = 12, name = 'Paired')
brewer.pal(n = 12, name = "Paired")
show_col(brewer_pal(palette = "Paired")(12))
"#A6CEE3" # light blue
"#1F78B4" 
"#B2DF8A" # green
"#33A02C"
"#FB9A99" # red
"#E31A1C" 
"#FDBF6F" # orange
"#FF7F00"
"#CAB2D6" # purple
"#6A3D9A" 
"#B15928 # brown
"#FFFF99" # yellow - replace with darker yellow for readability #F0E442
zhang_bradley_patani_tyzack_birger_neyrinck.a <- c(
                                                   rep("#E31A1C", 6),
                                                   rep("#FB9A99", 6),
                                                   rep("#A6CEE3", 4),
                                                   rep("#1F78B4", 7),
                                                   rep("#B2DF8A", 4),
                                                   rep("#33A02C", 12),
                                                   rep("#FDBF6F", 6),
                                                   rep("#FF7F00", 12),
                                                  rep("#F0E442", 3),
                                                 rep("#6A3D9A", 1),
                                                 rep("#CAB2D6", 5))
zhang_bradley_patani_tyzack_birger_neyrinck.dendrogram <- ggdendrogram(zhang_bradley_patani_tyzack_birger_neyrinck.hc, rotate = TRUE, theme_dendro = FALSE) +  theme_classic()  + theme(axis.line=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y= element_text(colour = zhang_bradley_patani_tyzack_birger_neyrinck.a, size = 8), strip.background = element_rect(colour="black", fill="white"), panel.grid = element_blank()) 
# zhang_bradley_patani_tyzack_birger_neyrinck.dendrogram
# ggsave(zhang_bradley_patani_tyzack_birger_neyrinck.dendrogram, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/zhang_bradley_patani_tyzack_birger_neyrinck.dendrogram_celltypes.png", height = 7, width = 4)

zhang_bradley_patani_tyzack_birger_neyrinck.clustering <- ggarrange(zhang_bradley_patani_tyzack_birger_neyrinck.pca, zhang_bradley_patani_tyzack_birger_neyrinck.dendrogram, nrow = 2, heights = c(1,1), labels = c("A", "B"))
zhang_bradley_patani_tyzack_birger_neyrinck.clustering
ggsave(zhang_bradley_patani_tyzack_birger_neyrinck.clustering, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/FigS1.zhang_bradley_patani_tyzack_birger_neyrinck.clustering.png", height = 14, width = 9)
```


# Fig 1 CTRL & VCP Characterisation

A is biorender schematic of ipsc differentiation protocol

## Astrocyte marker heatmap

```{r}
astrocyte.genes <- c("VIM","TNC","GFAP","GJA1","SOX9","ID4","NFIX", "MLC1", "GLI3","EZR","CCDC80","EDNRB","PBXIP1","FGFR3","RFX4","TMEM47","F3","SLC9A3R1", "BMPR1B","EMP2","FZD2","CHRDL1","AQP4","MGST1", "EGFR","CYBRD1","CBS","S1PR1", "S100B", "SLC7A2", "ACSBG1")
celltype.marker.df = data.frame("gene_name" = astrocyte.genes) %>% mutate(group = case_when(gene_name %in% astrocyte.genes ~ "astrocyte"))
assay(ctrls.zhang_bradley_patani$vsd) %>% as_tibble(rownames = "gene_id") %>% left_join(gene2ens, by = "gene_id")  %>% filter(gene_name %in% astrocyte.genes) %>% group_by(gene_name) %>% filter(n()>1) # any duplicate gene_names?

vsd_counts.celltype.marker <-  assay(ctrls.zhang_bradley_patani$vsd) %>% as_tibble(rownames = "gene_id") %>% left_join(gene2ens, by = "gene_id")  %>% filter(gene_name %in% astrocyte.genes) %>% 
 rowwise() %>%
 mutate("Current study" = mean(c_across(starts_with("astrocyte_ipsc")), na.rm = TRUE), 
        "Bradley et al" = mean(c_across(starts_with("ventral_spinalcord")), na.rm = TRUE), 
        "Astrocyte fetal" = mean(c_across(starts_with("astrocyte_fetal")), na.rm = TRUE), 
        "Astrocyte adult" = mean(c_across(starts_with("astrocyte_adult_temporal")), na.rm = TRUE), 
        Oligodendrocyte = mean(c_across(starts_with("oligodendrocyte")), na.rm = TRUE), 
        Myeloid = mean(c_across(starts_with("myeloid")), na.rm = TRUE), 
        Neuron = mean(c_across(starts_with("neuron")), na.rm = TRUE)) %>% 
  select(gene_name, Myeloid, Neuron, Oligodendrocyte, `Astrocyte adult`, `Astrocyte fetal`, `Bradley et al`, `Current study`, -gene_id) %>%
  filter(rowMeans(across(where(is.numeric))) > 3.31) %>% # remove genes with no expression across samples
  mutate_if(is.numeric, funs((. - 3.309)))  %>% # subtract from all values so start from 0 
  transpose_tibble(old_rownames = "gene_name", new_rownames = "group") %>% # transpose: rows > columns
  mutate(across(where(is.numeric), ~ scale2(.x, na.rm = FALSE))) %>% # scale to the columns (i.e. row scale)  scale2 <- function(x, na.rm = FALSE) (x - mean(x, na.rm = na.rm)) / sd(x, na.rm)
  transpose_tibble(old_rownames = "group", new_rownames = "gene_name") #%>% arrange(`Current study`)# transpose back: columns > rows, order by expression in our astrocytes

vsd_counts.celltype.marker.mat <- make_matrix(select(vsd_counts.celltype.marker,-gene_name), pull(vsd_counts.celltype.marker,gene_name))
celltype.marker.df.filt <- celltype.marker.df %>% filter(gene_name %in% vsd_counts.celltype.marker$gene_name)
astrocyte.marker.heatmap <- Heatmap(vsd_counts.celltype.marker.mat, 
          heatmap_legend_param = list(title = ""), 
          cluster_rows = FALSE, cluster_columns = TRUE,
          row_order = vsd_counts.celltype.marker$gene_name,
          show_row_names = TRUE, row_names_side = "right", row_names_gp = gpar(fontsize = 8), #row_labels = celltype.marker.row.labels,
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("Astrocyte markers"), labels_gp = gpar(fontsize = 10))),
          row_title = NULL,
          column_names_rot = 90, 
          column_title = NULL,
          column_names_gp = gpar(fontsize = c(9,9,9,9,9,9,10)))
astrocyte.marker.heatmap

```

## Glutamate uptake heatmap

hiPSC astrocytes expressed several genes known to be critical in phagocytosis including AXL, ABCA1, MERTK, MEGF10, GAS6 (...) and glutamate uptake including EAAT1, EAAT2, GRIN2b, GRIA1, GRIK1 (...) (Fig. 1D)

```{r}
glutamate.uptake.df = data.frame("gene_name" = glutamate.uptake.go) %>% mutate(group = case_when(gene_name %in% glutamate.uptake.go ~ "glutamate.uptake"))
assay(ctrls.zhang_bradley_patani$vsd) %>% as_tibble(rownames = "gene_id") %>% left_join(gene2ens, by = "gene_id")  %>% filter(gene_name %in% glutamate.uptake.go) %>% group_by(gene_name) %>% filter(n()>1) # any duplicate gene_names?
vsd_counts.glutamate.uptake <-  assay(ctrls.zhang_bradley_patani$vsd) %>% as_tibble(rownames = "gene_id") %>% left_join(gene2ens, by = "gene_id") %>% 
  filter(gene_name %in% glutamate.uptake.go) %>% filter(!gene_id %in% c("ENSG00000100031", "ENSG00000286070")) %>%  # remove duplicate ENSID for GGT1
 rowwise() %>%
 mutate("Current study" = mean(c_across(starts_with("astrocyte_ipsc")), na.rm = TRUE), 
        "Bradley et al" = mean(c_across(starts_with("ventral_spinalcord")), na.rm = TRUE), 
        "Astrocyte fetal" = mean(c_across(starts_with("astrocyte_fetal")), na.rm = TRUE), 
        "Astrocyte adult" = mean(c_across(starts_with("astrocyte_adult_temporal")), na.rm = TRUE), 
        Oligodendrocyte = mean(c_across(starts_with("oligodendrocyte")), na.rm = TRUE), 
        Myeloid = mean(c_across(starts_with("myeloid")), na.rm = TRUE), 
        Neuron = mean(c_across(starts_with("neuron")), na.rm = TRUE)) %>% 
  select(gene_name, Myeloid, Neuron, Oligodendrocyte, `Astrocyte adult`, `Astrocyte fetal`, `Bradley et al`, `Current study`, -gene_id) %>%
  filter(rowMeans(across(where(is.numeric))) > 3.31) %>% # remove genes with no expression across samples
  mutate_if(is.numeric, funs((. - 3.309)))  %>% # subtract from all values so start from 0 
  arrange(`Current study`)
glutamate.uptake.row.labels = c("CANX", "GLUL", "SLC1A3", "PTEN1", "GRIA1", "FLOT1", "CACNG4", "SLC7A11", "FLOT2", "GRID1")
glutamate.uptake.row.index = match( glutamate.uptake.row.labels, vsd_counts.glutamate.uptake$gene_name)
vsd_counts.glutamate.uptake.mat <- make_matrix(select(vsd_counts.glutamate.uptake,-gene_name), pull(vsd_counts.glutamate.uptake,gene_name))
glutamate.uptake.df.filt <- glutamate.uptake.df %>% filter(gene_name %in% vsd_counts.glutamate.uptake$gene_name)
col_ramp_glut.uptake = colorRamp2(c(0, 3, 6), c("blue", "white", "red")) # set colour limits to -4 to 4 for all heatmaps

glutamate.uptake.heatmap <- 
  Heatmap(vsd_counts.glutamate.uptake.mat, 
          heatmap_legend_param = list(title = ""),  col = col_ramp_glut.uptake,
          cluster_rows = FALSE, cluster_columns = FALSE,
          row_order = vsd_counts.glutamate.uptake$gene_name,
          show_row_names = FALSE, #row_names_side = "left", row_names_gp = gpar(fontsize = 8), row_labels = glutamate.uptake.row.labels,
          border = TRUE, #, #, col = c(rep("red", 10), rep("blue", 8)))
          right_annotation = rowAnnotation(markers = anno_mark(at = glutamate.uptake.row.index, labels = glutamate.uptake.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("Glutamate uptake"), labels_gp = gpar(fontsize = 10))),
          row_title = NULL,
          column_names_rot = 90, 
          column_split =  c(1,1,1,1,1,2,2),
          column_title = NULL,
          column_names_gp = gpar(fontsize = c(9,9,9,9,9,9,10)),
          bottom_annotation = HeatmapAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white")), labels = c("Human Cortex\n(Zhang et al)", "Astrocyte\nhiPSC"), labels_gp = gpar(fontsize = 9))), border_gp = gpar(col = "black"))
glutamate.uptake.heatmap


# most highly expressed in ipsc_astrocytes
glutamate.receptor.go <- unique(c(go.pathways.msigdb$GO_GLUTAMATE_BINDING, go.pathways.msigdb$GO_IONOTROPIC_GLUTAMATE_RECEPTOR_ACTIVITY, go.pathways.msigdb$GO_IONOTROPIC_GLUTAMATE_RECEPTOR_SIGNALING_PATHWAY, go.pathways.msigdb$GO_IONOTROPIC_GLUTAMATE_RECEPTOR_SIGNALING_PATHWAY, go.pathways.msigdb$GO_IONOTROPIC_GLUTAMATE_RECEPTOR_BINDING, go.pathways.msigdb$GO_AMPA_GLUTAMATE_RECEPTOR_CLUSTERING))
vsd_counts.phag_glut %>% filter(gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>% arrange(-astrocyte_ipsc) %>% pull(gene_name)
vsd_counts.phag_glut %>% filter(gene_name %in% glutamate.uptake.go) %>% arrange(-astrocyte_ipsc) %>% pull(gene_name)
vsd_counts.phag_glut %>% filter(gene_name %in% glutamate.receptor.go) %>% arrange(-astrocyte_ipsc) %>% select(gene_name,astrocyte_ipsc)
assay(zhang_patani$vsd) %>% as_tibble(rownames = "gene_id") %>% left_join(gene2ens, by = "gene_id")   %>% filter(gene_name == "GRIA2") %>%
 mutate(astrocyte_ipsc = mean(c_across(starts_with("astrocyte_ipsc")), na.rm = TRUE), CD49_astrocyte_ipsc = mean(c_across(starts_with("CD49_astrocyte_ipsc")), na.rm = TRUE), 
         astrocyte_fetal = mean(c_across(starts_with("astrocyte_fetal")), na.rm = TRUE), astrocyte_adult = mean(c_across(starts_with("astrocyte_adult_temporal")), na.rm = TRUE), 
         oligodendrocyte = mean(c_across(starts_with("oligodendrocyte")), na.rm = TRUE), 
         myeloid = mean(c_across(starts_with("myeloid")), na.rm = TRUE), neuron = mean(c_across(starts_with("neuron")), na.rm = TRUE)) %>% 
  select(gene_name, astrocyte_ipsc, CD49_astrocyte_ipsc, astrocyte_fetal, astrocyte_adult, oligodendrocyte, neuron, myeloid, -gene_id)

```


## Glutamate uptake assay

In control lines only

```{r}
ctrl.glutamate.uptake_assay = read_excel("/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/assay/ctrl_glutamate.uptake_phagocytosis_assay_by_17aug21.xlsx", sheet = "glutamate.uptake") %>% 
  pivot_longer(!c(cellline, experiment), names_to = "treatment", values_to = "intensity") %>% 
  mutate(treatment = gsub("Na_", "Na+ ", treatment), treatment = factor(treatment, levels = c("Untreated", "PDC", "Na+ free")))

# plot fold change glutamate uptake (over Untreated)
ctrl.glutamate.uptake_assay %>% filter(treatment == "Untreated") %>% group_by(experiment) %>% summarise(mean = mean(intensity, na.rm = TRUE)) # mean of CTRL in each experiment
# experiment  mean
#        <dbl> <dbl>
# 1          1  34.8
# 2          2  54.8
# 3          3  43.1
ctrl.glutamate.uptake_assay = ctrl.glutamate.uptake_assay %>% mutate(foldchange = case_when(experiment == 1 ~ intensity / 34.8, experiment == 2 ~ intensity / 54.8, experiment == 3 ~ intensity / 43.1))

# stats on normalised data
ctrl.glutamate.uptake_assay.stats_test <- ctrl.glutamate.uptake_assay %>% wilcox_test(foldchange ~ treatment) %>% add_significance() %>% add_xy_position(x = "treatment")
ctrl.glutamate.uptake_assay.stats_test
# .y.        group1    group2      n1    n2 statistic     p p.adj p.adj.signif y.position groups  xmin  xmax
#   <chr>      <chr>     <chr>    <int> <int>     <dbl> <dbl> <dbl> <chr>             <dbl> <name> <dbl> <dbl>
# 1 foldchange Untreated PDC          9     9        71 0.006 0.012 *                  1.48 <chr ?     1     2
# 2 foldchange Untreated Na+ free     9     9        72 0.004 0.012 *                  1.58 <chr ?     1     3
# 3 foldchange PDC       Na+ free     9     9        48 0.546 0.546 ns                 1.68 <chr ?     2     3

# Box plot
ctrl.glutamate.uptake_assay.boxplot = ggboxplot(ctrl.glutamate.uptake_assay, x="treatment", y = "foldchange", add = "point", color = "treatment") +
  theme_bw() + theme(legend.position = "none", axis.text=element_text(size=10), axis.title=element_text(size=10)) + 
  scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Glutamate~uptake~fold~change)) +
  stat_pvalue_manual(ctrl.glutamate.uptake_assay.stats_test, label = "p.adj.signif", tip.length = 0.01, hide.ns = TRUE, bracket.nudge.y = -0.1)
ctrl.glutamate.uptake_assay.boxplot

```


## RNAseq VCP Volcano

```{r}
immune.up.genes <- patani$res %>% filter(padj < 0.05, log2FoldChange > 1, gene_name %in% all.reactivity.go, !gene_name %in% c("ANGPT1", "PID1", "TXNIP")) %>%  pull(gene_name)
phagocytosis.down.genes <- patani$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>%  pull(gene_name)
glutamate.uptake.down.genes <- patani$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% glutamate.uptake.go) %>%  pull(gene_name)
interesting.gene.labels.filt <- c(phagocytosis.down.genes, glutamate.uptake.down.genes, immune.up.genes, "ASPN", "GJA5", "CALB2", "GABRA2", "GABRB2", "SLC3A2") 

patani.volcano <- volcano_plot_deseq(data = patani$res, labels_list = interesting.gene.labels.filt) + xlab(expression(RNAseq~log[2]~fold~change~VCP:CTRL)) + 
  coord_cartesian(xlim = c(-10,10), ylim = c(0,8)) +
  geom_segment(aes(x = 3, xend = 9, y= 7, yend= 7), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -3, xend = -9, y= 7, yend= 7),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 6, y = 8, label = "Up in VCP", color = "firebrick2", size = 2.8) + annotate("text", x = -6, y = 8, label = "Down in VCP", color = "dodgerblue2", size = 2.8)
patani.volcano

patani$res %>% filter(padj < 0.05, log2FoldChange > 0) # 91
patani$res %>% filter(padj < 0.05, log2FoldChange < 0) # 108

```

## RNAseq VCP GO terms

```{r}
patani.dge_genes <- patani$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") %>% gost()
patani.dge_gprofiles_filt <- patani.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " VCP Down ", query == "query_2" ~ " VCP Up "), term_name = as.factor(term_name)) 
patani.dge_gprofiles_down <- patani.dge_gprofiles_filt %>% filter(query == " VCP Down ")
patani.dge_gprofiles_up <- patani.dge_gprofiles_filt %>% filter(query == " VCP Up ")
paste('"',unique(patani.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"GABA receptor Signaling",
# "integral component of plasma membrane",
"brain development",
"GABA-ergic synapse",
"central nervous system neuron development",
"plasma membrane",
"forebrain development",
"intrinsic component of membrane")
# "cell periphery",
# "plasma membrane region")
patani.dge_gprofiles_filt_down <- patani.dge_gprofiles_filt %>% filter(query == " VCP Down ")  %>% filter(term_name %in% down_list)
paste('"',unique(patani.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"circulatory system process",
"gap junction",
"extracellular matrix structural constituent conferring compression resistance")
# "cardiac conduction system development",
# "Cardiac shunt",
# "animal organ development")
patani.dge_gprofiles_filt_up <- patani.dge_gprofiles_filt %>% filter(query == " VCP Up ")  %>% filter(term_name %in% up_list)
patani.dge_gprofiles_filt_combined <- bind_rows(patani.dge_gprofiles_filt_down, patani.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" VCP Up ", " VCP Down ")))
patani.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", patani.dge_gprofiles_filt_combined$term_name)
patani.dge_gprofiles_filt_combined$term_name <- gsub("central nervous system ", "", patani.dge_gprofiles_filt_combined$term_name)
patani.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", patani.dge_gprofiles_filt_combined$term_name)
patani.go_curated <- curated_profiles(gprofiles = patani.dge_gprofiles_filt_combined) + theme(legend.position = "none", axis.text = element_text(size = 10))
patani.go_curated

# which genes are driving the terms
patani$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
patani$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
patani$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
patani$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)
```

## GSEA: Phagocytosis, Glutamate uptke

```{r}
patani.geneList <- patani$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(patani.geneList) <- patani$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
patani.geneList = sort(patani.geneList, decreasing = TRUE)

# GSEA glutamate uptake
glutamate.uptake_genes.list <- list("glutamate.uptake" = patani$res$gene_name[patani$res$gene_name %in% glutamate.uptake.go])
patani.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = patani.geneList)
patani.glutamate.uptake_fgseaRes
#  pathway       pval       padj   log2err         ES       NES size                              leadingEdge
# 1: glutamate.uptake 0.02476068 0.02476068 0.3524879 -0.3276907 -1.257345  401 KCNA1,PTPRT,GAD2,ADRA1A,KCND2,CACNG5,...
patani.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], patani.geneList) + #labs(subtitle = "VCP Glutamate Uptake GSEA") + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake~GSEA)) + xlab(expression(VCP~vs~CTRL~gene~rank)) +
  annotate("text", x = 1000, y = -0.25, label = paste0("NES = ", round(patani.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(patani.glutamate.uptake_fgseaRes$pval, digits = 3)), size = 3, hjust = 0)
patani.glutamate.gseaplot

```

## Mass spec Volcano & GO

```{r}
# Volcano
mass_spec.res.volcano <- mass_spec.res %>% mutate(direction = case_when(pval < 0.05 & lfc > 0 ~ "upregulated", pval < 0.05 & lfc < 0 ~ "downregulated", TRUE ~ "unchanged"))
mass_spec.volcano <- ggplot(data = mass_spec.res.volcano, aes(x = lfc, y =  -log10(pval), colour = direction)) +  geom_point(size = 0.5) + #xlim(1,5) + ylim(-3,3) + 
  scale_colour_manual( values = c(unchanged = "darkgray", upregulated = "firebrick2", downregulated = "dodgerblue2") ) +  
  theme_bw() +  theme(panel.grid = element_blank(), legend.title = element_blank(), legend.position = "none") + 
  ylab(expression( -log[10]~P~value )) +  xlab(expression( Mass~Spec~log~fold~change~VCP:CTRL )) +
  geom_text_repel(data = filter(mass_spec.res.volcano, pval < 0.05, gene_name %in% all.reactivity.go), aes(x = lfc, y = -log10(pval), label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size=2.5, max.overlaps = Inf) + 
  geom_hline(yintercept = -log10(0.05), linetype = 2) + geom_vline(xintercept =0, linetype = 2) +
  geom_segment(aes(x = 0.8, xend = 2.8, y= 2.8, yend= 2.8), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -0.8, xend = -2.8, y= 2.8, yend= 2.8),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 1.7, y = 3, label = "Up in VCP", color = "firebrick2", size = 2.8) + annotate("text", x = -1.7, y = 3, label = "Down in VCP", color = "dodgerblue2", size = 2.8)
mass_spec.volcano

mass_spec.res.volcano$direction %>% table
# downregulated     unchanged   upregulated 
           # 36          1120             4

# GO terms mass spec
patani.mass_spec.dge_genes <- mass_spec.res %>% filter(pval < 0.05) %>% group_split(lfc > 0) %>%  map("gene_name") # create list of IR up/down & Expression up/down genes
patani.mass_spec.dge_genes <- gost(patani.mass_spec.dge_genes) # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
patani.mass_spec.dge_gprofiles_filt <- patani.mass_spec.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " VCP Down ", query == "query_2" ~ " Up in VCP "), term_name = as.factor(term_name)) 
patani.mass_spec.dge_gprofiles_down <- patani.mass_spec.dge_gprofiles_filt %>% filter(query == " VCP Down ")
patani.mass_spec.dge_gprofiles_up <- patani.mass_spec.dge_gprofiles_filt %>% filter(query == " Up in VCP ")

paste('"',unique(patani.mass_spec.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"hippocampus; glial cells[?Medium]",
"intracellular transport",
"axo-dendritic transport",
"large ribosomal subunit",
"axonal transport",
"neuron projection cytoplasm",
"cell-substrate junction",
"RNA binding",
"focal adhesion",
"cerebellum; cells in molecular layer[?Medium]",
"axon cytoplasm",
"cytoplasm",
"retrograde axonal transport",
"extracellular vesicle")
patani.mass_spec.dge_gprofiles_filt_down <- patani.mass_spec.dge_gprofiles_filt %>% filter(query == " VCP Down ")  %>% filter(term_name %in% down_list)
patani.mass_spec.go_curated <- curated_profiles(gprofiles = patani.mass_spec.dge_gprofiles_filt_down, cols = "dodgerblue2") + theme(legend.position = "none", axis.text = element_text(size = 10))
patani.mass_spec.go_curated

# how many of phagocytosis & glutamate uptake detected proteins are downregulated? 
mass_spec.res %>% filter(gene_name %in% glutamate.uptake.go) # 44
mass_spec.res %>% filter(gene_name %in% glutamate.uptake.go, lfc < 0) # 26 / 44 ()
```

## VCP Glutamate Uptake assay

Calculate fold change from CTRL in each experimental repeat prior to combining.

```{r}
# Glutamate uptake
glutamate.uptake_assay = read_excel("/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/assay/vcp.glutamate.uptake_assay_bc_20aug21.xlsx") %>% 
  mutate(group = case_when(cellline %in% c("CNTRL1", "NCRM1", "VCPF10", "C1", "C5") ~ "CTRL", TRUE ~ "VCP"), group = factor(group, levels = c("CTRL", "VCP")))
glutamate.uptake_assay.long = glutamate.uptake_assay %>% pivot_longer(cols = c(repeat1, repeat2, repeat3), names_to = "repeat", values_to = "intensity")

# # Raw data
# glutamate.uptake_assay.long.plot = ggplot(glutamate.uptake_assay.long, aes(x=cellline, y = intensity, color=cellline)) + 
#   geom_point() +
#   theme_bw() + theme(legend.title = element_blank()) + 
#   # scale_colour_manual(values = c("dodgerblue2", "firebrick2")) +# scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
#    xlab(label = "") + ylab(expression(Glutamate~uptake~"%")) +
#   stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) +  # standard error of mean bars - alternative: stat_summary(fun.data = mean_cl_normal, geom = "errorbar", fun.args = list(mult = 1)) +
#   stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
#   facet_wrap(~experiment)
# glutamate.uptake_assay.long.plot
# # NCRM1 line technical repeats are quite variable, particularly in experiment block 1. 
# # C1 line is quite variable between blocks (very high in block 4).
# 
# # plot technical repeats
# vcp.glutamate.uptake_assay.long.plot = ggplot(glutamate.uptake_assay.long, aes(x=group, y = intensity, color=group)) + 
#   geom_point() +
#   theme_bw() + theme(legend.title = element_blank()) + scale_colour_manual(values = c("dodgerblue2", "firebrick2"), axis.text = element_text(size = 10)) +# scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
#    xlab(label = "") + ylab(expression(Glutamate~uptake~"%")) +
#   stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) +  # standard error of mean bars - alternative: stat_summary(fun.data = mean_cl_normal, geom = "errorbar", fun.args = list(mult = 1)) +
#   stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
#   facet_wrap(~experiment)
# vcp.glutamate.uptake_assay.long.plot

#Normalise intensities between experimental blocks by taking the VCP/CTRL Fold Change in each block, then plot.
glutamate.uptake_assay %>% filter(group == "CTRL") %>% group_by(experiment) %>% summarise(mean = mean(mean, na.rm = TRUE)) # mean of CTRL in each experiment
# experiment  mean
#        <dbl> <dbl>
# 1          1  37.0
# 2          2  50.8
# 3          3  47.5
# 4          4  72.4

glutamate.uptake_assay = glutamate.uptake_assay %>% mutate(foldchange = case_when(experiment == 1 ~ mean / 37, experiment == 2 ~ mean / 50.8, experiment == 3 ~ mean / 47.5, experiment == 4 ~ mean / 72.4))
glutamate.uptake_assay.long = glutamate.uptake_assay.long %>% mutate(foldchange = case_when(experiment == 1 ~ mean / 37, experiment == 2 ~ mean / 50.8, experiment == 3 ~ mean / 47.5, experiment == 4 ~ mean / 72.4))

# stats on normalised data
glutamate.uptake_assay.stats_test <- glutamate.uptake_assay %>% wilcox_test(foldchange ~ group) %>% add_significance() %>% add_xy_position(x = "group")
glutamate.uptake_assay.stats_test

# Box plot
vcp.glutamate.uptake_assay.boxplot = ggboxplot(glutamate.uptake_assay, x="group", y = "foldchange", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none", axis.text = element_text(size = 10)) + 
  scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Glutamate~uptake~fold~change)) +
  stat_pvalue_manual(glutamate.uptake_assay.stats_test, label = "p.signif", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.glutamate.uptake_assay.boxplot

```


## Merge

```{r}
fig1.merged <- ggarrange(
  ggarrange(as.ggplot(astrocyte.marker.heatmap), NULL, as.ggplot(glutamate.uptake.heatmap), ctrl.glutamate.uptake_assay.boxplot, ncol = 4, labels = c("B", "C","","D"), widths = c(0.9,0.06,1.1,0.8)),
  ggarrange(patani.volcano, patani.go_curated, patani.glutamate.gseaplot, ncol = 3, labels = c("E", "F","G"), widths = c(1,0.8,0.6)),
  ggarrange(mass_spec.volcano, patani.mass_spec.go_curated, vcp.glutamate.uptake_assay.boxplot, ncol = 3, labels = c("H","I","J"), widths = c(1,0.8,0.6)),
  nrow = 3, heights = c(1.3,1,1))
# fig1.merged
ggsave(fig1.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig1.merged.png", height = 12, width = 10.5)



# # merge list of heatmaps into single figure
# phagocytosis.glutamate.heatmaps = phagocytosis.heatmap %v% glutamate.uptake.heatmap
# draw(phagocytosis.glutamate.heatmaps)
# phagocytosis.glutamate.heatmaps.grob = grid.grabExpr(draw(phagocytosis.glutamate.heatmaps)) 
# ggsave(phagocytosis.glutamate.heatmaps.grob, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/phagocytosis.glutamate.uptake.heatmaps.png", height = 6, width = 8)

# fig2.merged <- ggarrange(
#   ggarrange(patani.volcano, patani.go_curated, ncol = 2, labels = c("A", "B"), widths = c(1,0.8)),
#   ggarrange(mass_spec.volcano, patani.mass_spec.go_curated, ncol = 2, labels = c("C", "D"), widths = c(1,0.8)),
#   ggarrange(patani.glutamate.gseaplot, patani.phagocytosis.gseaplot, ncol = 2, labels = c("E", "F")),
#   nrow = 3, heights = c(1,1,0.7))
# # fig2.merged
# ggsave(fig2.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig2.merged.png", height = 8, width = 7)


  # ggarrange(gene_sets_sina_plot, mass_spec.gene_sets_sina_plot, ncol = 2, labels = c("C", "D"), widths = c(1,1)),

```


# Fig S2 Morphology


```{r}
# only the 2 GFAP repeats
morphology_assay = read_excel("/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/assay/vcp.morphology_dt_6sep21.xlsx") %>% 
  mutate(group = case_when(cellline %in% c("c1", "c2", "c3", "c4") ~ "CTRL", TRUE ~ "VCP"), group = factor(group, levels = c("CTRL", "VCP")), 
         individual = case_when(cellline %in% c("GLIA", "GLIB") ~ "R191Q", cellline %in% c("CBID", "CBIE") ~ "R155C", TRUE ~ cellline), individual = as.factor(individual), 
         experiment = as.factor(experiment), technical = as.factor(technical))
morphology_assay.mean = morphology_assay %>% group_by(cellline, experiment) %>% summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) %>% ungroup %>% # calculate mean for each cell line repeat
  mutate(group = case_when(cellline %in% c("c1", "c2", "c3", "c4") ~ "CTRL", TRUE ~ "VCP"), group = factor(group, levels = c("CTRL", "VCP")))

```

Experimental repeat & Cell line differences

```{r}
morphology_assay.cell_area.cellline.plot = ggplot(morphology_assay, aes(x=cellline, y = gfap_cell_area, color=cellline)) + geom_point() +  theme_bw() + theme(legend.position="none") + 
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  xlab(label = "") + ylab(expression(Cell~area~um^2)) + facet_wrap(~experiment)
morphology_assay.cell_area.cellline.plot

morphology_assay.cell_roundedness.cellline.plot = ggplot(morphology_assay, aes(x=cellline, y = gfap_cell_roundedness, color=cellline)) + geom_point() +  theme_bw() + theme(legend.position="none") + 
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  xlab(label = "") + ylab(expression(Cell~roundedness)) + facet_wrap(~experiment)
morphology_assay.cell_roundedness.cellline.plot

morphology_assay.cell_length.cellline.plot = ggplot(morphology_assay, aes(x=cellline, y = gfap_cell_length, color=cellline)) + geom_point() +  theme_bw() + theme(legend.position="none") + 
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  xlab(label = "") + ylab(expression(Cell~length~um)) + facet_wrap(~experiment)
morphology_assay.cell_length.cellline.plot

morphology_assay.cell_width.cellline.plot = ggplot(morphology_assay, aes(x=cellline, y = gfap_cell_width, color=cellline)) + geom_point() +  theme_bw() + theme(legend.position="none") + 
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  xlab(label = "") + ylab(expression(Cell~width~um)) + facet_wrap(~experiment)
morphology_assay.cell_width.cellline.plot

ggarrange(morphology_assay.cell_area.cellline.plot, morphology_assay.cell_roundedness.cellline.plot, morphology_assay.cell_length.cellline.plot, morphology_assay.cell_width.cellline.plot)

# take the mean of each technical repeat within repeats
```


VCP vs CTRL comparison using t-test

```{r}
# cell area
morphology_assay.cell_area.stats_test <- morphology_assay.mean %>% t_test(gfap_cell_area ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.cell_area.stats_test

summary(aov(gfap_cell_area ~ group + Error(cellline), data = morphology_assay.mean)) # account for cell line
anova(lme(gfap_cell_area ~ group, random = ~ 1 | cellline, data = morphology_assay.mean))

# standard error bar plot
vcp.morphology_assay.cell_area.plot = ggplot(morphology_assay.mean, aes(x=group, y = gfap_cell_area, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(Cell~area~um^2)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.cell_area.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.cell_area.plot

# Box plot
vcp.morphology_assay.cell_area.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "gfap_cell_area", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Cell~area~um^2)) +
  stat_pvalue_manual(morphology_assay.cell_area.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.cell_area.boxplot

# cell length
morphology_assay.cell_length.stats_test <- morphology_assay.mean %>% t_test(gfap_cell_length ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.cell_length.stats_test

# standard error bar plot
vcp.morphology_assay.cell_length.plot = ggplot(morphology_assay.mean, aes(x=group, y = gfap_cell_length, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(Cell~length~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.cell_length.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.cell_length.plot

# Box plot
vcp.morphology_assay.cell_length.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "gfap_cell_length", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Cell~length~um)) +
  stat_pvalue_manual(morphology_assay.cell_length.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.cell_length.boxplot

# cell width
morphology_assay.cell_width.stats_test <- morphology_assay.mean %>% t_test(gfap_cell_width ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.cell_width.stats_test

# standard error bar plot
vcp.morphology_assay.cell_width.plot = ggplot(morphology_assay.mean, aes(x=group, y = gfap_cell_width, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(Cell~width~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.cell_width.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.cell_width.plot

# Box plot
vcp.morphology_assay.cell_width.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "gfap_cell_width", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Cell~width~um)) +
  stat_pvalue_manual(morphology_assay.cell_width.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.cell_width.boxplot

# cell roundedness
morphology_assay.cell_roundedness.stats_test <- morphology_assay.mean %>% t_test(gfap_cell_roundedness ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.cell_roundedness.stats_test

# standard error bar plot
vcp.morphology_assay.cell_roundedness.plot = ggplot(morphology_assay.mean, aes(x=group, y = gfap_cell_roundedness, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(Cell~roundedness~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.cell_roundedness.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.01) 
vcp.morphology_assay.cell_roundedness.plot

# Box plot
vcp.morphology_assay.cell_roundedness.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "gfap_cell_roundedness", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Cell~roundedness~um)) +
  stat_pvalue_manual(morphology_assay.cell_roundedness.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.01)
vcp.morphology_assay.cell_roundedness.boxplot



# nucleus area
morphology_assay.nucleus_area.stats_test <- morphology_assay.mean %>% t_test(nucleus_area ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.nucleus_area.stats_test

# standard error bar plot
vcp.morphology_assay.nucleus_area.plot = ggplot(morphology_assay.mean, aes(x=group, y = nucleus_area, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(nucleus~area~um^2)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.nucleus_area.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.nucleus_area.plot

# Box plot
vcp.morphology_assay.nucleus_area.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "nucleus_area", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(nucleus~area~um^2)) +
  stat_pvalue_manual(morphology_assay.nucleus_area.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.nucleus_area.boxplot

# nucleus length
morphology_assay.nucleus_length.stats_test <- morphology_assay.mean %>% t_test(nucleus_length ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.nucleus_length.stats_test

# standard error bar plot
vcp.morphology_assay.nucleus_length.plot = ggplot(morphology_assay.mean, aes(x=group, y = nucleus_length, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(nucleus~length~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.nucleus_length.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.nucleus_length.plot

# Box plot
vcp.morphology_assay.nucleus_length.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "nucleus_length", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(nucleus~length~um)) +
  stat_pvalue_manual(morphology_assay.nucleus_length.stats_test, label = "p", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.nucleus_length.boxplot

# nucleus width
morphology_assay.nucleus_width.stats_test <- morphology_assay.mean %>% t_test(nucleus_width ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.nucleus_width.stats_test

# standard error bar plot
vcp.morphology_assay.nucleus_width.plot = ggplot(morphology_assay.mean, aes(x=group, y = nucleus_width, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(nucleus~width~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.nucleus_width.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.nucleus_width.plot

# Box plot
vcp.morphology_assay.nucleus_width.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "nucleus_width", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(nucleus~width~um)) +
  stat_pvalue_manual(morphology_assay.nucleus_width.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.nucleus_width.boxplot

# nucleus roundedness
morphology_assay.nucleus_roundedness.stats_test <- morphology_assay.mean %>% t_test(nucleus_roundedness ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.nucleus_roundedness.stats_test

# standard error bar plot
vcp.morphology_assay.nucleus_roundedness.plot = ggplot(morphology_assay.mean, aes(x=group, y = nucleus_roundedness, color=group)) + geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  xlab(expression()) + ylab(expression(nucleus~roundedness~um)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) + stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) +
  stat_pvalue_manual(morphology_assay.nucleus_roundedness.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.01) 
vcp.morphology_assay.nucleus_roundedness.plot

# Box plot
vcp.morphology_assay.nucleus_roundedness.boxplot = ggboxplot(morphology_assay.mean, x="group", y = "nucleus_roundedness", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(nucleus~roundedness~um)) +
  stat_pvalue_manual(morphology_assay.nucleus_roundedness.stats_test, label = "p", tip.width = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.01)
vcp.morphology_assay.nucleus_roundedness.boxplot

vcp.morphology_assay.plot = ggarrange(vcp.morphology_assay.cell_area.plot, vcp.morphology_assay.cell_roundedness.plot, vcp.morphology_assay.cell_length.plot, vcp.morphology_assay.cell_width.plot, 
          vcp.morphology_assay.nucleus_area.plot, vcp.morphology_assay.nucleus_roundedness.plot, vcp.morphology_assay.nucleus_length.plot, vcp.morphology_assay.nucleus_width.plot,
          nrow = 2, ncol = 4, labels = c("B","C","D","E","F","G","H","I"))
ggsave(vcp.morphology_assay.plot, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/vcp.morphology_assay.plot.png", height = 8, width = 10)

```


Mixed (fixed & random) model (i.e. non linear y = ax + c+ bz) adjustment for cell line https://ourcodingclub.github.io/tutorials/mixed-models/
fixed effect = group (VCP vs control)
random effect = cellline (control for this) - this is a nested (rather than crossed) random effect because of heirachical structure (cell lines are within a mutation group). Ideally has at least 5 levels - variation is modelled through variance (dispersion)
Avoid pseudoreplication of technical repeats that are non-independent data (violates assumption of independance of observations)
Clones of R155C & R191Q are implicit nesting and can be added as an additional factor (individual). Account for differences between cell lines, as well as differences between the genotypes within cell lines

nested random effects = the factor appears ONLY within a particular level of another factor (each genotype belongs to a specific cell line and only to that cell line)
crossed effects = the factor appears in more than one level of another factor (e.g. treatment appearing within more than one cell line).

```{r}
library(lme4)
morphology.cell_area.mixed.lmer <- lmer(gfap_cell_area ~ group + (1|cellline), data = morphology_assay.mean) # account for nested non independent data - ie repeated sampling from same cell lines
morphology.cell_area.mixed.lm <- lm(gfap_cell_area ~ group + cellline, data = morphology_assay.mean) # account for nested non independent data - ie repeated sampling from same cell lines
summary(morphology.cell_area.mixed.lm)

morphology.cell_area.mixed.lmer <- lmer(gfap_cell_area ~ group + (1|cellline/technical), data = morphology_assay) 
morphology.cell_area.mixed.lmer <- lmer(gfap_cell_area ~ group + (1|cellline/experiment/technical), data = morphology_assay) # account for nested non independent data - ie repeated sampling from same cell lines
morphology.cell_area.mixed.lmer <- lmer(gfap_cell_area ~ group + (1|cellline/experiment/technical) + (1|individual), data = morphology_assay)  # also account for genotype (individual)
morphology.cell_area.mixed.lmer <- lmer(gfap_cell_area ~ group + (1|cellline) + (1|individual), data = morphology_assay) # also account for genotype (individual) - remove experiemnt, technical adjustment

anova(morphology.cell_area.mixed.lmer)

summary(morphology.cell_area.mixed.lmer) # is model estimate smaller than its associated error?
plot(morphology.cell_area.mixed.lmer)


summary(aov(gfap_cell_area ~ group + Error(cellline), data = morphology_assay.mean))
anova(lme(gfap_cell_area ~ group, random = ~ 1 | cellline, data = morphology_assay.mean))




# QQplot - plots should fall onto the line
qqnorm(resid(morphology.cell_area.mixed.lmer))
qqline(resid(morphology.cell_area.mixed.lmer)) 
morphology.mixed.model.lm <- lm(gfap_cell_area ~ group + cellline, data = morphology_assay.mean) # estimate difference in area between cell lines
summary(morphology.mixed.model.lm)

# 
ggplot(morphology_assay, aes(x = cellline, y = gfap_cell_area, colour = individual)) +
      facet_wrap(~group) +   # a panel for each mountain range
      geom_point(alpha = 0.5) +
      theme_classic() +
      geom_line(data = cbind(morphology_assay, pred = predict(morphology.cell_area.mixed.lmer)), aes(y = pred), size = 1) +  # adding predicted line from mixed model 
      theme(legend.position = "none") 

# morphology_assay.long = morphology_assay %>% pivot_longer(cols = c(repeat1, repeat2, repeat3), names_to = "repeat", values_to = "intensity")

# Raw data
morphology_assay.long.plot = ggplot(morphology_assay.long, aes(x=cellline, y = intensity, color=cellline)) + 
  geom_point() +
  theme_bw() + theme(legend.title = element_blank()) + 
  # scale_colour_manual(values = c("dodgerblue2", "firebrick2")) +# scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
   xlab(label = "") + ylab(expression(Glutamate~uptake~"%")) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) +  # standard error of mean bars - alternative: stat_summary(fun.data = mean_cl_normal, geom = "errorbar", fun.args = list(mult = 1)) +
  stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  facet_wrap(~experiment)
morphology_assay.long.plot
# NCRM1 line technical repeats are quite variable, particularly in experiment block 1. 
# C1 line is quite variable between blocks (very high in block 4).

# plot technical repeats
vcp.morphology_assay.long.plot = ggplot(morphology_assay.long, aes(x=group, y = intensity, color=group)) + 
  geom_point() +
  theme_bw() + theme(legend.title = element_blank()) + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) +# scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
   xlab(label = "") + ylab(expression(Glutamate~uptake~"%")) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) +  # standard error of mean bars - alternative: stat_summary(fun.data = mean_cl_normal, geom = "errorbar", fun.args = list(mult = 1)) +
  stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  facet_wrap(~experiment)
vcp.morphology_assay.long.plot
```

Normalise intensities between experimental blocks by taking the VCP/CTRL Fold Change in each block, then plot.

```{r}
morphology_assay %>% filter(group == "CTRL") %>% group_by(experiment) %>% summarise(mean = mean(mean, na.rm = TRUE)) # mean of CTRL in each experiment
# experiment  mean
#        <dbl> <dbl>
# 1          1  37.0
# 2          2  50.8
# 3          3  47.5
# 4          4  72.4

morphology_assay = morphology_assay %>% mutate(foldchange = case_when(experiment == 1 ~ mean / 37, experiment == 2 ~ mean / 50.8, experiment == 3 ~ mean / 47.5, experiment == 4 ~ mean / 72.4))
morphology_assay.long = morphology_assay.long %>% mutate(foldchange = case_when(experiment == 1 ~ mean / 37, experiment == 2 ~ mean / 50.8, experiment == 3 ~ mean / 47.5, experiment == 4 ~ mean / 72.4))

# stats on normalised data
morphology_assay.stats_test <- morphology_assay %>% wilcox_test(foldchange ~ group) %>% add_significance() %>% add_xy_position(x = "group")
morphology_assay.stats_test

# plot standard error bars
vcp.morphology_assay.plot = ggplot(morphology_assay, aes(x=group, y = foldchange, color=group)) + 
  geom_point() + 
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
   xlab(expression()) + ylab(expression(Glutamate~uptake~fold~change)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult=1), geom="errorbar", width=0.4, position=position_dodge(0.8)) +  # standard error of mean bars - alternative: stat_summary(fun.data = mean_cl_normal, geom = "errorbar", fun.args = list(mult = 1)) +
  stat_summary(fun=mean, geom="crossbar", position=position_dodge(0.8)) + 
  stat_pvalue_manual(morphology_assay.stats_test, label = "p.signif", tip.length = 0.01, hide.ns = TRUE, bracket.nudge.y = -0.1) 
vcp.morphology_assay.plot

# Box plot
vcp.morphology_assay.boxplot = ggboxplot(morphology_assay, x="group", y = "foldchange", add = "point", color = "group") +
  theme_bw() + theme(legend.position = "none") + scale_colour_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2", "forestgreen")) +
  xlab(expression()) + ylab(expression(Glutamate~uptake~fold~change)) +
  stat_pvalue_manual(morphology_assay.stats_test, label = "p.signif", tip.length = 0.01, hide.ns = FALSE, bracket.nudge.y = -0.1)
vcp.morphology_assay.boxplot

```

# Table S2 Mass spec results

```{r}
# DEP proteomics
mass_spec_ac <- read.table("/camp/home/ziffo/home/projects/astrocyte-meta-analysis/expression/mass-spectrometry/ac_vcp_fractions_massspec_protein_groups.txt", sep = '\t',header = TRUE)
mass_spec_ac$Gene.names %>% duplicated() %>% any()
mass_spec_ac %>% group_by(Gene.names) %>% dplyr::summarize(frequency = dplyr::n()) %>%  arrange(desc(frequency)) %>% filter(frequency > 1) # for genes without an annotated genename use the Uniprot ID
mass_spec_ac_all <- make_unique(mass_spec_ac, "Gene.names", "Protein.IDs", delim = ";")
mass_spec_ac_all$name %>% duplicated() %>% any()
# Generate a SummarizedExperiment object using an experimental design
LFQ_columns <- grep("LFQ.", colnames(mass_spec_ac_all)) # get LFQ column numbers
experimental_design <- data.frame("label" = c("C1_01","C1_02","C1_03","C5_01","C5_02","C5_03","CCbie_01","CCbie_02","CCbie_03","CGlia_01","CGlia_02","CGlia_03",
                                   "N1_01","N1_02","N1_03","N5_01","N5_02","N5_03","NCbie_01","NCbie_02","NCbie_03", "NGlia_01","NGlia_02","NGlia_03"),
                       "condition" = c("ctrl","ctrl","ctrl","ctrl","ctrl","ctrl","vcp","vcp","vcp","vcp","vcp","vcp",
                                       "ctrl","ctrl","ctrl","ctrl","ctrl","ctrl","vcp","vcp","vcp", "vcp","vcp","vcp"),
                       "replicate"= c("1","2","3","4","5","6","1","2","3","4","5","6",
                                      "7","8","9","10","11","12","7","8","9", "10","11","12"))
data_se <- make_se(mass_spec_ac_all, LFQ_columns, experimental_design) # create summarised experiment - this log2 transforms assay data
data_filt <- filter_missval(data_se, thr = 12) # # Less stringent filtering - Filter proteins identified in 1/6 replicates of at least one condition 1160 / 1160
data_norm <- normalize_vsn(data_filt) # normalise with VST
data_imp <- impute(data_norm, fun = "MinProb", q = 0.01) # Impute missing data using random draws from a Gaussian distribution centered around a minimal value (for MNAR)
data_diff <- test_diff(data_imp, type = "control", control = "ctrl") # Differential enrichment analysis - linear models with empirical Bayes, utilises limma. specify the control sample.
dep <- add_rejections(data_diff, alpha = 0.05)
data_results <- get_results(dep) # Generate a results table
mass_spec.res <- select(data_results, gene_name = name, ID, pval = vcp_vs_ctrl_p.val, lfc = vcp_vs_ctrl_ratio)
# saveRDS(mass_spec.res, "/camp/lab/luscomben/home/users/ziffo/projects/astrocyte-a1-als-meta/expression/mass-spec/mass_spec.res_vcp_vs_ctrl.rds")
write_csv(mass_spec.res, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/mass-spec/TableS2.mass_spec.csv")


mass_spec.res %>% filter(pval < 0.05) # 40
mass_spec.res %>% filter(pval < 0.05, lfc > 0) #4
mass_spec.res %>% filter(pval < 0.05, lfc < 0) #36

mass_spec.res %>% filter(gene_name %in% glutamate.uptake.go) #44
mass_spec.res %>% filter(gene_name %in% glutamate.uptake.go, lfc < 0) # 26

```

# Fig S3 C9orf72 & SOD1 & FUS

## C9orf72 Birger

### Volcano

```{r}
# Volcano
interesting.gene.labels <- birger$res %>% filter(padj < 0.001, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go)) %>% pull(gene_name) # all.reactivity.go
immune.up.genes <- birger$res %>% filter(padj < 0.05, log2FoldChange > 1, gene_name %in% all.reactivity.go, !gene_name %in% c("ANGPT1", "PID1", "TXNIP")) %>%  pull(gene_name)
phagocytosis.down.genes <- birger$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>%  pull(gene_name)
glutamate.uptake.down.genes <- birger$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% glutamate.uptake.go) %>%  pull(gene_name)
interesting.gene.labels.filt <- c(phagocytosis.down.genes, glutamate.uptake.down.genes, immune.up.genes, "ASPN", "GJA5", "CALB2", "GABRA2", "GABRB2", "SLC3A2") 

birger.volcano <- volcano_plot_deseq(data = birger$res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~C9orf72:CTRL)) + 
  coord_cartesian(xlim = c(-10,10), ylim = c(0,25)) +
  geom_segment(aes(x = 3, xend = 9, y= 23, yend= 23), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -3, xend = -9, y= 23, yend= 23),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 6, y = 25, label = "Up in C9orf72", color = "firebrick2", size = 2.8) + annotate("text", x = -6, y = 25, label = "Down in C9orf72", color = "dodgerblue2", size = 2.8)
birger.volcano
```

### GO terms

```{r}
birger.dge_genes <- birger$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") # create list of IR up/down & Expression up/down genes
birger.dge_genes <- gost(birger.dge_genes) # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
birger.dge_gprofiles_filt <- birger.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in C9orf72 ", query == "query_2" ~ " Up in C9orf72 "), term_name = as.factor(term_name)) 
birger.dge_gprofiles_down <- birger.dge_gprofiles_filt %>% filter(query == " Down in C9orf72 ")
birger.dge_gprofiles_up <- birger.dge_gprofiles_filt %>% filter(query == " Up in C9orf72 ")
paste('"',unique(birger.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
# "Senescence-Associated Secretory Phenotype (SASP)",
"synapse",
"chromatin assembly",
"Oxidative Stress Induced Senescence",
"neuron differentiation",
"neuron projection",
"DNA methylation",
"chromosome organization",
"generation of neurons",
"nervous system development",
"mitotic cell cycle")
birger.dge_gprofiles_filt_down <- birger.dge_gprofiles_filt %>% filter(query == " Down in C9orf72 ")  %>% filter(term_name %in% down_list)

paste('"',unique(birger.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"integrin binding",
"actin cytoskeleton",
"response to wounding",
"anchoring junction",
"Collagen degradation",
# "regulation of cellular component movement",
"Collagen formation",
"cell adhesion",
"collagen fibril organization",
"endoplasmic reticulum lumen",
"extracellular matrix")
birger.dge_gprofiles_filt_up <- birger.dge_gprofiles_filt %>% filter(query == " Up in C9orf72 ")  %>% filter(term_name %in% up_list)
birger.dge_gprofiles_filt_combined <- bind_rows(birger.dge_gprofiles_filt_down, birger.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in C9orf72 ", " Down in C9orf72 ")))
birger.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", birger.dge_gprofiles_filt_combined$term_name)
birger.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", birger.dge_gprofiles_filt_combined$term_name)
birger.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", birger.dge_gprofiles_filt_combined$term_name)
birger.go_curated <- curated_profiles(gprofiles = birger.dge_gprofiles_filt_combined) + theme(legend.position = "none")
birger.go_curated

# which genes are driving the terms
birger$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
birger$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
birger$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
birger$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)
```

### GSEA: Glutamate uptake

```{r}
# GSEA phagocytosis
birger.geneList <- birger$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(birger.geneList) <- birger$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
birger.geneList = sort(birger.geneList, decreasing = TRUE)
glutamate.uptake_genes.list <- list("glutamate.uptake" = birger$res$gene_name[birger$res$gene_name %in% glutamate.uptake.go])
birger.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = birger.geneList)
birger.glutamate.uptake_fgseaRes
#             pathway         pval         padj   log2err         ES       NES size
# 1: glutamate.uptake 4.468517e-07 4.468517e-07 0.6749629 -0.3842181 -1.690604  402
birger.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], birger.geneList)  + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(C9orf72)) +
  annotate("text", x = 100, y = -0.25, label = paste0("NES = ", round(birger.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(birger.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
birger.glutamate.gseaplot

```

## SOD1 Tyzack

### Volcano

```{r}
# Volcano
interesting.gene.labels <- tyzack$res %>% filter(-log10(padj) > 10, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go)) %>% pull(gene_name)
immune.up.genes <- tyzack$res %>% filter(padj < 0.05, log2FoldChange > 1, gene_name %in% all.reactivity.go, !gene_name %in% c("ANGPT1", "PID1", "TXNIP")) %>%  pull(gene_name)
phagocytosis.down.genes <- tyzack$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>%  pull(gene_name)
glutamate.uptake.down.genes <- tyzack$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% glutamate.uptake.go) %>%  pull(gene_name)
interesting.gene.labels.filt <- c(phagocytosis.down.genes, glutamate.uptake.down.genes, immune.up.genes, "ASPN", "GJA5", "CALB2", "GABRA2", "GABRB2", "SLC3A2") 

tyzack.volcano <- volcano_plot_deseq(data = tyzack$res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~SOD1:CTRL)) + 
  coord_cartesian(xlim = c(-10,10), ylim = c(0,50)) +
  geom_segment(aes(x = 3, xend = 9, y= 45, yend= 45), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -3, xend = -9, y= 45, yend= 45),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 6, y = 49, label = "Up in SOD1", color = "firebrick2", size = 2.8) + annotate("text", x = -6, y = 49, label = "Down in SOD1", color = "dodgerblue2", size = 2.8)
tyzack.volcano
```

### GO terms

```{r}
tyzack.dge_genes <- tyzack$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") # create list of IR up/down & Expression up/down genes
tyzack.dge_genes <- gost(tyzack.dge_genes) # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
tyzack.dge_gprofiles_filt <- tyzack.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in SOD1 ", query == "query_2" ~ " Up in SOD1 "), term_name = as.factor(term_name)) 
tyzack.dge_gprofiles_down <- tyzack.dge_gprofiles_filt %>% filter(query == " Down in SOD1 ")
tyzack.dge_gprofiles_up <- tyzack.dge_gprofiles_filt %>% filter(query == " Up in SOD1 ")
paste('"',unique(tyzack.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"glutamatergic synapse",
"dendrite",
"cell-cell signaling",
"axon",
"synaptic signaling",
"neuron projection",
"nervous system development",
"synapse")
tyzack.dge_gprofiles_filt_down <- tyzack.dge_gprofiles_filt %>% filter(query == " Down in SOD1 ")  %>% filter(term_name %in% down_list)
paste('"',unique(tyzack.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"integrin binding",
"actin cytoskeleton",
"response to wounding",
"anchoring junction",
"Collagen degradation",
# "regulation of cellular component movement",
"Collagen formation",
"cell adhesion",
"collagen fibril organization",
"endoplasmic reticulum lumen",
"extracellular matrix")
tyzack.dge_gprofiles_filt_up <- tyzack.dge_gprofiles_filt %>% filter(query == " Up in SOD1 ")  %>% filter(term_name %in% up_list)
tyzack.dge_gprofiles_filt_combined <- bind_rows(tyzack.dge_gprofiles_filt_down, tyzack.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in SOD1 ", " Down in SOD1 ")))
tyzack.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", tyzack.dge_gprofiles_filt_combined$term_name)
tyzack.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", tyzack.dge_gprofiles_filt_combined$term_name)
tyzack.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", tyzack.dge_gprofiles_filt_combined$term_name)
tyzack.go_curated <- curated_profiles(gprofiles = tyzack.dge_gprofiles_filt_combined) + theme(legend.position = "none")
tyzack.go_curated

# which genes are driving the terms
tyzack$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
tyzack$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
tyzack$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
tyzack$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)

```

### GSEA: Glutamate uptake

```{r}
tyzack.geneList <- tyzack$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(tyzack.geneList) <- tyzack$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
tyzack.geneList = sort(tyzack.geneList, decreasing = TRUE)
glutamate.uptake_genes.list <- list("glutamate.uptake" = tyzack$res$gene_name[tyzack$res$gene_name %in% glutamate.uptake.go])
tyzack.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = tyzack.geneList)
tyzack.glutamate.uptake_fgseaRes
# pathway  pval  padj log2err         ES       NES size
# 1: glutamate.uptake 1e-10 1e-10      NA -0.6068929 -2.474473  397
tyzack.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], tyzack.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(SOD1)) +  
  annotate("text", x = 100, y = -0.45, label = paste0("NES = ", round(tyzack.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(tyzack.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
tyzack.glutamate.gseaplot


```

## FUS neyrinck

### Volcano

```{r}
# Volcano
interesting.gene.labels <- neyrinck$res %>% filter(-log10(padj) > 10, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go)) %>% pull(gene_name)
immune.up.genes <- neyrinck$res %>% filter(padj < 0.05, log2FoldChange > 1, gene_name %in% all.reactivity.go, !gene_name %in% c("ANGPT1", "PID1", "TXNIP")) %>%  pull(gene_name)
phagocytosis.down.genes <- neyrinck$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>%  pull(gene_name)
glutamate.uptake.down.genes <- neyrinck$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% glutamate.uptake.go) %>%  pull(gene_name)
interesting.gene.labels.filt <- c(phagocytosis.down.genes, glutamate.uptake.down.genes, immune.up.genes, "ASPN", "GJA5", "CALB2", "GABRA2", "GABRB2", "SLC3A2") 

neyrinck.volcano <- volcano_plot_deseq(data = neyrinck$res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~FUS:CTRL)) + 
  coord_cartesian(xlim = c(-10,10), ylim = c(0,40)) +
  geom_segment(aes(x = 3, xend = 9, y= 36, yend= 36), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -3, xend = -9, y= 36, yend= 36),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 6, y = 39, label = "Up in FUS", color = "firebrick2", size = 2.8) + annotate("text", x = -6, y = 39, label = "Down in FUS", color = "dodgerblue2", size = 2.8)
neyrinck.volcano
```

### GO terms

```{r}
neyrinck.dge_genes <- neyrinck$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") # create list of IR up/down & Expression up/down genes
neyrinck.dge_genes <- gost(neyrinck.dge_genes) # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
neyrinck.dge_gprofiles_filt <- neyrinck.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in FUS ", query == "query_2" ~ " Up in FUS "), term_name = as.factor(term_name)) 
neyrinck.dge_gprofiles_down <- neyrinck.dge_gprofiles_filt %>% filter(query == " Down in FUS ")
neyrinck.dge_gprofiles_up <- neyrinck.dge_gprofiles_filt %>% filter(query == " Up in FUS ")
paste('"',unique(neyrinck.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"synaptic signaling",
"glutamatergic synapse",
"axon",
# "cerebral cortex",
"trans-synaptic signaling",
"dendrite",
"cell-cell signaling",
"neurogenesis",
# "regulation of signaling",
"somatodendritic compartment",
# "protein binding",
"nervous system development",
"neuron projection",
"synapse")
neyrinck.dge_gprofiles_filt_down <- neyrinck.dge_gprofiles_filt %>% filter(query == " Down in FUS ")  %>% filter(term_name %in% down_list)
paste('"',unique(neyrinck.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
# "integrin binding",
"actin cytoskeleton",
"response to wounding",
"anchoring junction",
"Collagen degradation",
"focal adhesion",
"collagen-containing extracellular matrix",
"collagen fibril organization",
"cell adhesion",
"biological adhesion",
"Collagen formation",
"endoplasmic reticulum lumen",
"endomembrane system",
"extracellular matrix",
"endoplasmic reticulum")#,
# "extracellular matrix organization")
neyrinck.dge_gprofiles_filt_up <- neyrinck.dge_gprofiles_filt %>% filter(query == " Up in FUS ")  %>% filter(term_name %in% up_list)
neyrinck.dge_gprofiles_filt_combined <- bind_rows(neyrinck.dge_gprofiles_filt_down, neyrinck.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in FUS ", " Down in FUS ")))
# neyrinck.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", neyrinck.dge_gprofiles_filt_combined$term_name)
# neyrinck.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", neyrinck.dge_gprofiles_filt_combined$term_name)
neyrinck.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", neyrinck.dge_gprofiles_filt_combined$term_name)
neyrinck.go_curated <- curated_profiles(gprofiles = neyrinck.dge_gprofiles_filt_combined) + theme(legend.position = "none")
neyrinck.go_curated

# which genes are driving the terms
neyrinck$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
neyrinck$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
neyrinck$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
neyrinck$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)

```

### GSEA: Glutamate uptake

```{r}
neyrinck.geneList <- neyrinck$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(neyrinck.geneList) <- neyrinck$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
neyrinck.geneList = sort(neyrinck.geneList, decreasing = TRUE)
glutamate.uptake_genes.list <- list("glutamate.uptake" = neyrinck$res$gene_name[neyrinck$res$gene_name %in% glutamate.uptake.go])
neyrinck.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = neyrinck.geneList)
neyrinck.glutamate.uptake_fgseaRes
# pathway  pval  padj log2err         ES       NES size
# 1: glutamate.uptake 1e-10 1e-10      NA -0.6068929 -2.474473  397
neyrinck.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], neyrinck.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + 
  annotate("text", x = 100, y = -0.25, label = paste0("NES = ", round(neyrinck.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(neyrinck.glutamate.uptake_fgseaRes$pval, digits = 3)), size = 3, hjust = 0) +
  ylab(expression(Glutamate~Uptake)) + xlab(expression(FUS))
neyrinck.glutamate.gseaplot

```

## Overlap VCP, C9orf72 & SOD1

```{r}
patani.res.dge.up <- patani$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
patani.res.dge.down <- patani$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
tyzack.res.dge.up <- tyzack$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
tyzack.res.dge.down <- tyzack$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
birger.res.dge.up <- birger$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
birger.res.dge.down <- birger$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
neyrinck.res.dge.up <- neyrinck$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
neyrinck.res.dge.down <- neyrinck$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
patani.tyzack.birger.neyrinck.up_genes <- list("VCP" = patani.res.dge.up, "SOD1" = tyzack.res.dge.up, "C9orf72" = birger.res.dge.up, "FUS" = neyrinck.res.dge.up)
patani.tyzack.birger.neyrinck.down_genes <- list("VCP" = patani.res.dge.down, "SOD1" = tyzack.res.dge.down, "C9orf72" = birger.res.dge.down, "FUS" = neyrinck.res.dge.down)
patani.tyzack.birger.neyrinck_venn_up <- ggvenn(patani.tyzack.birger.neyrinck.up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen", "gold2"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.7) + labs(subtitle = "Overlap Up")  + theme(plot.subtitle = element_text(hjust = 0.5, colour = "firebrick2"), plot.margin = unit(c(0, -1, -1, -1), "lines"))
patani.tyzack.birger.neyrinck_venn_up
patani.tyzack.birger.neyrinck_venn_down <- ggvenn(patani.tyzack.birger.neyrinck.down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen", "gold2"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.7) + labs(subtitle = "Overlap Down") + theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, -1, -1), "lines"))
patani.tyzack.birger.neyrinck_venn_down
patani.tyzack.birger.neyrinck_venn = ggarrange(patani.tyzack.birger.neyrinck_venn_up, patani.tyzack.birger.neyrinck_venn_down, row = 2, ncol = 1)
patani.tyzack.birger.neyrinck_venn

# Fisher exact overlap test
unique(c(birger.res.dge.up, patani.res.dge.up)) # 923
DGEup_C9ORF72_VCP <- birger.res.dge.up[birger.res.dge.up %in% patani.res.dge.up] # 15 # 1.6%
genome.size <- patani$res %>% distinct(gene_name) %>% nrow
go.obj <- newGeneOverlap(patani.res.dge.up,
                         birger.res.dge.up,
                         genome.size=genome.size)
testGeneOverlap(go.obj)

# GeneOverlap object:
# listA size=91
# listB size=847
# Intersection size=15
# Overlapping p-value=2.7e-12
# Jaccard Index=0.0

unique(c(birger.res.dge.down, patani.res.dge.down)) # 1087 
DGEdown_C9ORF72_VCP <- birger.res.dge.down[birger.res.dge.down %in% patani.res.dge.down] # 10 0.92%
go.obj <- newGeneOverlap(patani.res.dge.down,
                         birger.res.dge.down,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=108
# listB size=989
# Intersection size=10
# Overlapping p-value=1.2e-05
# Jaccard Index=0.0

unique(c(tyzack.res.dge.up, patani.res.dge.up)) # 1381
DGEup_SOD1_VCP <- tyzack.res.dge.up[tyzack.res.dge.up %in% patani.res.dge.up] # 15 1.1%
go.obj <- newGeneOverlap(patani.res.dge.up,
                         tyzack.res.dge.up,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=91
# listB size=1305
# Intersection size=15
# Overlapping p-value=1.1e-09
# Jaccard Index=0.0

unique(c(tyzack.res.dge.down, patani.res.dge.down)) # 2013 
DGEdown_SOD1_VCP <- tyzack.res.dge.down[tyzack.res.dge.down %in% patani.res.dge.down] # 18 0.9%
go.obj <- newGeneOverlap(patani.res.dge.down,
                         tyzack.res.dge.down,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=108
# listB size=1923
# Intersection size=18
# Overlapping p-value=9e-09
# Jaccard Index=0.0

unique(c(neyrinck.res.dge.up, patani.res.dge.up)) # 1418
DGEup_FUS_VCP <- neyrinck.res.dge.up[neyrinck.res.dge.up %in% patani.res.dge.up] # 19 
newGeneOverlap(patani.res.dge.up, neyrinck.res.dge.up, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=91
# listB size=1346
# Intersection size=19
# Overlapping p-value=1.3e-13
# Jaccard Index=0.0

unique(c(neyrinck.res.dge.down, patani.res.dge.down)) # 1742
DGEdown_FUS_VCP <- neyrinck.res.dge.down[neyrinck.res.dge.down %in% patani.res.dge.down] # 26 
newGeneOverlap(patani.res.dge.down, neyrinck.res.dge.down, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=108
# listB size=1660
# Intersection size=26
# Overlapping p-value=1.6e-17
# Jaccard Index=0.0

DGEup_C9orf72_VCP_SOD1 = DGEup_C9ORF72_VCP[DGEup_C9ORF72_VCP %in% DGEup_SOD1_VCP] # "PLN"    "GJB2"   "GATD3A" "IGFBP5"
DGEdown_C9orf72_VCP_SOD1 = DGEdown_C9ORF72_VCP[DGEdown_C9ORF72_VCP %in% DGEdown_SOD1_VCP] #"RYR2"   "BRINP2" "LRRC3B" "MOB3B" 

DGEup_C9orf72_VCP_SOD1[DGEup_C9orf72_VCP_SOD1 %in% DGEup_FUS_VCP] # GJB2
DGEdown_C9orf72_VCP_SOD1[DGEdown_C9orf72_VCP_SOD1 %in% DGEdown_FUS_VCP] #"LRRC3B" "MOB3B" 

# Chi-squared 3 way overlap
list1 <- unique(patani.res.dge.up[!is.na(patani.res.dge.up)])
list2 <- unique(tyzack.res.dge.up[!is.na(tyzack.res.dge.up)])
list3 <- unique(birger.res.dge.up[!is.na(birger.res.dge.up)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 0.001218456

list1 <- unique(patani.res.dge.down[!is.na(patani.res.dge.down)])
list2 <- unique(tyzack.res.dge.down[!is.na(tyzack.res.dge.down)])
list3 <- unique(birger.res.dge.down[!is.na(birger.res.dge.down)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 0.02202255



IRdown_DGEup_SOD1_VCP <- IRdown_DGEup_SOD1[IRdown_DGEup_SOD1 %in% IRdown_DGEup_VCP]
IRdown_DGEup_C9ORF72_VCP <- IRdown_DGEup_C9ORF72[IRdown_DGEup_C9ORF72 %in% IRdown_DGEup_VCP]
IRdown_DGEup_SOD1_VCP_C9ORF72 <- IRdown_DGEup_SOD1_VCP[IRdown_DGEup_SOD1_VCP %in% IRdown_DGEup_C9ORF72]
IRdown_DGEup_SOD1_VCP_C9ORF72[IRdown_DGEup_SOD1_VCP_C9ORF72 %in% all.reactivity.go] # 4 are relevent to reactivity "FLNA"  "PLOD3" "MRC2"  "ACTN4"

IRdown_A1_ALS[IRdown_A1_ALS %in% all.reactivity.go] # "HSPG2"   "PSMD11"  "NFKBIZ"  "DNAJC2"  "ERF"     "TINF2"   "OSMR"    "TNIK"    "ILK"     "NUP188"  "STIP1"   "TBK1"    "MCAM"    "ARHGEF2" "NT5C3A"  "FN1"     "POLR3C"


# ggsave(patani.tyzack.birger.neyrinck_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/patani.tyzack.birger.neyrinck_venn_up.png", height = 5, width = 5)
# ggsave(patani.tyzack.birger.neyrinck_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/patani.tyzack.birger.neyrinck_venn_down.png", height = 5, width = 5)

# barbar.tyzack.up_genes <- list("A1 up" = barbar.res.dge.up, "SOD1 up" = tyzack.res.dge.up)
# barbar.tyzack.down_genes <- list("A1 down" = barbar.res.dge.down, "SOD1 down" = tyzack.res.dge.down)
# barbar.birger.up_genes <- list("A1 up" = barbar.res.dge.up, "C9orf72 up" = birger.res.dge.up)
# barbar.birger.down_genes <- list("A1 down" = barbar.res.dge.down, "C9orf72 down" = birger.res.dge.down)

# tyzack_barbar_venn_up <- ggvenn(barbar.tyzack.up_genes, fill_color = c("dodgerblue3", "firebrick1"),show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# tyzack_barbar_venn_up
# tyzack_barbar_venn_down <- ggvenn(barbar.tyzack.down_genes, fill_color = c("dodgerblue3", "firebrick1"), show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# tyzack_barbar_venn_down
# ggsave(tyzack_barbar_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/tyzack_barbar_venn_up.png", height = 3, width = 3)
# ggsave(tyzack_barbar_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/tyzack_barbar_venn_down.png", height = 3, width = 3)
# 
# birger_barbar_venn_up <- ggvenn(barbar.birger.up_genes, fill_color = c("dodgerblue3", "firebrick1"),show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# birger_barbar_venn_up
# birger_barbar_venn_down <- ggvenn(barbar.birger.down_genes, fill_color = c("dodgerblue3", "firebrick1"), show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# birger_barbar_venn_down
# ggsave(birger_barbar_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/birger_barbar_venn_up.png", height = 3, width = 3)
# ggsave(birger_barbar_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/birger_barbar_venn_down.png", height = 3, width = 3)
```

## Merge

```{r}
# birger.tyzack.neyrink.gsea = ggarrange(birger.glutamate.gseaplot, tyzack.glutamate.gseaplot, neyrinck.glutamate.gseaplot, als_datasets.glutamate.uptake.gseaplot, nrow = 2, ncol = 2)
# birger.phagocytosis.gseaplot, tyzack.phagocytosis.gseaplot, neyrinck.phagocytosis.gseaplot,

figS3.merged <- ggarrange(
  ggarrange(birger.volcano, tyzack.volcano, neyrinck.volcano, ncol = 3, labels = c("A", "B", "C")),
  ggarrange(birger.go_curated, tyzack.go_curated, neyrinck.go_curated, ncol = 3, labels = c("D", "E", "F")),
  ggarrange(birger.glutamate.gseaplot, tyzack.glutamate.gseaplot, neyrinck.glutamate.gseaplot, ncol = 3, labels = c("G","H","I")),  
  ggarrange(patani.tyzack.birger.neyrinck_venn_up, patani.tyzack.birger.neyrinck_venn_down, ncol = 2, labels = c("J", "K")),
  nrow = 4,heights = c(1,0.9,0.9,1))
# figS3.merged
ggsave(figS3.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS3.merged.png", height = 13, width = 10)


  
patani.birger.tyzack.gseaplot.merged = ggarrange(patani.phagocytosis.gseaplot, patani.glutamate.gseaplot, birger.phagocytosis.gseaplot, birger.glutamate.gseaplot, tyzack.phagocytosis.gseaplot, tyzack.glutamate.gseaplot, ncol = 2, nrow = 3, labels = )
ggsave(patani.birger.tyzack.gseaplot.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/patani.birger.tyzack.gseaplot.merged.png", height = 8, width = 8)

```

# Table S3. DEG overlap in hiPSC ALS datasets

```{r}
patani.dge <- patani$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.VCP = log2FoldChange, FDR.VCP = padj) %>% mutate(direction.VCP = case_when(FDR.VCP < 0.05 & log2FC.VCP > 0 ~ "up", FDR.VCP < 0.05 & log2FC.VCP < 0 ~ "down", TRUE ~ "non-significant"))
birger.dge <- birger$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.C9orf72 = log2FoldChange, FDR.C9orf72 = padj) %>% mutate(direction.C9orf72 = case_when(FDR.C9orf72 < 0.05 & log2FC.C9orf72 > 0 ~ "up", FDR.C9orf72 < 0.05 & log2FC.C9orf72 < 0 ~ "down", TRUE ~ "non-significant"))
tyzack.dge <- tyzack$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj) %>% mutate(direction.SOD1 = case_when(FDR.SOD1 < 0.05 & log2FC.SOD1 > 0 ~ "up", FDR.SOD1 < 0.05 & log2FC.SOD1 < 0 ~ "down", TRUE ~ "non-significant"))
neyrinck.dge <- neyrinck$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.FUS = log2FoldChange, FDR.FUS = padj) %>% mutate(direction.FUS = case_when(FDR.FUS < 0.05 & log2FC.FUS > 0 ~ "up", FDR.FUS < 0.05 & log2FC.FUS < 0 ~ "down", TRUE ~ "non-significant"))
als_datasets_merged.dge <- patani.dge %>% full_join(tyzack.dge) %>% full_join(birger.dge) %>% full_join(neyrinck.dge) %>% 
  mutate(overlap = case_when(FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP > 0 & log2FC.C9orf72 > 0 & log2FC.SOD1 > 0 & log2FC.FUS > 0 ~ "overlapping up",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP < 0 & log2FC.C9orf72 < 0 & log2FC.SOD1 < 0 & log2FC.FUS < 0 ~ "overlapping down",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & log2FC.VCP > 0 & log2FC.C9orf72 > 0 & log2FC.SOD1 > 0 ~ "VCP C9orf72 SOD1 up",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & log2FC.VCP < 0 & log2FC.C9orf72 < 0 & log2FC.SOD1 < 0 ~ "VCP C9orf72 SOD1 down",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP > 0 & log2FC.C9orf72 > 0 & log2FC.FUS > 0 ~ "VCP C9orf72 FUS up",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP < 0 & log2FC.C9orf72 < 0 & log2FC.FUS < 0 ~ "VCP C9orf72 FUS down",
                             FDR.VCP < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP > 0 & log2FC.SOD1 > 0 & log2FC.FUS > 0 ~ "VCP SOD1 FUS up",
                             FDR.VCP < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.VCP < 0 & log2FC.SOD1 < 0 & log2FC.FUS < 0 ~ "VCP SOD1 FUS down",
                             FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.C9orf72 > 0 & log2FC.SOD1 > 0 & log2FC.FUS > 0 ~ "C9orf72 SOD1 FUS up",
                             FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.C9orf72 < 0 & log2FC.SOD1 < 0 & log2FC.FUS < 0 ~ "C9orf72 SOD1 FUS down",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & log2FC.VCP > 0 & log2FC.C9orf72 > 0 ~ "VCP C9orf72 up",
                             FDR.VCP < 0.05 & FDR.C9orf72 < 0.05 & log2FC.VCP < 0 & log2FC.C9orf72 < 0~ "VCP C9orf72 down",
                             FDR.VCP < 0.05 & FDR.SOD1 < 0.05 & log2FC.VCP > 0 & log2FC.SOD1 > 0 ~ "VCP SOD1 up",
                             FDR.VCP < 0.05 & FDR.SOD1 < 0.05 & log2FC.VCP < 0 & log2FC.SOD1 < 0~ "VCP SOD1 down",
                             FDR.VCP < 0.05 & FDR.FUS < 0.05 & log2FC.VCP > 0 & log2FC.FUS > 0 ~ "VCP FUS up",
                             FDR.VCP < 0.05 & FDR.FUS < 0.05 & log2FC.VCP < 0 & log2FC.FUS < 0~ "VCP FUS down",
                             FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & log2FC.C9orf72 > 0 & log2FC.SOD1 > 0 ~ "C9orf72 SOD1 up",
                             FDR.C9orf72 < 0.05 & FDR.SOD1 < 0.05 & log2FC.C9orf72 < 0 & log2FC.SOD1 < 0~ "C9orf72 SOD1 down",
                             FDR.C9orf72 < 0.05 & FDR.FUS < 0.05 & log2FC.C9orf72 > 0 & log2FC.FUS > 0 ~ "C9orf72 FUS up",
                             FDR.C9orf72 < 0.05 & FDR.FUS < 0.05 & log2FC.C9orf72 < 0 & log2FC.FUS < 0~ "C9orf72 FUS down",
                             FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.SOD1 > 0 & log2FC.FUS > 0 ~ "SOD1 FUS up",
                             FDR.SOD1 < 0.05 & FDR.FUS < 0.05 & log2FC.SOD1 < 0 & log2FC.FUS < 0~ "SOD1 FUS down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "VCP C9orf72 SOD1 up", "VCP C9orf72 SOD1 down", "VCP C9orf72 FUS up", "VCP C9orf72 FUS down", "VCP SOD1 FUS up", "VCP SOD1 FUS down","C9orf72 SOD1 FUS up", "C9orf72 SOD1 FUS down","VCP C9orf72 up","VCP C9orf72 down","VCP SOD1 up","VCP SOD1 down", "VCP FUS up", "VCP FUS down","C9orf72 SOD1 up","C9orf72 SOD1 down","C9orf72 FUS up","C9orf72 FUS down","SOD1 FUS up","SOD1 FUS down","None"))) %>%  arrange(overlap) %>%
  select(gene_name, hsap.ensembl, overlap, everything())

write_csv(als_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS3.overlap_als_individual_datasets.csv")

# VCP.SOD1.C9ORF72.FUS_overlap <- cbindX(arrange(as_tibble_col(DGEup_C9ORF72_VCP, column_name = "C9ORF72_VCP_up"), C9ORF72_VCP_up),  
#                          arrange(as_tibble_col(DGEdown_C9ORF72_VCP, column_name = "C9ORF72_VCP_down"), C9ORF72_VCP_down),  
#                          arrange(as_tibble_col(DGEup_SOD1_VCP, column_name = "SOD1_VCP_up"), SOD1_VCP_up),  
#                          arrange(as_tibble_col(DGEdown_SOD1_VCP, column_name = "SOD1_VCP_down"), SOD1_VCP_down))
# VCP.SOD1.C9ORF72.FUS_overlap[is.na(VCP.SOD1.C9ORF72.FUS_overlap)] <- ""
# write_csv(VCP.SOD1.C9ORF72.FUS_overlap, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/Table.S3.VCP.SOD1.C9ORF72.FUS_overlap.csv")
```



# Fig 2 hiPSC ALS meta-analysis

## Volcano

```{r}
als_datasets.interesting.gene.labels <- als_datasets$res %>% filter(-log10(padj) > 3, abs(log2FoldChange) > 3, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go)) %>% pull(gene_name)
als_datasets.reactive.labels = als_datasets$res %>% filter(padj < 0.05, gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name)) %>% pull(gene_name)

als_datasets.volcano <- volcano_plot_deseq(data = als_datasets$res, labels_list = c(als_datasets.interesting.gene.labels, als_datasets.reactive.labels)) + xlab(expression(log[2]~fold~change~ALS:CTRL)) + 
  coord_cartesian(xlim = c(-6,6), ylim = c(0,11)) +
  geom_segment(aes(x = 1, xend = 6, y= 10, yend= 10), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -1, xend = -6, y= 10, yend= 10),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 3, y = 10.5, label = "Up in ALS", color = "firebrick2", size = 2.8) + annotate("text", x = -3, y = 10.5, label = "Down in ALS", color = "dodgerblue2", size = 2.8)
als_datasets.volcano

als_datasets$res %>% filter(padj<0.05, log2FoldChange > 0) # 1309
als_datasets$res %>% filter(padj<0.05, log2FoldChange < 0) # 1562

```

## GO terms ALS

```{r}
als_datasets.dge_genes <- als_datasets$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") %>% gost()
als_datasets.dge_gprofiles_filt <- als_datasets.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " ALS Down ", query == "query_2" ~ " ALS Up "), term_name = as.factor(term_name)) 
als_datasets.dge_gprofiles_down <- als_datasets.dge_gprofiles_filt %>% filter(query == " ALS Down ")
als_datasets.dge_gprofiles_up <- als_datasets.dge_gprofiles_filt %>% filter(query == " ALS Up ")
paste('"',unique(als_datasets.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
# "GABA-ergic synapse",
# "synapse organization",
"glutamatergic synapse",
"dendrite",
"axon",
"synaptic signaling",
"synaptic membrane",
"neuron differentiation",
"synapse")
# "nervous system development")
als_datasets.dge_gprofiles_filt_down <- als_datasets.dge_gprofiles_filt %>% filter(query == " ALS Down ")  %>% filter(term_name %in% down_list)
paste('"',unique(als_datasets.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
  "Protein processing in endoplasmic reticulum",
"response to endoplasmic reticulum stress",
"collagen-containing extracellular matrix",
  "focal adhesion",
  "Post-translational protein modification",
"Metabolism of proteins",
# "cell adhesion",
# "wound healing",
# "collagen binding",
# "collagen metabolic process",
"anchoring junction",
# "Elastic fibre formation",
# "cell-substrate junction",
"focal adhesion",
"collagen fibril organization",
"endoplasmic reticulum",
"extracellular matrix")
als_datasets.dge_gprofiles_filt_up <- als_datasets.dge_gprofiles_filt %>% filter(query == " ALS Up ")  %>% filter(term_name %in% up_list)
als_datasets.dge_gprofiles_filt_combined <- bind_rows(als_datasets.dge_gprofiles_filt_down, als_datasets.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" ALS Up ", " ALS Down ")))
als_datasets.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", als_datasets.dge_gprofiles_filt_combined$term_name) %>% gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", .) %>% gsub(" pathway", "", .) %>% gsub("Protein processing in endoplasmic reticulum", "Protein processing in ER", .) %>% gsub("response to endoplasmic reticulum stress","response to ER stress",.)
als_datasets.go_curated <- curated_profiles(gprofiles = als_datasets.dge_gprofiles_filt_combined) + theme(legend.position = "none", axis.text = element_text(size=10))
als_datasets.go_curated

# which genes are driving the terms
als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)
```

## panALS GSEA Glutamate uptake

```{r}
als_datasets.geneList <- als_datasets$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(als_datasets.geneList) <- als_datasets$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
als_datasets.geneList = sort(als_datasets.geneList, decreasing = TRUE)
als_datasets.glutamate.uptake_genes.list <- list("glutamate.uptake" = als_datasets$res$gene_name[als_datasets$res$gene_name %in% glutamate.uptake.go]) # gprofiler_database$`glutamatergic synapse`
als_datasets.glutamate.uptake_fgseaRes <- fgsea(pathways = als_datasets.glutamate.uptake_genes.list, stats = als_datasets.geneList)
als_datasets.glutamate.uptake_fgseaRes
# pathway  pval  padj log2err         ES       NES size
# 1: glutamate.uptake 1e-10 1e-10      NA -0.5920696 -2.758083  403
als_datasets.glutamate.uptake.gseaplot = plotEnrichment(als_datasets.glutamate.uptake_genes.list[["glutamate.uptake"]], als_datasets.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~uptake~GSEA)) + xlab(expression(pan~ALS))+
  annotate("text", x = 100, y = -0.3, label = paste0("NES = ", round(als_datasets.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(als_datasets.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3.2, hjust = 0)
als_datasets.glutamate.uptake.gseaplot

filter(als_datasets.res, gene_name %in% glutamate.uptake.go, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(als_datasets.res, gene_name %in% gprofiler_database$`glutamatergic synapse`, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(als_datasets.res, gene_name %in% go.pathways.msigdb$GO_GLUTAMATE_METABOLIC_PROCESS, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(als_datasets.res, gene_name %in% c("SLC1A2", "TMEM259"), padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)

glutamate.uptake.go <- c(go.pathways.msigdb$GO_GLUTAMATE_BINDING, go.pathways.msigdb$GO_GLUTAMATE_BIOSYNTHETIC_PROCESS, go.pathways.msigdb$GO_GLUTAMATE_GATED_CALCIUM_ION_CHANNEL_ACTIVITY, go.pathways.msigdb$GO_GLUTAMATE_METABOLIC_PROCESS, gprofiler_database$`glutamatergic synapse`, gprofiler_database$`glutamate reuptake`)

```

## panA1 & panALS scatter correlation

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
als_datasets_a1_datasets.dge <- full_join(als_datasets.dge, a1_datasets.dge, by = c("gene_name", "gene_id"))

als_datasets_a1_datasets.dge <- als_datasets_a1_datasets.dge %>% mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.A1 < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.A1 < 0.05 ~ "A1 specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "A1 specific up",
                                                                  FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "A1 specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS specific up", "ALS specific down", "A1 specific up", "A1 specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "A1 specific", "None"))) %>%
  arrange(overlap_direction)
table(als_datasets_a1_datasets.dge$overlap)
table(als_datasets_a1_datasets.dge$overlap_direction)
als_datasets_a1_datasets.dge

cor.test(x = als_datasets_a1_datasets.dge$log2FC.ALS, y = als_datasets_a1_datasets.dge$log2FC.A1) # 0.094
t.test( x = als_datasets_a1_datasets.dge$log2FC.ALS, y = als_datasets_a1_datasets.dge$log2FC.A1, paired = TRUE )

a1_datasets.A1_ALS_scatter <- ggscatter(als_datasets_a1_datasets.dge, x = "log2FC.ALS", y = "log2FC.A1", color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "grey", "grey", "grey", "grey", "grey"), 
                                        cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5, cor.coeff.args = list(label.x = -5.5, label.y = 8, label.sep="\n")) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +  
    coord_cartesian(xlim = c(-6,6), ylim = c(-6,9)) +
    geom_smooth(data = als_datasets_a1_datasets.dge, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(als_datasets_a1_datasets.dge, overlap_direction %in%  c("overlapping up", "overlapping down"), gene_name %in% all.reactivity.go, log2FC.A1 < 9), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), 
                    fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = 30) +  
  annotate(geom="text", x=3, y=9, label="ALS & A1 both Up", color="firebrick2", size = 3.2)  + annotate(geom="text", x=-3, y=-6, label="ALS & A1 both Down", color="dodgerblue2", size = 3.2) + labs(subtitle = "pan-ALS vs A1")
a1_datasets.A1_ALS_scatter

# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
A1.DGE.up.genes <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
genome.size <- als_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(ALS.DGE.up.genes,  A1.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=4025
# Intersection size=381
# Overlapping p-value=4e-141
# Jaccard Index=0.1

ALS.DGE.down.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
A1.DGE.down.genes <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
genome.size <- als_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(ALS.DGE.down.genes, A1.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=4694
# Intersection size=497
# Overlapping p-value=5.4e-175
# Jaccard Index=0.1
```

## Venn panALS, hiPSC & mouse A1

```{r}
# 2 way overlap  panA1 & panALS
als_datasets.res.dge.up <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
als_datasets.res.dge.down <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
a1_datasets.res.dge.up <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
a1_datasets.res.dge.down <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
als_datasets.a1_datasets.A1.up_genes <- list("ALS" = als_datasets.res.dge.up, "A1" = a1_datasets.res.dge.up)
als_datasets.a1_datasets.A1.down_genes <- list("ALS" = als_datasets.res.dge.down, " A1" = a1_datasets.res.dge.down)
a1_datasets_als_datasets_venn_up <- ggvenn(als_datasets.a1_datasets.A1.up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.7) + labs(subtitle = "Overlap Up")  + theme(plot.subtitle = element_text(hjust = 0.5), plot.margin = unit(c(0, -1, -1, -1), "lines"))
a1_datasets_als_datasets_venn_down <- ggvenn(als_datasets.a1_datasets.A1.down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.7) + labs(subtitle = "Overlap Down") + theme(plot.subtitle = element_text(hjust = 0.5), plot.margin = unit(c(0, -1, -1, -1), "lines"))
a1_datasets_als_datasets_venn = ggarrange(a1_datasets_als_datasets_venn_up, a1_datasets_als_datasets_venn_down, ncol = 2)
a1_datasets_als_datasets_venn

```

## GO terms panALS, hiPSC & mouse A1

```{r}
als_datasets_a1_datasets.gost = als_datasets_a1_datasets.dge %>% filter(overlap_direction %in% c("overlapping up", "overlapping down")) %>% split(.$overlap_direction) %>%  map("gene_id") %>% gost()
als_datasets_a1_datasets.gost_filt <- als_datasets_a1_datasets.gost$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "overlapping down" ~ " A1 & ALS Down ", query == "overlapping up" ~ " A1 & ALS Up "), term_name = as.factor(term_name)) 
als_datasets_a1_datasets.gprofiles_down <- als_datasets_a1_datasets.gost_filt %>% filter(query == " A1 & ALS Down ")
als_datasets_a1_datasets.gprofiles_up <- als_datasets_a1_datasets.gost_filt %>% filter(query == " A1 & ALS Up ")
paste('"',unique(als_datasets_a1_datasets.gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
als.a1.overlap.up_curated_list <- c(
"Collagen formation",
"Protein processing in endoplasmic reticulum",
"focal adhesion",
"Extracellular matrix organization",
"cellular response to stress",
"focal adhesion",
"Golgi apparatus",
"endoplasmic reticulum protein-containing complex",
"endoplasmic reticulum unfolded protein response",
"response to endoplasmic reticulum stress",
"endoplasmic reticulum")
als_datasets_a1_datasets.gost_filt.up <- als_datasets_a1_datasets.gost_filt %>% filter(term_name %in% als.a1.overlap.up_curated_list)
als_datasets_a1_datasets.gost_filt.up$term_name <- gsub("endoplasmic reticulum protein-containing complex", "ER protein-containing complex", als_datasets_a1_datasets.gost_filt.up$term_name) %>% gsub("endoplasmic reticulum unfolded protein response", "ER unfolded protein response", .) %>% gsub("response to endoplasmic reticulum stress", "response to ER stress", .) %>% gsub("Protein processing in endoplasmic reticulum", "Protein processing in ER", .)
paste('"',unique(als_datasets_a1_datasets.gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
als.a1.overlap.down_curated_list <- c(
"axon development",
"synaptic membrane",
"glutamatergic synapse",
"axon",
"postsynapse",
"dendrite",
"generation of neurons",
"synapse",
"neuron differentiation",
"neuron projection")
als_datasets_a1_datasets.gost_filt.down <- als_datasets_a1_datasets.gost_filt %>% filter(term_name %in% als.a1.overlap.down_curated_list)
als.a1.overlap.up_gprofiles_filt.up_down <- bind_rows(als_datasets_a1_datasets.gost_filt.up, als_datasets_a1_datasets.gost_filt.down) %>% mutate(query = factor(query, levels = c(" A1 & ALS Up ", " A1 & ALS Down ")))
als_datasets_a1.go_curated <- curated_profiles(gprofiles = als.a1.overlap.up_gprofiles_filt.up_down, colours = 2) + labs(subtitle = "A1 & pan-ALS overlap") + theme(legend.position = "none", axis.text = element_text(size=10))
als_datasets_a1.go_curated

```

## Merge

```{r}
fig2.merged <- ggarrange(
  ggarrange(als_datasets.volcano, als_datasets.go_curated, labels = c("B", "C"), ncol = 2),
  ggarrange(als_datasets.glutamate.uptake.gseaplot, a1_datasets.A1_ALS_scatter, widths = c(0.9,1), labels = c("D", "E"), ncol = 2),
  ggarrange(a1_datasets_als_datasets_venn,als_datasets_a1.go_curated, widths = c(1,1), labels = c("F", "G"), ncol = 2),
  nrow = 3)
# fig2.merged
ggsave(fig2.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig2.merged.png", height = 11, width = 11)

```

# Fig. S4 A1 PCA & dendrogram samples

```{r}
a1_datasets.pcaData <- plotPCA(a1_datasets$vsd, intgroup=c("group", "region", "replicate", "celltype_source", "sample", "dataset", "name"), returnData=TRUE) %>% mutate(Protocol = dataset, Treatment = case_when(group.1 == "a1" ~ "IL1a TNFa C1q", TRUE ~ "vehicle"))
a1_datasets.percentVar <- round(100 * attr(a1_datasets.pcaData, "percentVar"))
a1_datasets.pca <- ggplot(a1_datasets.pcaData, aes(PC1, PC2, color=Treatment, shape = Protocol)) + scale_colour_manual(values = c("firebrick2", "dodgerblue2")) +  
  theme_bw() + theme(panel.grid = element_blank(), legend.text=element_text(size=8), legend.position = "right", legend.box = "vertical", legend.spacing = unit(0.1, 'cm')) + geom_point(size=2) + 
  xlab(paste0("PC1: ",a1_datasets.percentVar[1],"% variance")) +  ylab(paste0("PC2: ",a1_datasets.percentVar[2],"% variance")) + #coord_fixed() + 
  ggforce::geom_mark_ellipse(aes(label = Protocol), label.fontsize = 8, label.fontface = "plain", con.type = "straight", con.cap = 0.5, show.legend = FALSE)
a1_datasets.pca

# Dendrogram
a1_datasets.sampleDists <- dist(t(assay(a1_datasets$vsd)))
a1_datasets.hc <- hclust(a1_datasets.sampleDists, method = "ward.D2")
a1_datasets.hc$labels <- gsub("ac_bar", "Barbar", a1_datasets.hc$labels) %>% gsub("a1f", "a1_R1", .) %>% gsub("a1m", "a1_R2", .) %>%  gsub("a1u", "a1_R3", .) %>% gsub("a0f", "a0_R1", .) %>% gsub("a0m", "a0_R2", .) %>%  gsub("a0u", "a0_R3", .) %>%  gsub("a0", "A0", .) %>% gsub("a1", "A1", .)
a1_datasets.a <-c( rep("dodgerblue2", 3), rep("firebrick2", 9), rep("dodgerblue2", 12), rep("firebrick2", 6))
a1_datasets.dendrogram <- ggdendrogram(a1_datasets.hc, rotate = TRUE, theme_dendro = FALSE) +  theme_classic()  + theme(axis.line=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y= element_text(colour = a1_datasets.a, size = 8), strip.background = element_rect(colour="black", fill="white"), panel.grid = element_blank()) 
a1_datasets.dendrogram
# ggsave(a1_datasets.dendrogram, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/a1_datasets.dendrogram_celltypes.png", height = 7, width = 4)

a1_datasets.clustering <- ggarrange(a1_datasets.pca, a1_datasets.dendrogram, nrow = 2, heights = c(1,1), labels = c("A", "B"))
a1_datasets.clustering
ggsave(a1_datasets.clustering, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/FigS4.a1_datasets.clustering.png", height = 13, width = 10)
```

# Table S4. ALS & A1 gene expression

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, ensembl = gene_id, log2FC.ALS = log2FoldChange, P.ALS = pvalue, FDR.ALS = padj) %>% 
  mutate(direction.ALS = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "up", FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "down", TRUE ~ "non-significant"))
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, ensembl = gene_id, log2FC.A1 = log2FoldChange, P.A1 = pvalue, FDR.A1 = padj) %>% 
  mutate(direction.A1 = case_when(FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "up", FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "down", TRUE ~ "non-significant"))

als_a1_datasets_merged.dge <- als_datasets.dge %>% full_join(a1_datasets.dge) %>%  
  mutate(overlap = case_when(direction.ALS == "up" & direction.A1 == "up"  ~ "overlapping up",
                             direction.ALS == "down" & direction.A1 == "down"  ~ "overlapping down",
                             direction.ALS == "up" ~ "ALS up", 
                             direction.ALS == "down" ~ "ALS down", 
                             direction.A1 == "up" ~ "A1 up", 
                             direction.A1 == "down" ~ "A1 down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "ALS u", "ALS down","A1 up","A1 down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, ensembl, overlap, everything()) %>% filter(overlap != "None")

write_csv(als_a1_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS4.overlap_als_a1_datasets.csv")
```


# Fig. S5 Sporadic ALS astrocytes

## GSEA

```{r}
# GSEA phagocytosis
ferraiuolo.geneList <- ferraiuolo.res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(ferraiuolo.geneList) <- ferraiuolo.res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
ferraiuolo.geneList = sort(ferraiuolo.geneList, decreasing = TRUE)
glutamate.uptake_genes.list <- list("glutamate.uptake" = ferraiuolo.res$gene_name[ferraiuolo.res$gene_name %in% glutamate.uptake.go])
ferraiuolo.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = ferraiuolo.geneList)
ferraiuolo.glutamate.uptake_fgseaRes
#             pathway       pval       padj   log2err        ES      NES size                               leadingEdge
# 1: glutamate.uptake 0.05979073 0.05979073 0.2249661 0.3063251 1.199837  389 PRKAR2B,GRM3,NPTX2,PCDH17,PLPPR4,NRGN,...
ferraiuolo.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], ferraiuolo.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(Sporadic~ALS)) +  
  annotate("text", x = 100, y = -0.12, label = paste0("NES = ", round(ferraiuolo.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = 0.08"), size = 3, hjust = 0)
ferraiuolo.glutamate.gseaplot
#             pathway   pval   padj   log2err        ES      NES size                               leadingEdge
# 1: glutamate.uptake 0.0784 0.0784 0.2020717 0.3070159 1.194868  389 PRKAR2B,GRM3,NPTX2,PCDH17,PLPPR4,NRGN,...

ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange > 0) # 45
ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange < 0) # 29
```


## panALS & sporadic Scatter

```{r}
# # correlate ferraiuolo sporadic with panALS:
als_datasets.res.ferraiuolo <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>%  drop_na(log2FC.ALS) %>% distinct(gene_name, .keep_all = TRUE)
ferraiuolo.res.filt <- ferraiuolo.res %>% select(gene_name, log2FC.sporadic = log2FoldChange, FDR.sporadic = pvalue) %>% drop_na(log2FC.sporadic) %>% distinct(gene_name, .keep_all = TRUE)
als_datasets_ferraiuolo.dge <- full_join(als_datasets.res.ferraiuolo, ferraiuolo.res.filt, by = "gene_name") %>%
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.sporadic < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.sporadic < 0.05 ~ "sporadic specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.sporadic < 0.05 & log2FC.sporadic > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.sporadic < 0.05 & log2FC.sporadic < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.sporadic < 0.05 & log2FC.sporadic > 0 ~ "sporadic specific up",
                                                                  FDR.sporadic < 0.05 & log2FC.sporadic < 0 ~ "sporadic specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS specific up", "ALS specific down", "sporadic specific up", "sporadic specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "sporadic specific", "None"))) %>%
  arrange(overlap_direction)
table(als_datasets_ferraiuolo.dge$overlap_direction)
# overlapping up  overlapping down   ALS specific up ALS specific down    sporadic specific up  sporadic specific down
#
panALS_sporadicALS_scatter <- ggscatter(als_datasets_ferraiuolo.dge, x = "log2FC.ALS", y = "log2FC.sporadic", 
                                     color = "overlap_direction", palette = c("dodgerblue2", "grey", "grey", "grey", "grey", "grey"),
                                     cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -4, label.y = 4, label.sep = "\n", size = 3),
          xlab = expression( Log[2]~Fold~Change~pan~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~sporadic~ALS:CTRL), size = 0.5) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +
  xlim(-7,7) + ylim(-3,5) +
    coord_cartesian(xlim = c(-5,5), ylim = c(-3,5)) +
    geom_smooth(data = als_datasets_ferraiuolo.dge, aes(x = log2FC.ALS, y = log2FC.sporadic), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
  geom_text_repel(data = filter(als_datasets_ferraiuolo.dge, overlap_direction %in%  c("overlapping up", "overlapping down")), aes(x = log2FC.ALS, y = log2FC.sporadic, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +
  annotate(geom="text", x=3, y=5, label="pan ALS &\nsporadic ALS Up", color="firebrick2", size = 3) + annotate(geom="text", x=-3, y=-3, label="pan ALS &\nsporadic Down", color="dodgerblue2", size = 3)
panALS_sporadicALS_scatter
```

## A1 & sporadic scatter

```{r}
ferraiuolo.dge <- ferraiuolo.res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = pvalue)
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
ferraiuolo_a1_datasets.dge <- full_join(ferraiuolo.dge, a1_datasets.dge) %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.A1 < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.A1 < 0.05 ~ "A1 specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "A1 specific up",
                                                                  FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "A1 specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS specific up", "ALS specific down", "A1 specific up", "A1 specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "A1 specific", "None"))) %>%
  arrange(overlap_direction)
table(ferraiuolo_a1_datasets.dge$overlap)
table(ferraiuolo_a1_datasets.dge$overlap_direction)
# overlapping up  overlapping down   ALS specific up ALS specific down    A1 specific up  A1 specific down              None 
#              8                 7                40                23              4680              4442             55419 

cor.test(x = ferraiuolo_a1_datasets.dge$log2FC.ALS, y = ferraiuolo_a1_datasets.dge$log2FC.A1) # -0.013

A1_sporadicALS_scatter <- ggscatter(ferraiuolo_a1_datasets.dge, x = "log2FC.ALS", y = "log2FC.A1", color = "overlap_direction", 
                                    palette = c("firebrick2", "dodgerblue2", "grey", "grey", "grey", "grey", "grey"),
                                    cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -4, label.y = 8, label.sep = "\n", size = 3),
          xlab = expression( Log[2]~Fold~Change~Sporadic~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  coord_cartesian(xlim = c(-4,4), ylim = c(-5,10)) +
    geom_smooth(data = ferraiuolo_a1_datasets.dge, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(ferraiuolo_a1_datasets.dge, overlap_direction %in%  c("overlapping up", "overlapping down")), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=2.5, y=7, label="Up in sporadic\nALS & A1", color="firebrick2", size = 3)  + annotate(geom="text", x=-2, y=-5, label="Down in sporadic\nALS & A1", color="dodgerblue2", size = 3) 
A1_sporadicALS_scatter


# Overlap tested using Fisher's exact test (alternative=greater)
sporadic.ALS.DGE.up.genes <- ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange > 0) %>% pull(gene_name)
A1.DGE.up.genes <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
genome.size <- a1_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(sporadic.ALS.DGE.up.genes,   A1.DGE.up.genes,  genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=45
# listB size=4025
# Intersection size=3
# Overlapping p-value=0.58
# Jaccard Index=0.0

sporadic.ALS.DGE.down.genes <- ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange < 0) %>% pull(gene_name)
A1.DGE.down.genes <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
newGeneOverlap(sporadic.ALS.DGE.down.genes,A1.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=29
# listB size=4694
# Intersection size=2
# Overlapping p-value=0.67
# Jaccard Index=0.0


```

## Venn overlap DEGs

```{r}
# 2 way overlap mouse A1 & mouseALS
ferraiuolo.res.dge.up <- ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange > 0) %>% pull(gene_name)
ferraiuolo.res.dge.down <- ferraiuolo.res %>% filter(pvalue < 0.05, log2FoldChange < 0) %>% pull(gene_name)
a1_datasets.res.dge.up <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
a1_datasets.res.dge.down <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
ferraiuolo.a1_datasets.up_genes <- list("sporadic ALS\nUp" = ferraiuolo.res.dge.up, "A1\nUp" = a1_datasets.res.dge.up)
ferraiuolo.a1_datasets.down_genes <- list("sporadic ALS\nDown" = ferraiuolo.res.dge.down, "A1\nDown" = a1_datasets.res.dge.down)
a1_datasets_ferraiuolo_venn_up <- ggvenn(ferraiuolo.a1_datasets.up_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
a1_datasets_ferraiuolo_venn_down <- ggvenn(ferraiuolo.a1_datasets.down_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
a1_datasets_ferraiuolo_venn = ggarrange(a1_datasets_ferraiuolo_venn_up, a1_datasets_ferraiuolo_venn_down, ncol = 2)
a1_datasets_ferraiuolo_venn

# 
# # Upregulated DEG
# venn_A1_ALS.up <- as.ggplot(
#   ~draw.pairwise.venn(
#     area1 = nrow( filter(ferraiuolo_a1_datasets.dge, overlap_direction %in% c("ALS specific up", "overlapping up"))),
#     area2 = nrow( filter(ferraiuolo_a1_datasets.dge, overlap_direction %in% c("A1 specific up", "overlapping up")) ),
#     cross.area = nrow(filter(ferraiuolo_a1_datasets.dge, overlap_direction %in% "overlapping up")),
#     category = c("ALS", "A1"),  fill = c("dodgerblue2", "firebrick2"),
#     alpha = 0.5, cat.fontfamily = "sans", cat.pos = c(0,0), cat.dist =rep(0.04, 2), scaled = FALSE)) +
#   labs(subtitle = "Overlap Up") + theme(plot.subtitle = element_text(hjust = 0.5, colour = "firebrick2"))
# venn_A1_ALS.up
# 
# # Downregulated DEG
# venn_A1_ALS.down <- as.ggplot(
#   ~draw.pairwise.venn(
#     area1 = nrow( filter(ferraiuolo_a1_datasets.dge, overlap_direction %in% c("ALS specific down", "overlapping down")) ),
#     area2 = nrow( filter(ferraiuolo_a1_datasets.dge, overlap_direction %in% c("A1 specific down", "overlapping down")) ),
#     cross.area = nrow(filter(ferraiuolo_a1_datasets.dge, overlap_direction == "overlapping down")),
#     category = c("ALS", "A1"),  fill = c("dodgerblue2", "firebrick2"),
#     alpha = 0.5, cat.fontfamily = "sans", cat.pos = c(0,0), cat.dist =rep(0.04, 2), scaled = FALSE)) +
#   labs(subtitle = "Overlap Down") + theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"))
# venn_A1_ALS.down

# Overlaping genes involved with A1 reactivity
als_datasets_a1_datasets.dge %>% filter(overlap_direction == "overlapping up" | overlap_direction == "overlapping down") %>% filter(gene_name %in% all.reactivity.go) 
als_datasets_a1_datasets.dge %>% filter(overlap_direction == "overlapping up" | overlap_direction == "overlapping down") %>% filter(gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) 
als_datasets_a1_datasets.dge %>% filter(overlap_direction == "overlapping up" | overlap_direction == "overlapping down") %>% filter(gene_name %in% glutamate.uptake.go) 
```


## Merge

```{r}
sporadic.ALS_a1_datasets.merged = ggarrange(
  ferraiuolo.glutamate.gseaplot, panALS_sporadicALS_scatter, 
  A1_sporadicALS_scatter,  ggarrange(a1_datasets_ferraiuolo_venn_up, a1_datasets_ferraiuolo_venn_down, ncol = 2),
  nrow = 2, ncol = 2, heights = c(1,1), labels = c("A","B","C","D"))
sporadic.ALS_a1_datasets.merged
ggsave(sporadic.ALS_a1_datasets.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/FigS4.merged.sporadic.ALS_A1.merged.png", height = 9, width = 10)

```


# Fig. 3 Protective astrocytes

3A biorender schematic of MCAO & SCI models

## MCAO & panALS scatter correlation

```{r}
# correlate zamanian A2 with ALS:
als_datasets.res.zamanian <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>%  drop_na(log2FC.ALS) %>% distinct(gene_name, .keep_all = TRUE)
zamanian.res.filt <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% drop_na(log2FC.MCAO) %>% distinct(gene_name, .keep_all = TRUE)
als_datasets_zamanian.dge <- full_join(als_datasets.res.zamanian, zamanian.res.filt, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.MCAO < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.MCAO < 0.05 ~ "MCAO specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "ALS up, MCAO down", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "ALS down, MCAO up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "MCAO specific up",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "MCAO specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS up, MCAO down", "ALS down, MCAO up", "ALS specific up", "ALS specific down", "MCAO specific up", "MCAO specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "MCAO specific", "None"))) %>%
  arrange(overlap_direction)
# table(als_datasets_zamanian.dge$overlap_direction)
# overlapping up  overlapping down   ALS specific up ALS specific down    MCAO specific up  MCAO specific down 
#               109               150               963              1198              1181              1276 
cor.test(x = als_datasets_zamanian.dge$log2FC.ALS, y = als_datasets_zamanian.dge$log2FC.MCAO) #  MCAO.day1_vs_A0.day1 0.09 

MCAO_ALS_scatter <- ggscatter(als_datasets_zamanian.dge, x = "log2FC.ALS", y = "log2FC.MCAO", cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -6, label.y = -2.5, label.sep = "\n", size = 3), 
                            color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"),
  xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~MCAO:Sham), size = 0.5) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  xlim(-7,7) + ylim(-3,5) +
  geom_smooth(data = als_datasets_zamanian.dge, aes(x = log2FC.ALS, y = log2FC.MCAO), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
  geom_text_repel(data = filter(als_datasets_zamanian.dge, overlap_direction %in%  c("ALS up, MCAO down", "ALS down, MCAO up"), gene_name %in% all.reactivity.go), aes(x = log2FC.ALS, y = log2FC.MCAO, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
  annotate(geom="text", x=5.5, y=-2.5, label="ALS up\nMCAO down", color="forestgreen", size = 3.2) + annotate(geom="text", x=-4.5, y=4.5, label="ALS down\nMCAO up", color="gold2", size = 3.2) + labs(subtitle = "pan-ALS vs MCAO")
MCAO_ALS_scatter


# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
A2.DGE.up.genes <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
ALS.DGE.down.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
A2.DGE.down.genes <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
genome.size <- als_datasets_zamanian.dge %>% distinct(gene_name) %>% nrow

newGeneOverlap(ALS.DGE.up.genes, A2.DGE.down.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=1460
# Intersection size=108
# Overlapping p-value=3.8e-19
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.down.genes, A2.DGE.up.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=1312
# Intersection size=64
# Overlapping p-value=3.1e-03
# Jaccard Index=0.0

newGeneOverlap(ALS.DGE.up.genes,A2.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=1312
# Intersection size=134
# Overlapping p-value=2e-37
# Jaccard Index=0.1

newGeneOverlap(ALS.DGE.down.genes,A2.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=1460
# Intersection size=171
# Overlapping p-value=1.7e-45
# Jaccard Index=0.1

```

## SCI & panALS scatter correlation

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
anderson.dge <- anderson$res %>% select(gene_name, gene_id, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
als_datasets_anderson.dge <- full_join(als_datasets.dge, anderson.dge, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.SCI < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.SCI < 0.05 ~ "SCI specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "ALS up, SCI down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "ALS down, SCI up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "SCI specific up",
                                                                  FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "SCI specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS up, SCI down", "ALS down, SCI up", "ALS specific up", "ALS specific down", "SCI specific up", "SCI specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "SCI specific", "None"))) %>%
  arrange(overlap_direction)
table(als_datasets_anderson.dge$overlap)
table(als_datasets_anderson.dge$overlap_direction)

cor.test(x = als_datasets_anderson.dge$log2FC.ALS, y = als_datasets_anderson.dge$log2FC.SCI) # 0.1088784 
t.test( x = als_datasets_anderson.dge$log2FC.ALS, y = als_datasets_anderson.dge$log2FC.SCI, paired = TRUE )

SCI_ALS_scatter <- ggscatter(als_datasets_anderson.dge, x = "log2FC.ALS", y = "log2FC.SCI", cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -6.5, label.y = -5, label.sep = "\n", size = 3), 
                             color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"), 
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~SCI:CTRL), size = 0.5) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  xlim(-7,7) + ylim(-6,8) +
    geom_smooth(data = als_datasets_anderson.dge, aes(x = log2FC.ALS, y = log2FC.SCI), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(als_datasets_anderson.dge, overlap_direction %in%  c("ALS up, SCI down", "ALS down, SCI up"), gene_name %in% all.reactivity.go, log2FC.SCI < 9), aes(x = log2FC.ALS, y = log2FC.SCI, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=5.3, y=-5.5, label="ALS up\nSCI down", color="forestgreen", size = 3.2)  + annotate(geom="text", x=-5, y=7.5, label="ALS down\nSCI up", color="gold2", size = 3.2) + labs(subtitle = "pan-ALS vs SCI")
SCI_ALS_scatter

# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
SCI.DGE.up.genes <- anderson$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
genome.size <- als_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(ALS.DGE.up.genes,SCI.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=2622
# Intersection size=215
# Overlapping p-value=9e-65
# Jaccard Index=0.1

ALS.DGE.down.genes <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
SCI.DGE.down.genes <- anderson$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
newGeneOverlap(ALS.DGE.down.genes,SCI.DGE.down.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=2274
# Intersection size=176
# Overlapping p-value=1.2e-38
# Jaccard Index=0.0

#Opposite overlap
newGeneOverlap(ALS.DGE.up.genes,SCI.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=2274
# Intersection size=105
# Overlapping p-value=4e-13
# Jaccard Index=0.0

newGeneOverlap(ALS.DGE.down.genes, SCI.DGE.up.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=2622
# Intersection size=164
# Overlapping p-value=1.6e-25
# Jaccard Index=0.0
```

## Venn panALS & protective

```{r}
# 3 way overlap SCI, hiPSC ALS, panALS
als_datasets.res.dge.up <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
als_datasets.res.dge.down <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
zamanian.A2.res.dge.up <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
zamanian.A2.res.dge.down <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
anderson.res.dge.up <- anderson$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
anderson.res.dge.down <- anderson$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
als_datasets_up.zamanian.A2.anderson_down_genes <- list("ALS Up" = als_datasets.res.dge.up, "MCAO Down" = zamanian.A2.res.dge.down, "SCI Down" = anderson.res.dge.down)
als_datasets_up.zamanian.A2.anderson_down_genes_venn <- ggvenn(als_datasets_up.zamanian.A2.anderson_down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
als_datasets_down.zamanian.A2.anderson_up_genes <- list("ALS Down" = als_datasets.res.dge.down, "MCAO Up" = zamanian.A2.res.dge.up, "SCI Up" = anderson.res.dge.up)
als_datasets_down.zamanian.A2.anderson_up_genes_venn <- ggvenn(als_datasets_down.zamanian.A2.anderson_up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
anderson_zamanian.A2_als_datasets_venn = ggarrange(als_datasets_up.zamanian.A2.anderson_down_genes_venn, als_datasets_down.zamanian.A2.anderson_up_genes_venn, nrow = 2)
anderson_zamanian.A2_als_datasets_venn


# Chi-squared 3 way overlap
list1 <- unique(als_datasets.res.dge.up[!is.na(als_datasets.res.dge.up)])
list2 <- unique(zamanian.A2.res.dge.down[!is.na(zamanian.A2.res.dge.down)])
list3 <- unique(anderson.res.dge.down[!is.na(anderson.res.dge.down)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 6.830366e-11


list1 <- unique(als_datasets.res.dge.down[!is.na(als_datasets.res.dge.down)])
list2 <- unique(zamanian.A2.res.dge.up[!is.na(zamanian.A2.res.dge.up)])
list3 <- unique(anderson.res.dge.up[!is.na(anderson.res.dge.up)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 1.133696e-05

```

## Liddelow heatmap

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
# guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.mouse.A1 = log2FoldChange, FDR.mouse.A1 = padj)
zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
anderson.dge = anderson$res %>%  select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
liddelow.astrocyte.reactivity.marker <- als_datasets.dge %>% full_join(a1_datasets.dge) %>% #left_join(guttenplan.A1.dge, by = "gene_name") %>% 
  left_join(zamanian.A2.dge, by = "gene_name") %>% left_join(anderson.dge, by = "gene_name") %>%
  filter(gene_name %in% astrocyte.reactivity.markers$gene_name, !gene_name %in% c("MICA","HLA-E", "HLA-F")) %>% arrange(factor(gene_name, levels = astrocyte.reactivity.markers$gene_name)) %>%
  select(gene_name, "hiPSC\nmeta-analysis\npan-ALS vs CTRL" = log2FC.ALS, "hiPSC\nTNFa IL1a C1q\nvs vehicle" = log2FC.A1, "Zamanian et al.\nmouse\nMCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse\nSCI vs CTRL" = log2FC.SCI)

liddelow.astrocyte.reactivity.marker %>%group_by(gene_name) %>% filter(n()>1) # any duplicate gene_names?

liddelow.astrocyte.reactivity.marker.mat <- make_matrix(select(liddelow.astrocyte.reactivity.marker,-gene_name), pull(liddelow.astrocyte.reactivity.marker,gene_name))
liddelow.astrocyte.reactivity.marker.mat.scale <- scale(liddelow.astrocyte.reactivity.marker.mat, center = FALSE) # make variance equal between datasets
# liddelow.astrocyte.reactivity.marker.mat.scale = t(scale(t(liddelow.astrocyte.reactivity.marker.mat.scale))) # row scale
# liddelow.astrocyte.reactivity.marker.mat.scale <- liddelow.astrocyte.reactivity.marker.mat.scale[!is.infinite(rowSums(liddelow.astrocyte.reactivity.marker.mat.scale)),]

liddelow.astrocyte.reactivity.markers.filt <- astrocyte.reactivity.markers %>% filter(gene_name %in% liddelow.astrocyte.reactivity.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

liddelow.astrocyte.reactivity.marker.heatmap <- Heatmap(liddelow.astrocyte.reactivity.marker.mat.scale,
          show_heatmap_legend = FALSE, col = col_ramp_reactivity.markers, 
          cluster_rows = FALSE, cluster_columns = FALSE, cluster_row_slices = FALSE,          
          row_names_gp = gpar(fontsize = 6), column_names_gp = gpar(fontsize = 8), border = TRUE, #, #, col = c(rep("red", 10), rep("blue", 8)))
          row_order = liddelow.astrocyte.reactivity.markers.filt$gene_name,
          row_split = factor(liddelow.astrocyte.reactivity.markers.filt$group, levels = unique(liddelow.astrocyte.reactivity.markers.filt$group)),
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("Pan\nreactive", "A1", "A2"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("ALS", "A1", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,2,3,3),
          row_title = "Liddelow et al. Astrocyte reactivity markers", row_title_gp = gpar(fontsize = 8))
liddelow.astrocyte.reactivity.marker.heatmap

```

## Escartin heatmap

Table 1 <https://www.nature.com/articles/s41593-020-00783-4>

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
# guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.mouse.A1 = log2FoldChange, FDR.mouse.A1 = padj)
zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
anderson.dge = anderson$res %>%  select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
main.escartin.marker <- als_datasets.dge %>% full_join(a1_datasets.dge) %>% #left_join(guttenplan.A1.dge, by = "gene_name") %>% 
  left_join(zamanian.A2.dge, by = "gene_name") %>% left_join(anderson.dge, by = "gene_name") %>%
  filter(gene_name %in% escartin.markers$gene_name, !gene_name %in% c("MICA","HLA-E", "HLA-F")) %>% arrange(factor(gene_name, levels = escartin.markers$gene_name)) %>%
  select(gene_name, "hiPSC\nmeta-analysis\npan-ALS vs CTRL" = log2FC.ALS, "hiPSC\nTNFa IL1a C1q\nvs vehicle" = log2FC.A1, "Zamanian et al.\nmouse\nMCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse\nSCI vs CTRL" = log2FC.SCI)
main.escartin.marker.mat <- make_matrix(select(main.escartin.marker,-gene_name), pull(main.escartin.marker,gene_name))
main.escartin.marker.mat.scale <- scale(main.escartin.marker.mat, center = FALSE) # make variance equal between datasets
# main.escartin.marker.mat.scale[main.escartin.marker.mat.scale > 3] <- 3 # crop outliers to improve colour distribution
# escartin.marker.mat.scale = t(scale(t(escartin.marker.mat.scale))) # row scale
# escartin.marker.mat.scale <- escartin.marker.mat.scale[!is.infinite(rowSums(escartin.marker.mat.scale)),]

main.escartin.markers.filt <- escartin.markers %>% filter(gene_name %in% main.escartin.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

main.escartin.marker.heatmap <- Heatmap(main.escartin.marker.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_ramp_reactivity.markers,
          cluster_rows = FALSE, cluster_row_slices = FALSE, cluster_columns = FALSE,
          row_split = factor(main.escartin.markers.filt$group, levels = unique(main.escartin.markers.filt$group)), border = TRUE,
          row_order = main.escartin.markers.filt$gene_name,
          row_names_gp = gpar(fontsize = 7), column_names_gp = gpar(fontsize = 8),
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white", "white", "white", "white")),
                                                                labels = c("Cytoskeleton", "Metabolism", "Chaperone", "Secreted\nproteins", "Cell\nsignalling", "Channels -\nTransporters"), labels_gp = gpar(fontsize = 7), labels_rot = 0)),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("ALS", "A1", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,2,3,3),
          row_title = "Escartin et al. Reactive astrocyte markers", row_title_gp = gpar(fontsize = 8))
main.escartin.marker.heatmap

```


## Signalling Pathway PROGENy

<https://github.com/saezlab/transcriptutorial/blob/master/scripts/03_Pathway_activity_with_Progeny.md> <https://saezlab.github.io/progeny/>

Pathway RespOnsive GENes (PROGENy) estimates signaling pathway activity

```{r}
als_datasets.res.matrix <- als_datasets$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
als_datasets.ALS.PathwayActivity_zscore <- progeny(als_datasets.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t()# enrichment analysis of each pathway activity using competitive permutation approach
colnames(als_datasets.ALS.PathwayActivity_zscore) <- "NES"
als_datasets.ALS.PathwayActivity_zscore_df <- as.data.frame(als_datasets.ALS.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>% mutate(Pathway = factor(Pathway), dataset = "pan-ALS")

a1_datasets.res.matrix <- a1_datasets$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
a1_datasets.A1.PathwayActivity_zscore <- progeny(a1_datasets.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
colnames(a1_datasets.A1.PathwayActivity_zscore) <- "NES"
a1_datasets.A1.PathwayActivity_zscore_df <- as.data.frame(a1_datasets.A1.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>% mutate(Pathway = factor(Pathway), dataset = "A1")

# guttenplan.A1.res.matrix <- guttenplan.A1$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
# guttenplan.A1.PathwayActivity_zscore <- progeny(guttenplan.A1.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>% t() # enrichment analysis of each pathway activity
# colnames(guttenplan.A1.PathwayActivity_zscore) <- "NES"
# guttenplan.A1.PathwayActivity_zscore_df <- as.data.frame(guttenplan.A1.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "Mouse A1")

zamanian.A2.res.matrix <- zamanian.A2.res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
zamanian.A2.PathwayActivity_zscore <- progeny(zamanian.A2.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
colnames(zamanian.A2.PathwayActivity_zscore) <- "NES"
zamanian.A2.PathwayActivity_zscore_df <- as.data.frame(zamanian.A2.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "MCAO")

anderson.res.matrix <- anderson$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
anderson.PathwayActivity_zscore <- progeny(anderson.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
colnames(anderson.PathwayActivity_zscore) <- "NES"
anderson.PathwayActivity_zscore_df <- as.data.frame(anderson.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "SCI")

# barchart
als_a1_protective_datasets.PathwayActivity_zscore_df <- bind_rows(als_datasets.ALS.PathwayActivity_zscore_df, a1_datasets.A1.PathwayActivity_zscore_df, zamanian.A2.PathwayActivity_zscore_df, anderson.PathwayActivity_zscore_df) %>% mutate(Pathway = factor(Pathway, levels = als_datasets.ALS.PathwayActivity_zscore_df$Pathway), dataset = factor(dataset, levels = c("pan-ALS", "A1","MCAO", "SCI")))
als_A1_protective.progeny.pathwayActivity <- ggplot(als_a1_protective_datasets.PathwayActivity_zscore_df, aes(x=dataset, y = NES, fill = dataset)) + theme_bw() +
  geom_bar(stat="identity", position=position_dodge(), width = 0.7) + theme(legend.position = "none", legend.title = element_blank(), axis.title = element_text(size = 10),
          axis.text.x = element_text(angle = 90, hjust = 1, size = 8), axis.text.y = element_text(size =8), strip.text.x = element_text(size = 8, angle = 0)) + 
  geom_hline(yintercept = 0, linetype = 2, colour = "darkgrey") + 
  scale_fill_manual( values = c("dodgerblue2","firebrick2",  "forestgreen", "gold2", "purple")) +
  facet_wrap(~Pathway, scales = "free", nrow = 2) +
  xlab("") + ylab(expression(Normalised~enrichment)) #+ labs(subtitle = "Signalling Pathway activity")
als_A1_protective.progeny.pathwayActivity

# a1_datasets.als_datasets.PathwayActivity_zscore_df.meanNES <- a1_datasets.als_datasets.PathwayActivity_zscore_df %>% filter(dataset == "pan-ALS") %>% arrange(NES)
# a1_datasets.als_datasets.PathwayActivity_zscore_df$Pathway <- factor(a1_datasets.als_datasets.PathwayActivity_zscore_df$Pathway, levels = a1_datasets.als_datasets.PathwayActivity_zscore_df.meanNES$Pathway)
# als_A1_protective.progeny.ordered.pathwayActivity <- ggplot(a1_datasets.als_datasets.PathwayActivity_zscore_df, aes(x=Pathway, y = NES, fill = dataset)) + theme_classic() +
#   geom_bar(stat="identity", position=position_dodge(), width = 0.7) + theme(legend.position = "none", legend.title = element_blank(), axis.title = element_text(size = 12),
#         axis.text.x = element_text(angle = 45, hjust = 1, size = 8), axis.text.y = element_text(size =8)) + 
#   geom_hline(yintercept = 0, linetype = 2, colour = "darkgrey") + scale_fill_manual( values = c("firebrick2", "dodgerblue2")) + 
#   facet_wrap(~dataset, scales = "free") +
#   xlab("") + ylab(expression(Normalised~enrichment))
# als_A1_protective.progeny.ordered.pathwayActivity

```



## Merge

```{r}
fig3.merged <- ggarrange(
  ggarrange(MCAO_ALS_scatter, SCI_ALS_scatter, anderson_zamanian.A2_als_datasets_venn, ncol = 3, labels = c("B", "C", "D"), widths = c(1.2,1.2,0.8)),
  ggarrange(as.ggplot(liddelow.astrocyte.reactivity.marker.heatmap), as.ggplot(main.escartin.marker.heatmap), ncol = 2, labels = c("E", "F")),
  als_A1_protective.progeny.pathwayActivity,
  nrow = 3, heights = c(0.85,1.1,1), labels = c("", "", "G"))
# fig3.merged
ggsave(fig3.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig3.merged.pathways.markers.png", height = 12, width = 10)


  # ggarrange(ggarrange(als_datasets.phagocytosis.gseaplot, als_datasets.glutamate.uptake.gseaplot, barbar.phagocytosis.gseaplot, barbar.glutamate.uptake.gseaplot, ncol = 2, nrow = 2, labels = c("C", "D", "", "")),
  #   , ncol = 2, labels = c("", "E"), widths = c(1.2,1)),
  # ggarrange(A1_SOD1_TRAP_scatter, cleveland.A1_venn, cleveland_barbar.go_curated, ncol = 3, labels = c("F", "G", "H"), widths = c(1.2,0.6,1.1)), 
```


# Table S5 panALS & protective datasets

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% 
  mutate(direction.ALS = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "up", FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "down", TRUE ~ "non-significant"))
anderson.dge <- anderson$res %>% select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj) %>% 
  mutate(direction.SCI = case_when(FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "up", FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "down", TRUE ~ "non-significant"))
zamanian.A2.dge <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% 
  mutate(direction.MCAO = case_when(FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "up", FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "down", TRUE ~ "non-significant"))

als_protective_datasets_merged.dge <- als_datasets.dge %>% left_join(anderson.dge) %>% left_join(zamanian.A2.dge) %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "ALS up, MCAO & SCI down",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "ALS down, MCAO & SCI up",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 ~ "ALS up, MCAO down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0~ "ALS down, MCAO up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI < 0 ~ "ALS up, SCI down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI > 0 ~ "ALS down, SCI up",
           FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "overlapping up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "overlapping down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 ~ "ALS & MCAO up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0~ "ALS & MCAO down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI > 0 ~ "ALS & SCI up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI < 0~ "ALS & SCI down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("ALS up, MCAO & SCI down", "ALS down, MCAO & SCI up", "ALS up, MCAO down", "ALS down, MCAO up",  "ALS up, SCI down", "ALS down, SCI up", "overlapping up",  "overlapping down", "ALS MCAO SCI up", "ALS MCAO SCI down","ALS MCAO up","ALS MCAO down","ALS SCI up","ALS SCI down","MCAO SCI up","MCAO SCI down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, hsap.ensembl, overlap, everything()) %>% filter(overlap != "None")

write_csv(als_protective_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS5.overlap_als_protective_datasets.csv")

```


# Fig S6 Reactive markers ALS vs CTRL

## Liddelow correlations

```{r}
### hiPSC A1 & ALS
als_datasets.res.liddelow <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
a1_datasets.res.liddelow <- a1_datasets$res %>% select(gene_name, log2FC.A1 = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
als_datasets_a1_datasets.liddelow <- full_join(als_datasets.res.liddelow, a1_datasets.res.liddelow, by = "gene_name") %>% left_join(astrocyte.reactivity.markers) %>% drop_na() %>% rename(Markers = group)
A1.hipsc_ALS_scatter.liddelow <- ggscatter(als_datasets_a1_datasets.liddelow, x = "log2FC.ALS", y = "log2FC.A1", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~hiPSC~A1:A0), size = 0.5) + theme(legend.position = "top") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +
    geom_text_repel(data = filter(als_datasets_a1_datasets.liddelow, log2FC.A1 > 0.1, log2FC.ALS > 0.1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      
  geom_text_repel(data = filter(als_datasets_a1_datasets.liddelow, log2FC.A1 < -0.1, log2FC.ALS < -0.1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=1, y=10, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(hiPSC~A1~and~ALS~astrocytes:Liddelow~markers))
A1.hipsc_ALS_scatter.liddelow

# Overlap
als_datasets_a1_datasets.liddelow # 41
als_datasets_a1_datasets.liddelow %>% filter((log2FC.ALS > 0 & log2FC.A1 > 0) | (log2FC.ALS < 0 & log2FC.A1 < 0)) # 22

### MCAO & ALS
als_datasets.res.liddelow <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
zamanian.res.liddelow <- zamanian.A2.res %>% select(gene_name, log2FC.A2 = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
als_datasets_zamanian.liddelow <- full_join(als_datasets.res.liddelow, zamanian.res.liddelow) %>% left_join(astrocyte.reactivity.markers) %>% drop_na() %>% rename(Markers = group)
MCAO_ALS_scatter.liddelow <- ggscatter(als_datasets_zamanian.liddelow, x = "log2FC.ALS", y = "log2FC.A2", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~MCAO:Sham), size = 0.5) + theme(legend.position = "none") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
    geom_text_repel(data = filter(als_datasets_zamanian.liddelow, log2FC.A2 > 0.1, log2FC.ALS > 0.1), aes(x = log2FC.ALS, y = log2FC.A2, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_datasets_zamanian.liddelow, log2FC.A2 < -0.1, log2FC.ALS < -0.1), aes(x = log2FC.ALS, y = log2FC.A2, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=0.8, y=10, label="ALS & MCAO both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(MCAO~and~ALS~astrocytes:Liddelow~markers))
MCAO_ALS_scatter.liddelow

als_datasets_zamanian.liddelow # 38
als_datasets_zamanian.liddelow %>% filter((log2FC.ALS > 0 & log2FC.A2 > 0) | (log2FC.ALS < 0 & log2FC.A2 < 0)) # 17

### SCI & ALS
als_datasets.res.liddelow <- als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
anderson.res.liddelow <- anderson$res %>% select(gene_name, log2FC.A2 = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
als_datasets_anderson.liddelow <- full_join(als_datasets.res.liddelow, anderson.res.liddelow) %>% left_join(astrocyte.reactivity.markers) %>% drop_na() %>% rename(Markers = group)
SCI_ALS_scatter.liddelow <- ggscatter(als_datasets_anderson.liddelow, x = "log2FC.ALS", y = "log2FC.A2", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~SCI:CTRL), size = 0.5) + theme(legend.position = "none") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
    geom_text_repel(data = filter(als_datasets_anderson.liddelow, log2FC.A2 > 0.1, log2FC.ALS > 0.1), aes(x = log2FC.ALS, y = log2FC.A2, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_datasets_anderson.liddelow, log2FC.A2 < -0.1, log2FC.ALS < -0.1), aes(x = log2FC.ALS, y = log2FC.A2, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=1, y=10, label="ALS & SCI both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(SCI~and~ALS~astrocytes:Liddelow~markers))
SCI_ALS_scatter.liddelow

als_datasets_anderson.liddelow # 32
als_datasets_anderson.liddelow %>% filter((log2FC.ALS > 0 & log2FC.A2 > 0) | (log2FC.ALS < 0 & log2FC.A2 < 0)) # 14

### A1 & sporadic ALS
ferraiuolo.res.liddelow <- ferraiuolo.res %>% select(gene_name, log2FC.ALS = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
a1_datasets.res.liddelow <- a1_datasets$res %>% select(gene_name, log2FC.A1 = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
ferraiuolo_a1_datasets.liddelow <- full_join(ferraiuolo.res.liddelow, a1_datasets.res.liddelow, by = "gene_name") %>% left_join(astrocyte.reactivity.markers) %>% drop_na() %>% rename(Markers = group)
A1.sporadic_ALS_scatter.liddelow <- ggscatter(ferraiuolo_a1_datasets.liddelow, x = "log2FC.ALS", y = "log2FC.A1", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~sporadic~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~hiPSC~A1:A0), size = 0.5) + theme(legend.position = "top") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +
    geom_text_repel(data = filter(ferraiuolo_a1_datasets.liddelow, Markers == "A1"), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +
  # annotate(geom="text", x=1, y=10, label="ALS & A1 both Up", color="firebrick2", size = 3.2) +
  labs(subtitle = expression(hiPSC~A1~and~sporadic~ALS~atrocytes:Liddelow~markers))
A1.sporadic_ALS_scatter.liddelow

ferraiuolo_a1_datasets.liddelow # 40
ferraiuolo_a1_datasets.liddelow %>% filter((log2FC.ALS > 0 & log2FC.A1 > 0) | (log2FC.ALS < 0 & log2FC.A1 < 0)) # 20

```

## Liddelow heatmap

```{r}
vcp_datasets.dge <- patani$res %>% select(gene_name, gene_id, log2FC.VCP = log2FoldChange, FDR.VCP = padj)
mass_spec.dge <- mass_spec.res  %>% select(gene_name, log2FC.VCP.ms = lfc, FDR.VCP.ms = padj)
sod1_datasets.dge <- tyzack$res %>% select(gene_name, gene_id, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj)
c9orf72_datasets.dge <- birger$res %>% select(gene_name, gene_id, log2FC.C9ORF72 = log2FoldChange, FDR.C9ORF72 = padj)
fus_datasets.dge <- neyrinck$res %>% select(gene_name, gene_id, log2FC.FUS = log2FoldChange, FDR.FUS = padj)
sporadic.dge <- ferraiuolo.res %>% select(gene_name, log2FC.sporadic = log2FoldChange, FDR.sporadic = pvalue)
# a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
barbar.dge <- barbar$res %>% select(gene_name, gene_id, log2FC.barbar = log2FoldChange, FDR.barbar = padj)
leng.dge <- leng$res %>% select(gene_name, gene_id, log2FC.leng = log2FoldChange, FDR.leng = padj)
TCW.dge <- TCW$res %>% select(gene_name, gene_id, log2FC.TCW = log2FoldChange, FDR.TCW = padj)
li.dge <- li$res %>% select(gene_name, gene_id, log2FC.li = log2FoldChange, FDR.li = padj)
krencik.dge <- krencik$res %>% select(gene_name, gene_id, log2FC.krencik = log2FoldChange, FDR.krencik = padj)
zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
anderson.dge = anderson$res %>%  select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
supp.liddelow.marker <- vcp_datasets.dge %>% full_join(sod1_datasets.dge)%>% full_join(c9orf72_datasets.dge) %>% full_join(fus_datasets.dge) %>% full_join(mass_spec.dge) %>% full_join(sporadic.dge) %>%
  full_join(barbar.dge) %>% full_join(leng.dge) %>% full_join(TCW.dge) %>% full_join(li.dge) %>% full_join(krencik.dge) %>%
  left_join(anderson.dge, by = "gene_name") %>% left_join(zamanian.A2.dge, by = "gene_name") %>% 
  filter(gene_name %in% astrocyte.reactivity.markers$gene_name, !gene_name %in% c("MICA", "HLA-E", "HLA-F")) %>% arrange(factor(gene_name, levels = astrocyte.reactivity.markers$gene_name)) %>%
  select(gene_name, "mass spec\nVCP vs CTRL" = log2FC.VCP.ms,  "RNAseq\nVCP vs CTRL" = log2FC.VCP, "SOD1 vs CTRL" = log2FC.SOD1,"C9orf72 vs CTRL" = log2FC.C9ORF72, "FUS vs CTRL" = log2FC.FUS, 
         "Sporadic vs CTRL" = log2FC.sporadic,   # "hiPSC\nTNFa IL1a C1q\nvs vehicle" = log2FC.A1, 
         "Barbar protocol" = log2FC.barbar,  "Leng protocol" = log2FC.leng,  "TCW protocol" = log2FC.TCW,  "Li protocol" = log2FC.li,  "Krencik protocol" = log2FC.krencik, 
         "Zamanian et al.\nmouse MCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse SCI vs CTRL" = log2FC.SCI)

supp.liddelow.marker %>%group_by(gene_name) %>% filter(n()>1) # any duplicate gene_names?


supp.liddelow.marker.mat <- make_matrix(select(supp.liddelow.marker,-gene_name), pull(supp.liddelow.marker,gene_name))
supp.liddelow.marker.mat.scale <- scale(supp.liddelow.marker.mat, center = FALSE) # make variance equal between datasets
# supp.liddelow.marker.mat.scale[supp.liddelow.marker.mat.scale > 3] <- 3 # crop outliers to improve colour distribution
# liddelow.marker.mat.scale = t(scale(t(liddelow.marker.mat.scale))) # row scale
# liddelow.marker.mat.scale <- liddelow.marker.mat.scale[!is.infinite(rowSums(liddelow.marker.mat.scale)),]

supp.liddelow.markers.filt <- astrocyte.reactivity.markers %>% filter(gene_name %in% supp.liddelow.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

supp.liddelow.marker.heatmap <- Heatmap(supp.liddelow.marker.mat.scale, 
          show_heatmap_legend = FALSE, col = col_ramp_reactivity.markers,
          cluster_rows = FALSE, cluster_row_slices = FALSE, cluster_columns = FALSE,
          row_split = factor(supp.liddelow.markers.filt$group, levels = unique(supp.liddelow.markers.filt$group)), border = TRUE,
          row_order = supp.liddelow.markers.filt$gene_name,
          row_names_gp = gpar(fontsize = 7), column_names_gp = gpar(fontsize = 8),
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("Pan\nreactive", "A1", "A2"), labels_gp = gpar(fontsize = 7), labels_rot = 0)),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("ALS individual datasets", "A1 individual protocols", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,1,1,1,1,1,2,2,2,2,2,3,3),
          row_title = "Liddelow et al. Reactive astrocyte markers", row_title_gp = gpar(fontsize = 8))
supp.liddelow.marker.heatmap

```

## Escartin heatmap

Table 1 <https://www.nature.com/articles/s41593-020-00783-4>

```{r}
# Supp
vcp_datasets.dge <- patani$res %>% select(gene_name, gene_id, log2FC.VCP = log2FoldChange, FDR.VCP = padj)
mass_spec.dge <- mass_spec.res  %>% select(gene_name, log2FC.VCP.ms = lfc, FDR.VCP.ms = padj)
sod1_datasets.dge <- tyzack$res %>% select(gene_name, gene_id, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj)
c9orf72_datasets.dge <- birger$res %>% select(gene_name, gene_id, log2FC.C9ORF72 = log2FoldChange, FDR.C9ORF72 = padj)
fus_datasets.dge <- neyrinck$res %>% select(gene_name, gene_id, log2FC.FUS = log2FoldChange, FDR.FUS = padj)
sporadic.dge <- ferraiuolo.res %>% select(gene_name, log2FC.sporadic = log2FoldChange, FDR.sporadic = pvalue)
# a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
barbar.dge <- barbar$res %>% select(gene_name, gene_id, log2FC.barbar = log2FoldChange, FDR.barbar = padj)
leng.dge <- leng$res %>% select(gene_name, gene_id, log2FC.leng = log2FoldChange, FDR.leng = padj)
TCW.dge <- TCW$res %>% select(gene_name, gene_id, log2FC.TCW = log2FoldChange, FDR.TCW = padj)
li.dge <- li$res %>% select(gene_name, gene_id, log2FC.li = log2FoldChange, FDR.li = padj)
krencik.dge <- krencik$res %>% select(gene_name, gene_id, log2FC.krencik = log2FoldChange, FDR.krencik = padj)
# guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.mouse.A1 = log2FoldChange, FDR.mouse.A1 = padj)
zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
anderson.dge = anderson$res %>%  select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
supp.escartin.marker <- vcp_datasets.dge %>% full_join(sod1_datasets.dge)%>% full_join(c9orf72_datasets.dge) %>% full_join(fus_datasets.dge) %>% full_join(mass_spec.dge) %>% full_join(sporadic.dge) %>%
  full_join(barbar.dge) %>% full_join(leng.dge) %>% full_join(TCW.dge) %>% full_join(li.dge) %>% full_join(krencik.dge) %>%
  left_join(anderson.dge, by = "gene_name") %>% left_join(zamanian.A2.dge, by = "gene_name") %>% 
  filter(gene_name %in% escartin.markers$gene_name, !gene_name %in% c("MICA", "HLA-E", "HLA-F")) %>% arrange(factor(gene_name, levels = escartin.markers$gene_name)) %>%
  select(gene_name, "mass spec\nVCP vs CTRL" = log2FC.VCP.ms,  "RNAseq\nVCP vs CTRL" = log2FC.VCP, "SOD1 vs CTRL" = log2FC.SOD1,"C9orf72 vs CTRL" = log2FC.C9ORF72, "FUS vs CTRL" = log2FC.FUS, 
         "Sporadic vs CTRL" = log2FC.sporadic, # "hiPSC\nTNFa IL1a C1q\nvs vehicle" = log2FC.A1, 
         "Barbar protocol" = log2FC.barbar,  "Leng protocol" = log2FC.leng,  "TCW protocol" = log2FC.TCW,  "Li protocol" = log2FC.li,  "Krencik protocol" = log2FC.krencik, 
         "Zamanian et al.\nmouse MCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse SCI vs CTRL" = log2FC.SCI)


supp.escartin.marker.mat <- make_matrix(select(supp.escartin.marker,-gene_name), pull(supp.escartin.marker,gene_name))
supp.escartin.marker.mat.scale <- scale(supp.escartin.marker.mat, center = FALSE) # make variance equal between datasets
# supp.escartin.marker.mat.scale[supp.escartin.marker.mat.scale > 3] <- 3 # crop outliers to improve colour distribution
# escartin.marker.mat.scale = t(scale(t(escartin.marker.mat.scale))) # row scale
# escartin.marker.mat.scale <- escartin.marker.mat.scale[!is.infinite(rowSums(escartin.marker.mat.scale)),]

supp.escartin.markers.filt <- escartin.markers %>% filter(gene_name %in% supp.escartin.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

supp.escartin.marker.heatmap <- Heatmap(supp.escartin.marker.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_ramp_reactivity.markers,
          cluster_rows = FALSE, cluster_row_slices = FALSE, cluster_columns = FALSE,
          row_split = factor(supp.escartin.markers.filt$group, levels = unique(supp.escartin.markers.filt$group)), border = TRUE,
          row_order = supp.escartin.markers.filt$gene_name,
          row_names_gp = gpar(fontsize = 7), column_names_gp = gpar(fontsize = 8),
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white", "white", "white", "white")),
                                                                labels = c("Cytoskeleton", "Metabolism", "Chaperone", "Secreted\nproteins", "Cell\nsignalling", "Channels -\nTransporters"), labels_gp = gpar(fontsize = 7), labels_rot = 0)),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("ALS individual datasets", "A1 individual protocols", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,1,1,1,1,1,2,2,2,2,2,3,3),
          row_title = "Escartin et al. Reactive astrocyte markers", row_title_gp = gpar(fontsize = 8))
supp.escartin.marker.heatmap


# # All datasets
# als_datasets.dge <- als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
# vcp_datasets.dge <- patani$res %>% select(gene_name, gene_id, log2FC.VCP = log2FoldChange, FDR.VCP = padj)
# mass_spec.dge <- mass_spec.res  %>% select(gene_name, log2FC.VCP.ms = lfc, FDR.VCP.ms = padj)
# sod1_datasets.dge <- tyzack$res %>% select(gene_name, gene_id, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj)
# c9orf72_datasets.dge <- birger$res %>% select(gene_name, gene_id, log2FC.C9ORF72 = log2FoldChange, FDR.C9ORF72 = padj)
# a1_datasets.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
# zamanian.A1.dge = zamanian.A1.res %>%  select(gene_name, log2FC.A1.zamanian = log2FoldChange, FDR.A1.zamanian = padj)
# zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
# all_datasets.dge <- als_datasets.dge %>% full_join(a1_datasets.dge)  %>% full_join(vcp_datasets.dge) %>% full_join(sod1_datasets.dge)%>% full_join(c9orf72_datasets.dge) %>% full_join(mass_spec.dge) %>% left_join(zamanian.A1.dge) %>% left_join(zamanian.A2.dge)
# 
# escartin.marker <- all_datasets.dge %>% filter(gene_name %in% escartin.markers$gene_name) %>% arrange(factor(gene_name, levels = escartin.markers$gene_name)) %>%
#   select(gene_name, "mass spec\nVCP vs CTRL" = log2FC.VCP.ms,  "RNAseq\nVCP vs CTRL" = log2FC.VCP, "SOD1 vs CTRL" = log2FC.SOD1,"C9orf72 vs CTRL" = log2FC.C9ORF72, "Meta-analysis\npan-ALS vs CTRL" = log2FC.ALS, 
#          "a1_datasets hiPSC" = log2FC.A1, "Zamanian\nmouse A1 vs A0" = log2FC.A1.zamanian, "Zamanian\nmouse A2 vs A0" = log2FC.A2)
# escartin.marker.mat <- make_matrix(select(escartin.marker,-gene_name), pull(escartin.marker,gene_name))
# escartin.marker.mat.scale <- scale(escartin.marker.mat, center = FALSE) # make variance equal between datasets
# # escartin.marker.mat.scale[escartin.marker.mat.scale > 6] <- 6 # crop outliers to improve colour distribution
# # escartin.marker.mat.scale = t(scale(t(escartin.marker.mat.scale))) # row scale
# # escartin.marker.mat.scale <- escartin.marker.mat.scale[!is.infinite(rowSums(escartin.marker.mat.scale)),]
# 
# escartin.markers.filt <- escartin.markers %>% filter(gene_name %in% escartin.marker$gene_name)
# 
# escartin.marker.heatmap <- as.ggplot(
#   Heatmap(escartin.marker.mat.scale, 
#           heatmap_legend_param = list(title = ""), 
#           cluster_rows = FALSE, cluster_columns = FALSE,
#           row_split = factor(escartin.markers.filt$group, levels = unique(escartin.markers.filt$group)),
#           row_order = escartin.markers.filt$gene_name,
#           row_names_gp = gpar(fontsize = 8), column_names_gp = gpar(fontsize = 10), border = TRUE,
#           right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white", "white", "white", "white")),
#                                                                 labels = c("cytoskeleton", "metabolism", "chaperone", "secreted", "signalling", "channels"), labels_gp = gpar(fontsize = 7)), annotation_name_rot = 45),
#           row_title = NULL, cluster_row_slices = FALSE,
#           column_names_rot = 45, column_names_centered = TRUE,
#           column_split =  c(1,2,2,2,3,3,3,3), column_title = NULL
#           # bottom_annotation = HeatmapAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("mass spec", "RNAs"), labels_gp = gpar(fontsize = 10))), border_gp = gpar(col = "black")
#           ))
# escartin.marker.heatmap

```

## Merge

```{r}
figS6.merged <- ggarrange(
  ggarrange(A1.hipsc_ALS_scatter.liddelow, A1.sporadic_ALS_scatter.liddelow, ncol = 2, labels = c("A", "B")),
  ggarrange(MCAO_ALS_scatter.liddelow, SCI_ALS_scatter.liddelow, ncol = 2, labels = c("C", "D")),
  ggarrange(as.ggplot(supp.liddelow.marker.heatmap), as.ggplot(supp.escartin.marker.heatmap), ncol = 2, labels = c("E", "F"), widths = c(1,1.1)), 
  nrow = 3, heights = c(1.1,0.8,1))
# figS6.merged
ggsave(figS6.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS6.merged.reactive.genes.png", height = 15, width = 11)

```

# Fig S7 PROGENy pathway heatmaps

```{r}
library(circlize)
col_fun = colorRamp2(c(-4, 0, 4), c("blue", "white", "red")) # set colour limits to -4 to 4 for all heatmaps
col_fun(seq(-4, 4))

prog_matrix <- getModel("Human", top=100) %>% as.data.frame()  %>% tibble::rownames_to_column("GeneID")

als_datasets.res.progeny <- als_datasets$res %>% select(gene_name, ALS = log2FoldChange, ALS.FDR = padj) %>% distinct(gene_name, .keep_all = TRUE) 
barbar.res.progeny <- barbar$res %>% select(gene_name, A1 = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) 
# guttenplan.A1.res.progeny <- guttenplan.A1$res %>% select(gene_name, `mouse A1` = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) 
zamanian.A2.res.progeny <- zamanian.A2.res %>% select(gene_name, MCAO = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) 
anderson.res.progeny <- anderson$res %>% select(gene_name, SCI = log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) 


# TGFb responsive genes
TGFb_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, TGFb) %>% filter(TGFb != 0)
als_a1_protective.TGFb <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% TGFb_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.TGFb.row.labels = als_a1_protective.TGFb %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.TGFb.row.index = match( als_a1_protective.TGFb.row.labels, als_a1_protective.TGFb$gene_name)
als_a1_protective.TGFb = als_a1_protective.TGFb %>% select(-ALS.FDR)
als_a1_protective.TGFb.mat <- make_matrix(select(als_a1_protective.TGFb,-gene_name), pull(als_a1_protective.TGFb,gene_name))
als_a1_protective.TGFb.mat.scale <- scale(als_a1_protective.TGFb.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.TGFb.heatmap <- Heatmap(als_a1_protective.TGFb.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.TGFb$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.TGFb.row.index, labels = als_a1_protective.TGFb.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("TGFb pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.TGFb.heatmap

als_a1_protective.TGFb %>% arrange(-ALS) 

# A1_ALS_scatter.TGFb <- ggscatter(als_a1_protective.TGFb, x = "ALS", y = "A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.TGFb, aes(x = log2FC.ALS, y = A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.TGFb, ALS > 1), aes(x = ALS, y = A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      
#   geom_text_repel(data = filter(als_a1_protective.TGFb, A1 < -1, ALS < -1), aes(x = ALS, y = A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +
#   annotate(geom="text", x=3, y=5, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(TGFb~Pathway~correlation))
# A1_ALS_scatter.TGFb


# WNT responsive genes
WNT_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, WNT) %>% filter(WNT != 0)
als_a1_protective.WNT <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% WNT_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.WNT.row.labels = als_a1_protective.WNT %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.WNT.row.index = match( als_a1_protective.WNT.row.labels, als_a1_protective.WNT$gene_name)
als_a1_protective.WNT = als_a1_protective.WNT %>% select(-ALS.FDR)
als_a1_protective.WNT.mat <- make_matrix(select(als_a1_protective.WNT,-gene_name), pull(als_a1_protective.WNT,gene_name))
als_a1_protective.WNT.mat.scale <- scale(als_a1_protective.WNT.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.WNT.heatmap <- Heatmap(als_a1_protective.WNT.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.WNT$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.WNT.row.index, labels = als_a1_protective.WNT.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("WNT pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.WNT.heatmap

# A1_ALS_scatter.WNT <- ggscatter(als_a1_protective.WNT, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.WNT, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.WNT, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_a1_protective.WNT, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=2, y=10, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(WNT~Pathway~correlation))
# A1_ALS_scatter.WNT

# Hypoxia responsive genes
Hypoxia_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, Hypoxia) %>% filter(Hypoxia != 0)
als_a1_protective.Hypoxia <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% Hypoxia_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.Hypoxia.row.labels = als_a1_protective.Hypoxia %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.Hypoxia.row.index = match( als_a1_protective.Hypoxia.row.labels, als_a1_protective.Hypoxia$gene_name)
als_a1_protective.Hypoxia = als_a1_protective.Hypoxia %>% select(-ALS.FDR)
als_a1_protective.Hypoxia.mat <- make_matrix(select(als_a1_protective.Hypoxia,-gene_name), pull(als_a1_protective.Hypoxia,gene_name))
als_a1_protective.Hypoxia.mat.scale <- scale(als_a1_protective.Hypoxia.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.Hypoxia.heatmap <- Heatmap(als_a1_protective.Hypoxia.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.Hypoxia$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.Hypoxia.row.index, labels = als_a1_protective.Hypoxia.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("Hypoxia pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.Hypoxia.heatmap
# A1_ALS_scatter.Hypoxia <- ggscatter(als_a1_protective.Hypoxia, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.Hypoxia, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.Hypoxia, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_a1_protective.Hypoxia, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=2, y=4, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(Hypoxia~Pathway~correlation))
# A1_ALS_scatter.Hypoxia

# TNFa responsive genes
TNFa_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, TNFa) %>% filter(TNFa != 0)
als_a1_protective.TNFa <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% TNFa_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.TNFa.row.labels = als_a1_protective.TNFa %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.TNFa.row.index = match( als_a1_protective.TNFa.row.labels, als_a1_protective.TNFa$gene_name)
als_a1_protective.TNFa = als_a1_protective.TNFa %>% select(-ALS.FDR)
als_a1_protective.TNFa.mat <- make_matrix(select(als_a1_protective.TNFa,-gene_name), pull(als_a1_protective.TNFa,gene_name))
als_a1_protective.TNFa.mat.scale <- scale(als_a1_protective.TNFa.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.TNFa.heatmap <- Heatmap(als_a1_protective.TNFa.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.TNFa$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.TNFa.row.index, labels = als_a1_protective.TNFa.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("TNFa pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.TNFa.heatmap
# A1_ALS_scatter.TNFa <- ggscatter(als_a1_protective.TNFa, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.TNFa, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.TNFa, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_a1_protective.TNFa, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=2, y=10, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(TNFa~Pathway~correlation))
# A1_ALS_scatter.TNFa


# VEGF responsive genes
VEGF_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, VEGF) %>% filter(VEGF != 0)
als_a1_protective.VEGF <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% VEGF_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.VEGF.row.labels = als_a1_protective.VEGF %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.VEGF.row.index = match( als_a1_protective.VEGF.row.labels, als_a1_protective.VEGF$gene_name)
als_a1_protective.VEGF = als_a1_protective.VEGF %>% select(-ALS.FDR)
als_a1_protective.VEGF.mat <- make_matrix(select(als_a1_protective.VEGF,-gene_name), pull(als_a1_protective.VEGF,gene_name))
als_a1_protective.VEGF.mat.scale <- scale(als_a1_protective.VEGF.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.VEGF.heatmap <- Heatmap(als_a1_protective.VEGF.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.VEGF$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.VEGF.row.index, labels = als_a1_protective.VEGF.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("VEGF pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.VEGF.heatmap
# A1_ALS_scatter.VEGF <- ggscatter(als_a1_protective.VEGF, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.VEGF, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.VEGF, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_a1_protective.VEGF, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=2, y=4, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(VEGF~Pathway~correlation))
# A1_ALS_scatter.VEGF

# NFkB responsive genes
NFkB_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, NFkB) %>% filter(NFkB != 0)
als_a1_protective.NFkB <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% NFkB_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.NFkB.row.labels = als_a1_protective.NFkB %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.NFkB.row.index = match( als_a1_protective.NFkB.row.labels, als_a1_protective.NFkB$gene_name)
als_a1_protective.NFkB = als_a1_protective.NFkB %>% select(-ALS.FDR)
als_a1_protective.NFkB.mat <- make_matrix(select(als_a1_protective.NFkB,-gene_name), pull(als_a1_protective.NFkB,gene_name))
als_a1_protective.NFkB.mat.scale <- scale(als_a1_protective.NFkB.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.NFkB.heatmap <- Heatmap(als_a1_protective.NFkB.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.NFkB$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.NFkB.row.index, labels = als_a1_protective.NFkB.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("NFkB pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.NFkB.heatmap
# A1_ALS_scatter.NFkB <- ggscatter(als_a1_protective.NFkB, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_a1_protective.NFkB, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_a1_protective.NFkB, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_a1_protective.NFkB, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=2, y=10, label="ALS & A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(NFkB~Pathway~correlation))
# A1_ALS_scatter.NFkB

# PI3K responsive genes
PI3K_matrix <- prog_matrix %>% as.tibble() %>% select(GeneID, PI3K) %>% filter(PI3K != 0)
als_a1_protective.PI3K <- als_datasets.res.progeny %>% full_join(barbar.res.progeny) %>% full_join(zamanian.A2.res.progeny) %>% full_join(anderson.res.progeny) %>% 
  filter(gene_name %in% PI3K_matrix$GeneID) %>% drop_na() %>% arrange(ALS + A1)
als_a1_protective.PI3K.row.labels = als_a1_protective.PI3K %>% filter(ALS.FDR < 0.05) %>% pull(gene_name)
als_a1_protective.PI3K.row.index = match( als_a1_protective.PI3K.row.labels, als_a1_protective.PI3K$gene_name)
als_a1_protective.PI3K = als_a1_protective.PI3K %>% select(-ALS.FDR)
als_a1_protective.PI3K.mat <- make_matrix(select(als_a1_protective.PI3K,-gene_name), pull(als_a1_protective.PI3K,gene_name))
als_a1_protective.PI3K.mat.scale <- scale(als_a1_protective.PI3K.mat, center = FALSE) # make variance equal between datasets
als_a1_protective.PI3K.heatmap <- Heatmap(als_a1_protective.PI3K.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_fun, show_heatmap_legend = FALSE,
          row_order = als_a1_protective.PI3K$gene_name, cluster_rows = FALSE, cluster_columns = FALSE, row_title = NULL, column_title = NULL,
          show_row_names = FALSE, column_names_rot = 0, column_names_gp = gpar(fontsize = 10), column_names_centered = TRUE,
          right_annotation = rowAnnotation(markers = anno_mark(at = als_a1_protective.PI3K.row.index, labels = als_a1_protective.PI3K.row.labels, labels_gp = gpar(fontsize = 8))),
          left_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white")), labels = c("PI3K pathway"), labels_gp = gpar(fontsize = 10))))
als_a1_protective.PI3K.heatmap
# A1_ALS_scatter.PI3K <- ggscatter(als_datasets_barbar.PI3K, x = "log2FC.ALS", y = "log2FC.A1", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~A1:A0), size = 0.5) +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   #xlim(-10,10) + ylim(-10,10) +
#     # geom_smooth(data = als_datasets_barbar.PI3K, aes(x = log2FC.ALS, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
#     geom_text_repel(data = filter(als_datasets_barbar.PI3K, log2FC.A1 > 0, log2FC.ALS > 1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +      geom_text_repel(data = filter(als_datasets_barbar.PI3K, log2FC.A1 < -1, log2FC.ALS < -1), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
#   annotate(geom="text", x=3, y=5, label="Up in both ALS & A1", color="firebrick2", size = 3.2) + labs(subtitle = expression(PI3K~Pathway~correlation))
# A1_ALS_scatter.PI3K
```

## Merge

```{r}
progeny.heatmaps.TGFb.WNT = grid.grabExpr(draw(als_a1_protective.TGFb.heatmap %v% als_a1_protective.WNT.heatmap))
progeny.heatmaps.PI3K.Hypoxia = grid.grabExpr(draw(als_a1_protective.PI3K.heatmap %v% als_a1_protective.Hypoxia.heatmap))
progeny.heatmaps.VEGF.TNFa.NFkB = grid.grabExpr(draw(als_a1_protective.VEGF.heatmap %v% als_a1_protective.TNFa.heatmap %v% als_a1_protective.NFkB.heatmap))
progeny.heatmaps = ggarrange(progeny.heatmaps.TGFb.WNT, progeny.heatmaps.PI3K.Hypoxia, progeny.heatmaps.VEGF.TNFa.NFkB, ncol = 3)
# progeny.heatmaps
ggsave(progeny.heatmaps, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/FigS7.progeny.heatmaps.png", height = 15, width = 13.5)

```

# Table S6 SOD1 TRAP & ALS & A1

```{r}
als_datasets.dge <- als_datasets$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% 
  mutate(direction.ALS = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "up", FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "down", TRUE ~ "non-significant"))
cleveland.dge <- cleveland$res %>% select(gene_name, log2FC.TRAP = log2FoldChange, FDR.TRAP = padj) %>% 
  mutate(direction.TRAP = case_when(FDR.TRAP < 0.05 & log2FC.TRAP > 0 ~ "up", FDR.TRAP < 0.05 & log2FC.TRAP < 0 ~ "down", TRUE ~ "non-significant"))
barbar.dge <- barbar$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.A1.hipsc = log2FoldChange, FDR.A1.hipsc = padj) %>% 
  mutate(direction.A1.hipsc = case_when(FDR.A1.hipsc < 0.05 & log2FC.A1.hipsc > 0 ~ "up", FDR.A1.hipsc < 0.05 & log2FC.A1.hipsc < 0 ~ "down", TRUE ~ "non-significant"))
guttenplan.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.A1.mouse = log2FoldChange, FDR.A1.mouse = padj) %>% 
  mutate(direction.A1.mouse = case_when(FDR.A1.mouse < 0.05 & log2FC.A1.mouse > 0 ~ "up", FDR.A1.mouse < 0.05 & log2FC.A1.mouse < 0 ~ "down", TRUE ~ "non-significant"))

als_trap_a1_datasets_merged.dge <- als_datasets.dge %>% left_join(cleveland.dge) %>% left_join(barbar.dge) %>% left_join(guttenplan.dge) %>%
    mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.A1.hipsc < 0.05 & FDR.A1.mouse < 0.05 & log2FC.ALS > 0 & log2FC.A1.hipsc > 0 & log2FC.A1.mouse > 0 ~ "overlapping up",
                             FDR.ALS < 0.05 & FDR.A1.hipsc < 0.05 & FDR.A1.mouse < 0.05 & log2FC.ALS < 0 & log2FC.A1.hipsc < 0 & log2FC.A1.mouse < 0 ~ "overlapping down",
                             FDR.ALS < 0.05 & FDR.A1.hipsc < 0.05 & log2FC.ALS > 0 & log2FC.A1.hipsc > 0 ~ "ALS A1.hipsc up",
                             FDR.ALS < 0.05 & FDR.A1.hipsc < 0.05 & log2FC.ALS < 0 & log2FC.A1.hipsc < 0~ "ALS A1.hipsc down",
                             FDR.ALS < 0.05 & FDR.A1.mouse < 0.05 & log2FC.ALS > 0 & log2FC.A1.mouse > 0 ~ "ALS A1.mouse up",
                             FDR.ALS < 0.05 & FDR.A1.mouse < 0.05 & log2FC.ALS < 0 & log2FC.A1.mouse < 0~ "ALS A1.mouse down",
                             FDR.A1.hipsc < 0.05 & FDR.A1.mouse < 0.05 & log2FC.A1.hipsc > 0 & log2FC.A1.mouse > 0 ~ "A1.hipsc A1.mouse up",
                             FDR.A1.hipsc < 0.05 & FDR.A1.mouse < 0.05 & log2FC.A1.hipsc < 0 & log2FC.A1.mouse < 0~ "A1.hipsc A1.mouse down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "ALS A1.hipsc A1.mouse up", "ALS A1.hipsc A1.mouse down","ALS A1.hipsc up","ALS A1.hipsc down","ALS A1.mouse up","ALS A1.mouse down","A1.hipsc A1.mouse up","A1.hipsc A1.mouse down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, hsap.ensembl, overlap, everything())


  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "ALS up, MCAO & SCI down",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "ALS down, MCAO & SCI up",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 ~ "ALS up, MCAO down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0~ "ALS down, MCAO up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI < 0 ~ "ALS up, SCI down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI > 0 ~ "ALS down, SCI up",
           FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "overlapping up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "overlapping down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 ~ "ALS & MCAO up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0~ "ALS & MCAO down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI > 0 ~ "ALS & SCI up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI < 0~ "ALS & SCI down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("ALS up, MCAO & SCI down", "ALS down, MCAO & SCI up", "ALS up, MCAO down", "ALS down, MCAO up",  "ALS up, SCI down", "ALS down, SCI up", "overlapping up",  "overlapping down", "ALS MCAO SCI up", "ALS MCAO SCI down","ALS MCAO up","ALS MCAO down","ALS SCI up","ALS SCI down","MCAO SCI up","MCAO SCI down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, hsap.ensembl, overlap, everything())

write_csv(als_protective_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS5.overlap_als_protective_datasets.csv")



anderson.dge <- anderson$res %>% select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj) %>% 
  mutate(direction.SCI = case_when(FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "up", FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "down", TRUE ~ "non-significant"))
zamanian.A2.dge <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% 
  mutate(direction.MCAO = case_when(FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "up", FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "down", TRUE ~ "non-significant"))


peng.dge <- peng$res %>% select(gene_name, mmus.ensembl = gene_id, log2FC.TDP43 = log2FoldChange, FDR.TDP43 = padj) %>% mutate(direction.TDP43 = case_when(FDR.TDP43 < 0.05 & log2FC.TDP43 > 0 ~ "up", FDR.TDP43 < 0.05 & log2FC.TDP43 < 0 ~ "down", TRUE ~ "non-significant"))
jiang.dge <- jiang$res %>% select(gene_name, mmus.ensembl = gene_id, log2FC.MEM = log2FoldChange, FDR.MEM = padj) %>% mutate(direction.MEM = case_when(FDR.MEM < 0.05 & log2FC.MEM > 0 ~ "up", FDR.MEM < 0.05 & log2FC.MEM < 0 ~ "down", TRUE ~ "non-significant"))
# mass_spec.summary <- mass_spec.res %>% select(gene_name, logFC.ALS.MS = lfc, FDR.ALS.MS = padj)
als_datasets_barbar.dge <- als_datasets.dge %>% full_join(patani.dge) %>% full_join(barbar.dge) #%>% full_join(birger.dge) %>% full_join(tyzack.dge) 
cleveland_peng_jiang.dge <- cleveland.dge %>% full_join(peng.dge) %>% full_join(jiang.dge)
all_datasets.dge <- full_join(als_datasets_barbar.dge, cleveland_peng_jiang.dge, by = "gene_name") %>% select(gene_name, hsap.ensembl, mmus.ensembl, everything())
write_csv(all_datasets.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS3.overlap_all_datasets.dge.csv")
```

# Fig S8 Mouse individual datasets

## TDP43 Peng

### Volcano

```{r}
# Volcano
interesting.gene.labels <- peng$res %>% filter(-log10(padj) > 4, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go, astrocyte.reactive.genes)) %>% pull(gene_name) # all.reactivity.go
immune.up.genes <- peng$res %>% filter(padj < 0.05, log2FoldChange > 1, gene_name %in% all.reactivity.go, !gene_name %in% c("ANGPT1", "PID1", "TXNIP")) %>%  pull(gene_name)
phagocytosis.down.genes <- peng$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% go.pathways.msigdb$GO_PHAGOCYTOSIS) %>%  pull(gene_name)
glutamate.uptake.down.genes <- peng$res %>% filter(padj < 0.05, log2FoldChange < 1, gene_name %in% glutamate.uptake.go) %>%  pull(gene_name)
interesting.gene.labels.filt <- c(phagocytosis.down.genes, glutamate.uptake.down.genes, immune.up.genes, "ASPN", "GJA5", "CALB2", "GABRA2", "GABRB2", "SLC3A2") 

peng.volcano <- volcano_plot_deseq(data = peng.res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~TDP43~KO:CTRL)) + 
  coord_cartesian(xlim = c(-2,2), ylim = c(0,35)) +
  geom_segment(aes(x = 1, xend = 2, y= 30, yend= 30), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -1, xend = -2, y= 30, yend= 30),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 1.3, y = 35, label = "Up in TDP43 KO", color = "firebrick2", size = 2.8) + annotate("text", x = -1.3, y = 35, label = "Down in TDP43 KO", color = "dodgerblue2", size = 2.8)
peng.volcano
```

### GO terms

```{r}
peng.dge_genes <- peng$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") %>% gost(organism = "mmusculus")
peng.dge_gprofiles_filt <- peng.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in TDP43 KO ", query == "query_2" ~ " Up in TDP43 KO "), term_name = as.factor(term_name)) 
peng.dge_gprofiles_down <- peng.dge_gprofiles_filt %>% filter(query == " Down in TDP43 KO ")
peng.dge_gprofiles_up <- peng.dge_gprofiles_filt %>% filter(query == " Up in TDP43 KO ")
paste('"',unique(peng.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
# "Senescence-Associated Secretory Phenotype (SASP)",
"chromatin assembly",
"Oxidative Stress Induced Senescence",
"DNA methylation",
"chromosome organization",
"axon",
"synapse",
"neuron projection",
"anchoring junction",
"oligodendrocyte differentiation",
"glial cell differentiation",
"protein binding",
"neuron development",
# "neuron differentiation",
# "generation of neurons",
"myelination",
"neurogenesis",
"nervous system development")
peng.dge_gprofiles_filt_down <- peng.dge_gprofiles_filt %>% filter(query == " Down in TDP43 KO ")  %>% filter(term_name %in% down_list)

paste('"',unique(peng.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"integrin binding",
"actin cytoskeleton",
"response to wounding",
"anchoring junction",
"Collagen degradation",
# "regulation of cellular component movement",
"Collagen formation",
"cell adhesion",
"collagen fibril organization",
"endoplasmic reticulum lumen",
"extracellular matrix",
"Pathways of neurodegeneration - multiple diseases",
"Amyotrophic lateral sclerosis",
"Alzheimer disease",
"Huntington disease",
"Parkinson disease",
"Prion disease",
"oxidative phosphorylation",
"cellular respiration",
"mitochondrial membrane")
peng.dge_gprofiles_filt_up <- peng.dge_gprofiles_filt %>% filter(query == " Up in TDP43 KO ")  %>% filter(term_name %in% up_list)
peng.dge_gprofiles_filt_combined <- bind_rows(peng.dge_gprofiles_filt_down, peng.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in TDP43 KO ", " Down in TDP43 KO ")))
peng.dge_gprofiles_filt_combined$term_name <- gsub(" - multiple diseases", "", peng.dge_gprofiles_filt_combined$term_name)
# peng.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", peng.dge_gprofiles_filt_combined$term_name)
# peng.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", peng.dge_gprofiles_filt_combined$term_name)
peng.go_curated <- curated_profiles(gprofiles = peng.dge_gprofiles_filt_combined) + theme(legend.position = "none")
peng.go_curated

# which genes are driving the terms
peng$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
peng$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
peng$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
peng$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)
```

### GSEA: Glutamate uptake

```{r}
peng.geneList <- peng$res %>% drop_na(log2FoldChange) %>% arrange(-log2FoldChange) %>% pull(log2FoldChange)
names(peng.geneList) <- peng$res %>% drop_na(log2FoldChange) %>% arrange(-log2FoldChange) %>% pull(gene_name) %>% as.character()
peng.geneList = sort(peng.geneList, decreasing = TRUE)
glutamate.uptake_genes.list <- list("glutamate.uptake" = peng.res$gene_name[peng.res$gene_name %in% glutamate.uptake.go])
peng.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = peng.geneList)
peng.glutamate.uptake_fgseaRes
#   pathway pval padj    log2err        ES       NES
# 1: glutamate.uptake    1    1 0.06238615 0.1245761 0.4661647
peng.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], peng.geneList)  + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(TDP43~KO)) +
  annotate("text", x = 100, y = -0.05, label = paste0("NES = ", round(peng.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(peng.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
peng.glutamate.gseaplot
```

## Membralin Jiang

### Volcano

```{r}
interesting.gene.labels <- jiang$res %>% filter(-log10(padj) > 3, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go, astrocyte.reactive.genes)) %>% pull(gene_name)
jiang.volcano <- volcano_plot_deseq(data = jiang.res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~Mem~KO:CTRL)) + 
  coord_cartesian(xlim = c(-3,3), ylim = c(0,10)) +
  geom_segment(aes(x = 1, xend = 3, y= 9, yend= 9), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -1, xend = -3, y= 9, yend= 9),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 2, y = 10, label = "Up in Mem KO", color = "firebrick2", size = 2.8) + annotate("text", x = -2, y = 10, label = "Down in Mem KO", color = "dodgerblue2", size = 2.8)
jiang.volcano
```

### GO terms

```{r}
jiang.dge_genes <- jiang$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") %>% gost(organism = "mmusculus")
jiang.dge_gprofiles_filt <- jiang.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in Mem KO ", query == "query_2" ~ " Up in Mem KO "), term_name = as.factor(term_name)) 
jiang.dge_gprofiles_down <- jiang.dge_gprofiles_filt %>% filter(query == " Down in Mem KO ")
jiang.dge_gprofiles_up <- jiang.dge_gprofiles_filt %>% filter(query == " Up in Mem KO ")
paste('"',unique(jiang.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"axon",
"synaptic signaling",
"neuron development",
"generation of neurons",
"dendrite",
"glutamatergic synapse",
"nervous system development",
"neuron projection",
"synapse")
jiang.dge_gprofiles_filt_down <- jiang.dge_gprofiles_filt %>% filter(query == " Down in Mem KO ")  %>% filter(term_name %in% down_list)
paste('"',unique(jiang.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"endoplasmic reticulum",
"cytokine production",
"innate immune response",
"cell migration",
"immune response",
"defense response",
"response to cytokine",
"immune system process",
"extracellular matrix",
"response to stress")
jiang.dge_gprofiles_filt_up <- jiang.dge_gprofiles_filt %>% filter(query == " Up in Mem KO ")  %>% filter(term_name %in% up_list)
jiang.dge_gprofiles_filt_combined <- bind_rows(jiang.dge_gprofiles_filt_down, jiang.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in Mem KO ", " Down in Mem KO ")))
# jiang.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", jiang.dge_gprofiles_filt_combined$term_name)
# jiang.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", jiang.dge_gprofiles_filt_combined$term_name)
# jiang.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", jiang.dge_gprofiles_filt_combined$term_name)
jiang.go_curated <- curated_profiles(gprofiles = jiang.dge_gprofiles_filt_combined) + theme(legend.position = "none")
jiang.go_curated

# which genes are driving the terms
jiang$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
jiang$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
jiang$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
jiang$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)

```

### GSEA: Glutamate uptake

```{r}
jiang.geneList <- jiang$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(jiang.geneList) <- jiang$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
jiang.geneList = sort(jiang.geneList, decreasing = TRUE)

# GSEA glutamate uptake
glutamate.uptake_genes.list <- list("glutamate.uptake" = jiang.res$gene_name[jiang.res$gene_name %in% glutamate.uptake.go])
jiang.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = jiang.geneList)
jiang.glutamate.uptake_fgseaRes
#             pathway pval padj    log2err        ES        NES
# 1: glutamate.uptake    1    1 0.06170541 -0.185918 -0.7633311
jiang.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], jiang.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(Membralin~KO)) +
  annotate("text", x = 100, y = -0.15, label = paste0("NES = ", round(jiang.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(jiang.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
jiang.glutamate.gseaplot
```

## SOD1 guttenplan.sod1

### Volcano

```{r}
interesting.gene.labels <- guttenplan.sod1$res %>% filter(, -log10(padj) > 2, -log10(padj) < 7) %>% pull(gene_name)
guttenplan.sod1.volcano <- volcano_plot_deseq(data = guttenplan.sod1.res, labels_list = interesting.gene.labels) + xlab(expression(log[2]~fold~change~SOD1:CTRL)) + 
  coord_cartesian(xlim = c(-3,3), ylim = c(0,8)) +
  geom_segment(aes(x = 1, xend = 3, y= 7, yend= 7), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -1, xend = -3, y= 7, yend= 7),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 2, y = 7.5, label = "Up in SOD1", color = "firebrick2", size = 2.8) + annotate("text", x = -2, y = 7.5, label = "Down in SOD1", color = "dodgerblue2", size = 2.8)
guttenplan.sod1.volcano
```

### GO terms

```{r}
guttenplan.sod1.dge_genes <- guttenplan.sod1$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") %>% gost(organism = "mmusculus") 
guttenplan.sod1.dge_gprofiles_filt <- guttenplan.sod1.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " Down in SOD1 ", query == "query_2" ~ " Up in SOD1 "), term_name = as.factor(term_name)) 
guttenplan.sod1.dge_gprofiles_down <- guttenplan.sod1.dge_gprofiles_filt %>% filter(query == " Down in SOD1 ")
guttenplan.sod1.dge_gprofiles_up <- guttenplan.sod1.dge_gprofiles_filt %>% filter(query == " Up in SOD1 ")
paste('"',unique(guttenplan.sod1.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
"regulation of Schwann cell proliferation",
"synapse")
guttenplan.sod1.dge_gprofiles_filt_down <- guttenplan.sod1.dge_gprofiles_filt %>% filter(query == " Down in SOD1 ")  %>% filter(term_name %in% down_list)
paste('"',unique(guttenplan.sod1.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"retinal cone cell differentiation",
"retinal cone cell development",
"protein binding")
guttenplan.sod1.dge_gprofiles_filt_up <- guttenplan.sod1.dge_gprofiles_filt %>% filter(query == " Up in SOD1 ")  %>% filter(term_name %in% up_list)
guttenplan.sod1.dge_gprofiles_filt_combined <- bind_rows(guttenplan.sod1.dge_gprofiles_filt_down, guttenplan.sod1.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" Up in SOD1 ", " Down in SOD1 ")))
guttenplan.sod1.go_curated <- curated_profiles(gprofiles = guttenplan.sod1.dge_gprofiles_filt_combined) + theme(legend.position = "none")
guttenplan.sod1.go_curated

# which genes are driving the terms
guttenplan.sod1$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
guttenplan.sod1$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
guttenplan.sod1$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
guttenplan.sod1$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)

```

### GSEA: Glutamate uptake

```{r}
guttenplan.sod1.geneList <- guttenplan.sod1$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(guttenplan.sod1.geneList) <- guttenplan.sod1$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
guttenplan.sod1.geneList = sort(guttenplan.sod1.geneList, decreasing = TRUE)

# GSEA glutamate uptake
glutamate.uptake_genes.list <- list("glutamate.uptake" = guttenplan.sod1.res$gene_name[guttenplan.sod1.res$gene_name %in% glutamate.uptake.go])
guttenplan.sod1.glutamate.uptake_fgseaRes <- fgsea(pathways = glutamate.uptake_genes.list, stats = guttenplan.sod1.geneList)
guttenplan.sod1.glutamate.uptake_fgseaRes
# pathway  pval  padj log2err         ES       NES size
# 1: glutamate.uptake 1e-10 1e-10      NA -0.6068929 -2.474473  397
guttenplan.sod1.glutamate.gseaplot = plotEnrichment(glutamate.uptake_genes.list[["glutamate.uptake"]], guttenplan.sod1.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~Uptake)) + xlab(expression(SOD1)) +  
  annotate("text", x = 100, y = -0.15, label = paste0("NES = ", round(guttenplan.sod1.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(guttenplan.sod1.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
guttenplan.sod1.glutamate.gseaplot
#  pathway      pval      padj    log2err        ES
# 1: glutamate.uptake 0.4069952 0.4069952 0.07788401 -0.264799

```


## Overlap VCP, TDP43 KO & SOD1

```{r}
guttenplan.sod1.res.dge.up <- guttenplan.sod1$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
guttenplan.sod1.res.dge.down <- guttenplan.sod1$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
peng.res.dge.up <- peng$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
peng.res.dge.down <- peng$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
jiang.res.dge.up <- jiang$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
jiang.res.dge.down <- jiang$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
guttenplan.sod1.peng.jiang.up_genes <- list("SOD1 Up" = guttenplan.sod1.res.dge.up, "TDP43 KO Up" = peng.res.dge.up, "MEM KO Up" = jiang.res.dge.up)
guttenplan.sod1.peng.jiang.down_genes <- list("SOD1 Down" = guttenplan.sod1.res.dge.down, "TDP43 KO Down" = peng.res.dge.down, "MEM KO Down" = jiang.res.dge.down)
guttenplan.sod1.peng.jiang_venn_up <- ggvenn(guttenplan.sod1.peng.jiang.up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
guttenplan.sod1.peng.jiang_venn_down <- ggvenn(guttenplan.sod1.peng.jiang.down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
guttenplan.sod1.peng.jiang_venn = ggarrange(guttenplan.sod1.peng.jiang_venn_up, guttenplan.sod1.peng.jiang_venn_down, row = 2, ncol = 1)
guttenplan.sod1.peng.jiang_venn

# Fisher exact overlap test
unique(c(peng.res.dge.up, res.dge.up)) # 923
DGEup_TDP43 KO_VCP <- peng.res.dge.up[peng.res.dge.up %in% res.dge.up] # 15 # 1.6%
genome.size <- res %>% distinct(gene_name) %>% nrow
go.obj <- newGeneOverlap(res.dge.up,
                         peng.res.dge.up,
                         genome.size=genome.size)
testGeneOverlap(go.obj)

# GeneOverlap object:
# listA size=91
# listB size=847
# Intersection size=15
# Overlapping p-value=2.7e-12
# Jaccard Index=0.0

unique(c(peng.res.dge.down, res.dge.down)) # 1087 
DGEdown_TDP43 KO_VCP <- peng.res.dge.down[peng.res.dge.down %in% res.dge.down] # 10 0.92%
go.obj <- newGeneOverlap(res.dge.down,
                         peng.res.dge.down,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=108
# listB size=989
# Intersection size=10
# Overlapping p-value=1.2e-05
# Jaccard Index=0.0

unique(c(guttenplan.sod1.res.dge.up, res.dge.up)) # 1381
DGEup_SOD1_VCP <- guttenplan.sod1.res.dge.up[guttenplan.sod1.res.dge.up %in% res.dge.up] # 15 1.1%
go.obj <- newGeneOverlap(res.dge.up,
                         guttenplan.sod1.res.dge.up,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=91
# listB size=1305
# Intersection size=15
# Overlapping p-value=1.1e-09
# Jaccard Index=0.0

unique(c(guttenplan.sod1.res.dge.down, res.dge.down)) # 2013 
DGEdown_SOD1_VCP <- guttenplan.sod1.res.dge.down[guttenplan.sod1.res.dge.down %in% res.dge.down] # 18 0.9%
go.obj <- newGeneOverlap(res.dge.down,
                         guttenplan.sod1.res.dge.down,
                         genome.size=genome.size)
testGeneOverlap(go.obj)
# GeneOverlap object:
# listA size=108
# listB size=1923
# Intersection size=18
# Overlapping p-value=9e-09
# Jaccard Index=0.0

unique(c(jiang.res.dge.up, res.dge.up)) # 1418
DGEup_MEM KO_VCP <- jiang.res.dge.up[jiang.res.dge.up %in% res.dge.up] # 19 
newGeneOverlap(res.dge.up, jiang.res.dge.up, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=91
# listB size=1346
# Intersection size=19
# Overlapping p-value=1.3e-13
# Jaccard Index=0.0

unique(c(jiang.res.dge.down, res.dge.down)) # 1742
DGEdown_MEM KO_VCP <- jiang.res.dge.down[jiang.res.dge.down %in% res.dge.down] # 26 
newGeneOverlap(res.dge.down, jiang.res.dge.down, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=108
# listB size=1660
# Intersection size=26
# Overlapping p-value=1.6e-17
# Jaccard Index=0.0

DGEup_TDP43 KO_VCP_SOD1 = DGEup_TDP43 KO_VCP[DGEup_TDP43 KO_VCP %in% DGEup_SOD1_VCP] # "PLN"    "GJB2"   "GATD3A" "IGFBP5"
DGEdown_TDP43 KO_VCP_SOD1 = DGEdown_TDP43 KO_VCP[DGEdown_TDP43 KO_VCP %in% DGEdown_SOD1_VCP] #"RYR2"   "BRINP2" "LRRC3B" "MOB3B" 

DGEup_TDP43 KO_VCP_SOD1[DGEup_TDP43 KO_VCP_SOD1 %in% DGEup_MEM KO_VCP] # GJB2
DGEdown_TDP43 KO_VCP_SOD1[DGEdown_TDP43 KO_VCP_SOD1 %in% DGEdown_MEM KO_VCP] #"LRRC3B" "MOB3B" 

# Chi-squared 3 way overlap
list1 <- unique(res.dge.up[!is.na(res.dge.up)])
list2 <- unique(guttenplan.sod1.res.dge.up[!is.na(guttenplan.sod1.res.dge.up)])
list3 <- unique(peng.res.dge.up[!is.na(peng.res.dge.up)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 0.001218456

list1 <- unique(res.dge.down[!is.na(res.dge.down)])
list2 <- unique(guttenplan.sod1.res.dge.down[!is.na(guttenplan.sod1.res.dge.down)])
list3 <- unique(peng.res.dge.down[!is.na(peng.res.dge.down)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# $pvalue
# [1] 0.02202255



IRdown_DGEup_SOD1_VCP <- IRdown_DGEup_SOD1[IRdown_DGEup_SOD1 %in% IRdown_DGEup_VCP]
IRdown_DGEup_TDP43 KO_VCP <- IRdown_DGEup_TDP43 KO[IRdown_DGEup_TDP43 KO %in% IRdown_DGEup_VCP]
IRdown_DGEup_SOD1_VCP_TDP43 KO <- IRdown_DGEup_SOD1_VCP[IRdown_DGEup_SOD1_VCP %in% IRdown_DGEup_TDP43 KO]
IRdown_DGEup_SOD1_VCP_TDP43 KO[IRdown_DGEup_SOD1_VCP_TDP43 KO %in% all.reactivity.go] # 4 are relevent to reactivity "FLNA"  "PLOD3" "MRC2"  "ACTN4"

IRdown_A1_ALS[IRdown_A1_ALS %in% all.reactivity.go] # "HSPG2"   "PSMD11"  "NFKBIZ"  "DNAJC2"  "ERF"     "TINF2"   "OSMR"    "TNIK"    "ILK"     "NUP188"  "STIP1"   "TBK1"    "MCAM"    "ARHGEF2" "NT5C3A"  "FN1"     "POLR3C"


# ggsave(guttenplan.sod1.peng.jiang_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/guttenplan.sod1.peng.jiang_venn_up.png", height = 5, width = 5)
# ggsave(guttenplan.sod1.peng.jiang_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/guttenplan.sod1.peng.jiang_venn_down.png", height = 5, width = 5)

# barbar.guttenplan.sod1.up_genes <- list("A1 up" = barbar.res.dge.up, "SOD1 up" = guttenplan.sod1.res.dge.up)
# barbar.guttenplan.sod1.down_genes <- list("A1 down" = barbar.res.dge.down, "SOD1 down" = guttenplan.sod1.res.dge.down)
# barbar.peng.up_genes <- list("A1 up" = barbar.res.dge.up, "TDP43 KO up" = peng.res.dge.up)
# barbar.peng.down_genes <- list("A1 down" = barbar.res.dge.down, "TDP43 KO down" = peng.res.dge.down)

# guttenplan.sod1_barbar_venn_up <- ggvenn(barbar.guttenplan.sod1.up_genes, fill_color = c("dodgerblue3", "firebrick1"),show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# guttenplan.sod1_barbar_venn_up
# guttenplan.sod1_barbar_venn_down <- ggvenn(barbar.guttenplan.sod1.down_genes, fill_color = c("dodgerblue3", "firebrick1"), show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# guttenplan.sod1_barbar_venn_down
# ggsave(guttenplan.sod1_barbar_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/guttenplan.sod1_barbar_venn_up.png", height = 3, width = 3)
# ggsave(guttenplan.sod1_barbar_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/guttenplan.sod1_barbar_venn_down.png", height = 3, width = 3)
# 
# peng_barbar_venn_up <- ggvenn(barbar.peng.up_genes, fill_color = c("dodgerblue3", "firebrick1"),show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# peng_barbar_venn_up
# peng_barbar_venn_down <- ggvenn(barbar.peng.down_genes, fill_color = c("dodgerblue3", "firebrick1"), show_percentage = FALSE, stroke_size = 0.5, set_name_size = 4)
# peng_barbar_venn_down
# ggsave(peng_barbar_venn_up, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/peng_barbar_venn_up.png", height = 3, width = 3)
# ggsave(peng_barbar_venn_down, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/peng_barbar_venn_down.png", height = 3, width = 3)
```

## GSEA glutamate uptake

GSEA of glutamate uptake & phagocytosis GO categories in ALS and A1 astrocytes

```{r}
mouse_als_datasets.geneList <- mouse_als_datasets$res %>% drop_na(log2FoldChange) %>% pull(log2FoldChange)
names(mouse_als_datasets.geneList) <- mouse_als_datasets$res %>% drop_na(log2FoldChange) %>% pull(gene_name) %>% as.character()
mouse_als_datasets.geneList = sort(mouse_als_datasets.geneList, decreasing = TRUE)
mouse_als_datasets.glutamate.uptake_genes.list <- list("glutamate.uptake" = mouse_als_datasets$res$gene_name[mouse_als_datasets$res$gene_name %in% glutamate.uptake.go]) # gprofiler_database$`glutamatergic synapse`
mouse_als_datasets.glutamate.uptake_fgseaRes <- fgsea(pathways = mouse_als_datasets.glutamate.uptake_genes.list, stats = mouse_als_datasets.geneList)
mouse_als_datasets.glutamate.uptake_fgseaRes
#             pathway     pval     padj    log2err         ES        NES size
# 1: glutamate.uptake 0.970297 0.970297 0.01675823 -0.2191383 -0.8031854  398
mouse_als_datasets.glutamate.uptake.gseaplot = plotEnrichment(mouse_als_datasets.glutamate.uptake_genes.list[["glutamate.uptake"]], mouse_als_datasets.geneList) + 
  theme(axis.text=element_text(size=8), axis.title=element_text(size=10)) + ylab(expression(Glutamate~uptake)) + xlab(expression(mouse~ALS~model)) + 
  annotate("text", x = 100, y = -0.15, label = paste0("NES = ", round(mouse_als_datasets.glutamate.uptake_fgseaRes$NES, digits = 3),"\nP = ", round(mouse_als_datasets.glutamate.uptake_fgseaRes$pval, digits = 4)), size = 3, hjust = 0)
mouse_als_datasets.glutamate.uptake.gseaplot


mouse_als_datasets$res %>% filter(gene_name %in% glutamate.uptake.go, padj < 0.05)
filter(mouse_als_datasets.res, gene_name %in% glutamate.uptake.go, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(mouse_als_datasets.res, gene_name %in% gprofiler_database$`glutamatergic synapse`, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(mouse_als_datasets.res, gene_name %in% go.pathways.msigdb$GO_GLUTAMATE_METABOLIC_PROCESS, padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)
filter(mouse_als_datasets.res, gene_name %in% c("SLC1A2", "TMEM259"), padj < 0.05, log2FoldChange < 0) %>% arrange(log2FoldChange)

glutamate.uptake.go <- c(go.pathways.msigdb$GO_GLUTAMATE_BINDING, go.pathways.msigdb$GO_GLUTAMATE_BIOSYNTHETIC_PROCESS, go.pathways.msigdb$GO_GLUTAMATE_GATED_CALCIUM_ION_CHANNEL_ACTIVITY, go.pathways.msigdb$GO_GLUTAMATE_METABOLIC_PROCESS, gprofiler_database$`glutamatergic synapse`, gprofiler_database$`glutamate reuptake`)
```

## Merge

```{r}
peng.guttenplan.sod1.neyrink.gsea = ggarrange(peng.glutamate.gseaplot, guttenplan.sod1.glutamate.gseaplot, jiang.glutamate.gseaplot, mouse_als_datasets.glutamate.uptake.gseaplot, nrow = 2, ncol = 2)
# peng.phagocytosis.gseaplot, guttenplan.sod1.phagocytosis.gseaplot, jiang.phagocytosis.gseaplot,

figS6.merged <- ggarrange(
  ggarrange(peng.volcano, guttenplan.sod1.volcano, jiang.volcano, ncol = 3, labels = c("A", "B", "C")),
  ggarrange(peng.go_curated, guttenplan.sod1.go_curated, jiang.go_curated, ncol = 3, labels = c("D", "E", "F")),
  # guttenplan.sod1.peng.jiang_venn, 
  ggarrange(ggarrange(guttenplan.sod1.peng.jiang_venn_up, guttenplan.sod1.peng.jiang_venn_down, nrow = 2), peng.guttenplan.sod1.neyrink.gsea, ncol = 2, widths = c(0.7,1.5), labels = c("G", "H")),
  nrow = 3,heights = c(0.9,0.7,1.3))
# figS6.merged
ggsave(figS6.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS6.merged.png", height = 13, width = 11)


  
peng.guttenplan.sod1.gseaplot.merged = ggarrange(phagocytosis.gseaplot, glutamate.gseaplot, peng.phagocytosis.gseaplot, peng.glutamate.gseaplot, guttenplan.sod1.phagocytosis.gseaplot, guttenplan.sod1.glutamate.gseaplot, ncol = 2, nrow = 3, labels = )
ggsave(peng.guttenplan.sod1.gseaplot.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/peng.guttenplan.sod1.gseaplot.merged.png", height = 8, width = 8)

```

# Table S6. Overlap mouse ALS datasets

```{r}
peng.dge <- peng$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.TDP43 = log2FoldChange, FDR.TDP43 = padj) %>% mutate(direction.TDP43 = case_when(FDR.TDP43 < 0.05 & log2FC.TDP43 > 0 ~ "up", FDR.TDP43 < 0.05 & log2FC.TDP43 < 0 ~ "down", TRUE ~ "non-significant"))
jiang.dge <- jiang$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.membralin = log2FoldChange, FDR.membralin = padj) %>% mutate(direction.membralin = case_when(FDR.membralin < 0.05 & log2FC.membralin > 0 ~ "up", FDR.membralin < 0.05 & log2FC.membralin < 0 ~ "down", TRUE ~ "non-significant"))
guttenplan.sod1.dge <- guttenplan.sod1$res %>% select(gene_name, hsap.ensembl = gene_id, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj) %>% mutate(direction.SOD1 = case_when(FDR.SOD1 < 0.05 & log2FC.SOD1 > 0 ~ "up", FDR.SOD1 < 0.05 & log2FC.SOD1 < 0 ~ "down", TRUE ~ "non-significant"))
mouse_als_datasets_merged.dge <- peng.dge %>% full_join(guttenplan.sod1.dge) %>% full_join(jiang.dge) %>% 
  mutate(overlap = case_when(FDR.TDP43 < 0.05 & FDR.membralin < 0.05 & FDR.SOD1 < 0.05 & log2FC.TDP43 > 0 & log2FC.membralin > 0 & log2FC.SOD1 > 0 ~ "overlapping up",
                             FDR.TDP43 < 0.05 & FDR.membralin < 0.05 & FDR.SOD1 < 0.05 & log2FC.TDP43 < 0 & log2FC.membralin < 0 & log2FC.SOD1 < 0 ~ "overlapping down",
                             FDR.TDP43 < 0.05 & FDR.membralin < 0.05 & log2FC.TDP43 > 0 & log2FC.membralin > 0 ~ "TDP43 membralin up",
                             FDR.TDP43 < 0.05 & FDR.membralin < 0.05 & log2FC.TDP43 < 0 & log2FC.membralin < 0~ "TDP43 membralin down",
                             FDR.TDP43 < 0.05 & FDR.SOD1 < 0.05 & log2FC.TDP43 > 0 & log2FC.SOD1 > 0 ~ "TDP43 SOD1 up",
                             FDR.TDP43 < 0.05 & FDR.SOD1 < 0.05 & log2FC.TDP43 < 0 & log2FC.SOD1 < 0~ "TDP43 SOD1 down",
                             FDR.membralin < 0.05 & FDR.SOD1 < 0.05 & log2FC.membralin > 0 & log2FC.SOD1 > 0 ~ "membralin SOD1 up",
                             FDR.membralin < 0.05 & FDR.SOD1 < 0.05 & log2FC.membralin < 0 & log2FC.SOD1 < 0~ "membralin SOD1 down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "TDP43 membralin SOD1 up", "TDP43 membralin SOD1 down", "TDP43 membralin up","TDP43 membralin down","TDP43 SOD1 up","TDP43 SOD1 down", "membralin SOD1 up","membralin SOD1 down","None"))) %>%  arrange(overlap) %>% filter(overlap != "None") %>% select(gene_name, hsap.ensembl, overlap, everything())

write_csv(mouse_als_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS6.overlap_mouse_als_individual_datasets.csv")

# TDP43.SOD1.membralin.FUS_overlap <- cbindX(arrange(as_tibble_col(DGEup_membralin_TDP43, column_name = "membralin_TDP43_up"), membralin_TDP43_up),  
#                          arrange(as_tibble_col(DGEdown_membralin_TDP43, column_name = "membralin_TDP43_down"), membralin_TDP43_down),  
#                          arrange(as_tibble_col(DGEup_SOD1_TDP43, column_name = "SOD1_TDP43_up"), SOD1_TDP43_up),  
#                          arrange(as_tibble_col(DGEdown_SOD1_TDP43, column_name = "SOD1_TDP43_down"), SOD1_TDP43_down))
# TDP43.SOD1.membralin.FUS_overlap[is.na(TDP43.SOD1.membralin.FUS_overlap)] <- ""
# write_csv(TDP43.SOD1.membralin.FUS_overlap, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/Table.S3.TDP43.SOD1.membralin.FUS_overlap.csv")
```

# Fig 4 Mouse meta-analysis

4A biorender schematic of mouse models

## Volcano

```{r}
mouse_als_datasets.interesting.gene.labels <- mouse_als_datasets$res %>% filter(-log10(padj) > 3, abs(log2FoldChange) > 3, gene_name %in% c(go.pathways.msigdb$GO_PHAGOCYTOSIS, glutamate.uptake.go)) %>% pull(gene_name)
mouse_als_datasets.reactive.labels = mouse_als_datasets$res %>% filter(padj < 0.05, gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name)) %>% pull(gene_name)

mouse_als_datasets.volcano <- volcano_plot_deseq(data = mouse_als_datasets$res, labels_list = c(mouse_als_datasets.interesting.gene.labels, mouse_als_datasets.reactive.labels)) + 
  xlab(expression(log[2]~fold~change~mouse~ALS:CTRL)) + 
  coord_cartesian(xlim = c(-3,3), ylim = c(0,8)) +
  geom_segment(aes(x = 1, xend = 3, y= 7, yend= 7), arrow=arrow(length=unit(0.3,"cm")), color = "firebrick2" ) +
  geom_segment(aes(x = -1, xend = -3, y= 7, yend= 7),arrow=arrow(length=unit(0.3,"cm")), color = "dodgerblue2") +
  annotate("text", x = 2, y = 7.5, label = "Up in mouse ALS", color = "firebrick2", size = 2.8) + annotate("text", x = -2, y = 7.5, label = "Down in mouse ALS", color = "dodgerblue2", size = 2.8)
mouse_als_datasets.volcano

mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) # 429
mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) # 624

```

## GO terms ALS

```{r}
mouse_als_datasets.dge_genes <- mouse_als_datasets$res %>% filter(padj < 0.05) %>% group_split(log2FoldChange > 0) %>%  map("gene_id") # create list of IR up/down & Expression up/down genes
mouse_als_datasets.dge_genes <- gost(mouse_als_datasets.dge_genes, organism = "mmusculus") # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
mouse_als_datasets.dge_gprofiles_filt <- mouse_als_datasets.dge_genes$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "query_1" ~ " mouse ALS Down ", query == "query_2" ~ " mouse ALS Up "), term_name = as.factor(term_name)) 
mouse_als_datasets.dge_gprofiles_down <- mouse_als_datasets.dge_gprofiles_filt %>% filter(query == " mouse ALS Down ")
mouse_als_datasets.dge_gprofiles_up <- mouse_als_datasets.dge_gprofiles_filt %>% filter(query == " mouse ALS Up ")
paste('"',unique(mouse_als_datasets.dge_gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
down_list <- c(
# "protein binding",
"glutamatergic synapse",
"axon",
"dendrite",
"synapse organization",
# "somatodendritic compartment",
"postsynapse",
"synapse",
# "neuron differentiation",
"generation of neurons",
"neuron projection",
"neurogenesis",
"nervous system development")
mouse_als_datasets.dge_gprofiles_filt_down <- mouse_als_datasets.dge_gprofiles_filt %>% filter(query == " mouse ALS Down ")  %>% filter(term_name %in% down_list)
mouse_als_datasets.dge_gprofiles_filt_down$term_name <- gsub("regulation of ", "", mouse_als_datasets.dge_gprofiles_filt_down$term_name)
paste('"',unique(mouse_als_datasets.dge_gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
up_list <- c(
"focal adhesion",
"endoplasmic reticulum",
"extracellular matrix",
"response to interferon-gamma",
"inflammatory response",
# "leukocyte mediated immunity",
"response to interferon-beta",
# "response to virus",
# "immune effector process",
# "response to bacterium",
"cytokine production",
"response to stress",
"response to cytokine",
# "innate immune response",
"immune system process",
"immune response")
# "defense response")
mouse_als_datasets.dge_gprofiles_filt_up <- mouse_als_datasets.dge_gprofiles_filt %>% filter(query == " mouse ALS Up ")  %>% filter(term_name %in% up_list)
mouse_als_datasets.dge_gprofiles_filt_combined <- bind_rows(mouse_als_datasets.dge_gprofiles_filt_down, mouse_als_datasets.dge_gprofiles_filt_up) %>% 
  mutate(query = factor(query, levels = c(" mouse ALS Up ", " mouse ALS Down ")))
# mouse_als_datasets.dge_gprofiles_filt_combined$term_name <- gsub("extracellular matrix structural constituent conferring compression resistance", "extracellular matrix", mouse_als_datasets.dge_gprofiles_filt_combined$term_name)
# mouse_als_datasets.dge_gprofiles_filt_combined$term_name <- gsub("enzyme linked receptor protein signaling pathway", "enzyme linked receptor signaling", mouse_als_datasets.dge_gprofiles_filt_combined$term_name)
# mouse_als_datasets.dge_gprofiles_filt_combined$term_name <- gsub(" pathway", "", mouse_als_datasets.dge_gprofiles_filt_combined$term_name)
mouse_als_datasets.go_curated <- curated_profiles(gprofiles = mouse_als_datasets.dge_gprofiles_filt_combined) + theme(legend.position = "none")
mouse_als_datasets.go_curated

# which genes are driving the terms
mouse_als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GABA_RECEPTOR_COMPLEX)
mouse_als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_PLASMA_MEMBRANE_REGION)
mouse_als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_GAP_JUNCTION)
mouse_als_datasets$res %>% filter(padj < 0.05, gene_name %in% go.pathways.msigdb$GO_EXTRACELLULAR_MATRIX_STRUCTURAL_CONSTITUENT_CONFERRING_COMPRESSION_RESISTANCE)
```

## Guttenplan A1 & mouseALS scatter correlation

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.guttenplan.A1 = log2FoldChange, FDR.guttenplan.A1 = padj)
mouse_als_datasets_guttenplan.A1.dge <- full_join(mouse_als_datasets.dge, guttenplan.A1.dge, by = "gene_name")

mouse_als_datasets_guttenplan.A1.dge <- mouse_als_datasets_guttenplan.A1.dge %>% mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.guttenplan.A1 < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.guttenplan.A1 < 0.05 ~ "A1 specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.guttenplan.A1 < 0.05 & log2FC.guttenplan.A1 > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.guttenplan.A1 < 0.05 & log2FC.guttenplan.A1 < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.guttenplan.A1 < 0.05 & log2FC.guttenplan.A1 > 0 ~ "A1 specific up",
                                                                  FDR.guttenplan.A1 < 0.05 & log2FC.guttenplan.A1 < 0 ~ "A1 specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS specific up", "ALS specific down", "A1 specific up", "A1 specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "A1 specific", "None"))) %>%
  arrange(overlap_direction)
table(mouse_als_datasets_guttenplan.A1.dge$overlap)
table(mouse_als_datasets_guttenplan.A1.dge$overlap_direction)
mouse_als_datasets_guttenplan.A1.dge

cor.test(x = mouse_als_datasets_guttenplan.A1.dge$log2FC.ALS, y = mouse_als_datasets_guttenplan.A1.dge$log2FC.guttenplan.A1) # 0.1088784 
t.test( x = mouse_als_datasets_guttenplan.A1.dge$log2FC.ALS, y = mouse_als_datasets_guttenplan.A1.dge$log2FC.guttenplan.A1, paired = TRUE )

guttenplan.A1_mouseALS_scatter <- ggscatter(mouse_als_datasets_guttenplan.A1.dge, x = "log2FC.ALS", y = "log2FC.guttenplan.A1", color = "overlap_direction", 
                                            palette = c("firebrick2", "dodgerblue2", "grey", "grey", "grey", "grey", "grey"), 
                                            cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -5, label.y = 6, label.sep = "\n", size = 3),
                                       xlab = expression( Log[2]~Fold~Change~mouse~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~mouse~A1:A0), size = 0.5) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  coord_cartesian(xlim = c(-5,5), ylim = c(-6,7)) +
    geom_smooth(aes(x = log2FC.ALS, y = log2FC.guttenplan.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(mouse_als_datasets_guttenplan.A1.dge, overlap_direction %in%  c("overlapping up", "overlapping down"), gene_name %in% all.reactivity.go, log2FC.guttenplan.A1 < 9), aes(x = log2FC.ALS, y = log2FC.guttenplan.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=3, y=7.3, label="ALS & A1 both Up", color="firebrick2", size = 3.2)  + annotate(geom="text", x=-3, y=-6, label="ALS & A1 both Down", color="dodgerblue2", size = 3.2)
guttenplan.A1_mouseALS_scatter

# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
guttenplan.A1.DGE.up.genes <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
ALS.DGE.down.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
guttenplan.A1.DGE.down.genes <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

genome.size <- mouse_als_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(ALS.DGE.up.genes,guttenplan.A1.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=429
# listB size=1973
# Intersection size=109
# Overlapping p-value=2.4e-60
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.down.genes,guttenplan.A1.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=624
# listB size=1926
# Intersection size=145
# Overlapping p-value=7.3e-76
# Jaccard Index=0.1
```

## Venn mouseALS, hiPSC & mouse A1

```{r}
# 2 way overlap mouse A1 & mouseALS
mouse_als_datasets.res.dge.up <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.down <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
guttenplan.A1.res.dge.up <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
guttenplan.A1.res.dge.down <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
mouse_als_datasets.guttenplan.A1.up_genes <- list("mouse ALS\nUp" = mouse_als_datasets.res.dge.up, "mouse A1\nUp" = guttenplan.A1.res.dge.up)
mouse_als_datasets.guttenplan.A1.down_genes <- list("mouse ALS\nDown" = mouse_als_datasets.res.dge.down, "mouse A1\nDown" = guttenplan.A1.res.dge.down)
guttenplan.A1_mouse_als_datasets_venn_up <- ggvenn(mouse_als_datasets.guttenplan.A1.up_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
guttenplan.A1_mouse_als_datasets_venn_down <- ggvenn(mouse_als_datasets.guttenplan.A1.down_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
guttenplan.A1_mouse_als_datasets_venn = ggarrange(guttenplan.A1_mouse_als_datasets_venn_up, guttenplan.A1_mouse_als_datasets_venn_down, ncol = 2)
guttenplan.A1_mouse_als_datasets_venn

# 
# # Chi-squared 3 way overlap
# list1 <- unique(mouse_als_datasets.res.dge.up[!is.na(mouse_als_datasets.res.dge.up)])
# list2 <- unique(barbar.res.dge.up[!is.na(barbar.res.dge.up)])
# list3 <- unique(guttenplan.A1.res.dge.up[!is.na(guttenplan.A1.res.dge.up)])
# univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
# xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
# ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
# glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
# glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
# anovatest <- anova(glm1,glm2,test='Chisq')
# pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
# ans <- list(xtab,ftable,glm1,glm2,pvalue)
# names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# # $pvalue
# # [1] 0.003614672
# 
# list1 <- unique(mouse_als_datasets.res.dge.down[!is.na(mouse_als_datasets.res.dge.down)])
# list2 <- unique(barbar.res.dge.down[!is.na(barbar.res.dge.down)])
# list3 <- unique(guttenplan.A1.res.dge.down[!is.na(guttenplan.A1.res.dge.down)])
# univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
# xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
# ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
# glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
# glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
# anovatest <- anova(glm1,glm2,test='Chisq')
# pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
# ans <- list(xtab,ftable,glm1,glm2,pvalue)
# names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
# # $pvalue
# # [1] 8.92463e-05


```

## GO terms mouseALS, hiPSC & mouse A1

```{r}
mouse_als_datasets_guttenplan.A1.gost = mouse_als_datasets_guttenplan.A1.dge %>% filter(overlap_direction %in% c("overlapping up", "overlapping down")) %>% split(.$overlap_direction) %>%  map("gene_id") %>% gost(organism = "mmusculus")
mouse_als_datasets_guttenplan.A1.gost_filt <- mouse_als_datasets_guttenplan.A1.gost$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% 
  mutate(query = case_when(query == "overlapping down" ~ " A1 & ALS Down ", query == "overlapping up" ~ " A1 & ALS Up "), term_name = as.factor(term_name)) 
mouse_als_datasets_guttenplan.A1.gprofiles_down <- mouse_als_datasets_guttenplan.A1.gost_filt %>% filter(query == " A1 & ALS Down ")
mouse_als_datasets_guttenplan.A1.gprofiles_up <- mouse_als_datasets_guttenplan.A1.gost_filt %>% filter(query == " A1 & ALS Up ")

paste('"',unique(mouse_als_datasets_guttenplan.A1.gprofiles_up$term_name),'",', sep = "", collapse = '\n') %>% cat()
als.a1.overlap.up_curated_list <- c(
# "extracellular matrix",
"Collagen formation",
"Protein processing in endoplasmic reticulum",
"focal adhesion",
# "angiogenesis",
"Extracellular matrix organization",
"cellular response to stress",
"focal adhesion",
# "Golgi apparatus",
"endoplasmic reticulum",
# "MHC class I peptide loading complex",
"tumor necrosis factor production",
"cellular response to lipopolysaccharide",
"cytokine production",
"response to interferon-beta",
"innate immune response",
"response to stress",
"response to interferon-gamma",
# "immune response",
"response to cytokine",
"immune system process")
mouse_als_datasets_guttenplan.A1.gost_filt.up <- mouse_als_datasets_guttenplan.A1.gost_filt %>% filter(term_name %in% als.a1.overlap.up_curated_list)

paste('"',unique(mouse_als_datasets_guttenplan.A1.gprofiles_down$term_name),'",', sep = "", collapse = '\n') %>% cat()
als.a1.overlap.down_curated_list <- c(
# "synaptic signaling",
# "GABA-ergic synapse",
"axon development",
# "synaptic membrane",
"glutamatergic synapse",
# "axon",
# "postsynapse",
# "dendritic tree",
# "dendrite",
"generation of neurons",
"neuron differentiation",
"neuron projection",

# "synapse",
# "gliogenesis",
# "somatodendritic compartment",
# "localization",
"glutamatergic synapse",
"neuron projection",
"neuron development",
"myelination",
"synapse organization",
# "neuron differentiation",
"glial cell differentiation",
"generation of neurons",
"synapse assembly",
"nervous system development")
mouse_als_datasets_guttenplan.A1.gost_filt.down <- mouse_als_datasets_guttenplan.A1.gost_filt %>% filter(term_name %in% als.a1.overlap.down_curated_list)
als.a1.overlap.up_gprofiles_filt.up_down <- bind_rows(mouse_als_datasets_guttenplan.A1.gost_filt.up, mouse_als_datasets_guttenplan.A1.gost_filt.down) %>% mutate(query = factor(query, levels = c(" A1 & ALS Up ", " A1 & ALS Down ")))
mouse_als_datasets_a1.go_curated <- curated_profiles(gprofiles = als.a1.overlap.up_gprofiles_filt.up_down, colours = 2) + labs(subtitle = "A1 & ALS overlap")
mouse_als_datasets_a1.go_curated

```


## Signalling Pathway PROGENy

<https://github.com/saezlab/transcriptutorial/blob/master/scripts/03_Pathway_activity_with_Progeny.md> <https://saezlab.github.io/progeny/>

Pathway RespOnsive GENes (PROGENy) estimates signaling pathway activity

```{r}
mouse_als_datasets.res.matrix <- mouse_als_datasets$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
mouse_als_datasets.ALS.PathwayActivity_zscore <- progeny(mouse_als_datasets.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t()# enrichment analysis of each pathway activity using competitive permutation approach
colnames(mouse_als_datasets.ALS.PathwayActivity_zscore) <- "NES"
mouse_als_datasets.ALS.PathwayActivity_zscore_df <- as.data.frame(mouse_als_datasets.ALS.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>% mutate(Pathway = factor(Pathway), dataset = "mouse ALS")

# a1_datasets.res.matrix <- a1_datasets$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
# a1_datasets.A1.PathwayActivity_zscore <- progeny(a1_datasets.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
# colnames(a1_datasets.A1.PathwayActivity_zscore) <- "NES"
# a1_datasets.A1.PathwayActivity_zscore_df <- as.data.frame(a1_datasets.A1.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>% mutate(Pathway = factor(Pathway), dataset = "A1")

guttenplan.A1.res.matrix <- guttenplan.A1$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
guttenplan.A1.PathwayActivity_zscore <- progeny(guttenplan.A1.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>% t() # enrichment analysis of each pathway activity
colnames(guttenplan.A1.PathwayActivity_zscore) <- "NES"
guttenplan.A1.PathwayActivity_zscore_df <- as.data.frame(guttenplan.A1.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "A1")

zamanian.A2.res.matrix <- zamanian.A2.res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
zamanian.A2.PathwayActivity_zscore <- progeny(zamanian.A2.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
colnames(zamanian.A2.PathwayActivity_zscore) <- "NES"
zamanian.A2.PathwayActivity_zscore_df <- as.data.frame(zamanian.A2.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "MCAO")

anderson.res.matrix <- anderson$res %>% select(gene_name, log2FoldChange) %>%  drop_na(log2FoldChange) %>% distinct(gene_name, .keep_all = TRUE) %>% column_to_rownames(var = "gene_name") %>% as.matrix()
anderson.PathwayActivity_zscore <- progeny(anderson.res.matrix, scale=TRUE, organism="Human", top = 100, perm = 10000, z_scores = TRUE) %>%  t() # enrichment analysis of each pathway activity
colnames(anderson.PathwayActivity_zscore) <- "NES"
anderson.PathwayActivity_zscore_df <- as.data.frame(anderson.PathwayActivity_zscore) %>% rownames_to_column(var = "Pathway") %>% arrange(NES) %>%  mutate(Pathway = factor(Pathway), dataset = "SCI")

# barchart
mouse_als_a1_protective_datasets.PathwayActivity_zscore_df <- bind_rows(mouse_als_datasets.ALS.PathwayActivity_zscore_df, guttenplan.A1.PathwayActivity_zscore_df, zamanian.A2.PathwayActivity_zscore_df, anderson.PathwayActivity_zscore_df) %>% mutate(Pathway = factor(Pathway, levels = mouse_als_datasets.ALS.PathwayActivity_zscore_df$Pathway), dataset = factor(dataset, levels = c("mouse ALS", "A1", "MCAO", "SCI")))
mouse_als_A1_protective.progeny.pathwayActivity <- ggplot(mouse_als_a1_protective_datasets.PathwayActivity_zscore_df, aes(x=dataset, y = NES, fill = dataset)) + theme_bw() +
  geom_bar(stat="identity", position=position_dodge(), width = 0.7) + theme(legend.position = "none", legend.title = element_blank(), axis.title = element_text(size = 10),
          axis.text.x = element_text(angle = 90, hjust = 1, size = 8), axis.text.y = element_text(size =8), strip.text.x = element_text(size = 8, angle = 0)) + 
  geom_hline(yintercept = 0, linetype = 2, colour = "darkgrey") + 
  scale_fill_manual( values = c("dodgerblue2","firebrick2",  "forestgreen", "gold2", "purple")) +
  facet_wrap(~Pathway, scales = "free", nrow = 2) +
  xlab("") + ylab(expression(Normalised~enrichment)) #+ labs(subtitle = "Signalling Pathway activity")
mouse_als_A1_protective.progeny.pathwayActivity


```


## Merge

```{r}
# fig5.merged <- ggarrange(
#   mouse_als_datasets.volcano, mouse_als_datasets.go_curated,
#   mouse_als_datasets.glutamate.uptake.gseaplot, guttenplan.A1_mouseALS_scatter, 
#   guttenplan.A1_mouse_als_datasets_venn, mouse_als_datasets_a1.go_curated,
#   nrow = 3, ncol = 2, labels = c("B", "C", "D", "E", "F", "G")) # heights = c(0.9,1.1,0.9,1.1),
# # fig5.merged
# ggsave(fig5.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig5.merged.png", height = 11, width = 11)

fig4.merged <- ggarrange(
  ggarrange(mouse_als_datasets.volcano, mouse_als_datasets.go_curated, ncol = 2, labels = c("B","C")),
  ggarrange(guttenplan.A1_mouseALS_scatter, ggarrange(guttenplan.A1_mouse_als_datasets_venn_up, guttenplan.A1_mouse_als_datasets_venn_down, nrow = 2), mouse_als_datasets_a1.go_curated, ncol = 3, widths = c(1,0.5,0.8), labels = c("D", "E", "F")),
  mouse_als_A1_protective.progeny.pathwayActivity,
  nrow = 3, ncol = 1, labels = c("", "", "G"), heights = c(0.8,1,1.4))
# fig4.merged
ggsave(fig4.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/fig4.merged.png", height = 12, width = 11)

```


# Fig S9 human & mouse ALS comparison

## Scatterplot mouse ALS & human ALS

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, log2FC.mouse_ALS = log2FoldChange, FDR.mouse_ALS = padj) %>% filter(gene_name %in% gene2ens$gene_name) 
als_datasets.dge <- als_datasets$res %>% select(gene_name, log2FC.human_ALS = log2FoldChange, FDR.human_ALS = padj)
mouse_als_datasets_als_datasets.dge <- full_join(mouse_als_datasets.dge, als_datasets.dge, by = "gene_name")

mouse_als_datasets_als_datasets.dge <- mouse_als_datasets_als_datasets.dge %>% mutate(overlap = case_when(FDR.mouse_ALS < 0.05 & FDR.human_ALS < 0.05 ~ "overlapping", # down in mouse_ALS
                                                        FDR.mouse_ALS < 0.05 ~ "mouse_ALS specific",
                                                        FDR.human_ALS < 0.05 ~ "human_ALS specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.mouse_ALS < 0.05 & log2FC.mouse_ALS > 0 & FDR.human_ALS < 0.05 & log2FC.human_ALS > 0 ~ "overlapping up", # down in mouse_ALS
                                                                  FDR.mouse_ALS < 0.05 & log2FC.mouse_ALS < 0 & FDR.human_ALS < 0.05 & log2FC.human_ALS < 0 ~ "overlapping down",
                                                                  FDR.mouse_ALS < 0.05 & log2FC.mouse_ALS > 0 ~ "mouse_ALS specific up",
                                                                  FDR.mouse_ALS < 0.05 & log2FC.mouse_ALS < 0 ~ "mouse_ALS specific down",
                                                                  FDR.human_ALS < 0.05 & log2FC.human_ALS > 0 ~ "human_ALS specific up",
                                                                  FDR.human_ALS < 0.05 & log2FC.human_ALS < 0 ~ "human_ALS specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "mouse_ALS specific up", "mouse_ALS specific down", "human_ALS specific up", "human_ALS specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "mouse_ALS specific", "human_ALS specific", "None"))) %>%
  arrange(overlap_direction)
table(mouse_als_datasets_als_datasets.dge$overlap)
table(mouse_als_datasets_als_datasets.dge$overlap_direction)


cor.test(x = mouse_als_datasets_als_datasets.dge$log2FC.mouse_ALS, y = mouse_als_datasets_als_datasets.dge$log2FC.human_ALS) # 0.105
t.test( x = mouse_als_datasets_als_datasets.dge$log2FC.mouse_ALS, y = mouse_als_datasets_als_datasets.dge$log2FC.human_ALS, paired = TRUE )

human_ALS_mouse_ALS_scatter <- ggscatter(mouse_als_datasets_als_datasets.dge, x = "log2FC.mouse_ALS", y = "log2FC.human_ALS", color = "overlap_direction", 
                                      palette = c("firebrick2", "dodgerblue3", "grey", "grey", "grey", "grey", "grey"), cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~mouse~ALS~models:CTRL), ylab = expression(Log[2]~Fold~Change~human~pan~ALS:CTRL), size = 0.5, cor.coef.size = 3) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  xlim(-2,2.1) + ylim(-5.5,5) +
    geom_smooth(data = mouse_als_datasets_als_datasets.dge, aes(x = log2FC.mouse_ALS, y = log2FC.human_ALS), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 1) + theme(legend.position = "none") +
    geom_text_repel(data = filter(mouse_als_datasets_als_datasets.dge, overlap_direction %in%  c("overlapping up", "overlapping down"), gene_name %in% all.reactivity.go), aes(x = log2FC.mouse_ALS, y = log2FC.human_ALS, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 20) +  
  annotate(geom="text", x=1, y=5, label="mouse ALS models &\nhuman pan-ALS Up", color="firebrick2", size = 3.2)  + 
  annotate(geom="text", x=-1, y=-5, label="mouse ALS models &\nhuman pan-ALS Down", color="dodgerblue3", size = 3.2) + labs(subtitle = "mouse ALS models vs human pan-ALS")
human_ALS_mouse_ALS_scatter
```

## Venn

```{r}
als_datasets.res.dge.up = als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
als_datasets.res.dge.down = als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.up = mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.down = mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
human_mouse_als_datasets.up_genes <- list("mouse ALS\nUp" = mouse_als_datasets.res.dge.up, "human ALS\nUp" = als_datasets.res.dge.up)
human_mouse_als_datasets.down_genes <- list("mouse ALS\nDown" = mouse_als_datasets.res.dge.down, "human ALS\nDown" = als_datasets.res.dge.down)
human_mouse_als_datasets_venn_up <- ggvenn(human_mouse_als_datasets.up_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
human_mouse_als_datasets_venn_down <- ggvenn(human_mouse_als_datasets.down_genes, fill_color = c("dodgerblue3", "firebrick1"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1")) +  theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"), plot.margin = unit(c(0, -1, 0, -1), "lines"))
human_mouse_als_datasets_venn = ggarrange(human_mouse_als_datasets_venn_up, human_mouse_als_datasets_venn_down, nrow = 2)
human_mouse_als_datasets_venn


newGeneOverlap(als_datasets.res.dge.up,mouse_als_datasets.res.dge.up, genome.size=nrow(distinct(als_datasets$res, gene_name))) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1309
# listB size=429
# Intersection size=41
# Overlapping p-value=3.2e-15
# Jaccard Index=0.0

newGeneOverlap(als_datasets.res.dge.down,mouse_als_datasets.res.dge.down,genome.size=nrow(distinct(als_datasets$res, gene_name))) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=1562
# listB size=624
# Intersection size=83
# Overlapping p-value=2.1e-34
# Jaccard Index=0.0

```

## GO overlap

```{r}
mouse_als_datasets_als_datasets.dge_overlap_genes <- mouse_als_datasets_als_datasets.dge %>% filter(overlap_direction == "overlapping up" | overlap_direction == "overlapping down" ) %>% split(.$overlap_direction) %>%  map("gene_name") %>% gost()
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt <- mouse_als_datasets_als_datasets.dge_overlap_genes$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% mutate( term_name = as.factor(term_name)) 
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up <- mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt %>% filter(query == "overlapping up")
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.down <- mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt %>% filter(query == "overlapping down")
paste('"',unique(mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up$term_name),'",', sep = "", collapse = '\n') %>% cat()
mouse_als_datasets_als_datasets.dge.up_curated_list <- c(
"positive regulation of cell death",
"endomembrane system",
"endoplasmic reticulum lumen",
"positive regulation of programmed cell death",
"endoplasmic reticulum",
"positive regulation of apoptotic process",
"response to laminar fluid shear stress",
"cytoplasm")
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up <- mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up %>% filter(term_name %in% mouse_als_datasets_als_datasets.dge.up_curated_list) %>% mutate(query = "upregulated")
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up$term_name <- gsub("myeloid cell activation involved in immune response", "immune response", mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up$term_name) %>% gsub("alpha/beta ", "", .)

paste('"',unique(mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.down$term_name),'",', sep = "", collapse = '\n') %>% cat()
mouse_als_datasets_als_datasets.dge.up_curated_list <- c(
"postsynapse",
"glutamatergic synapse",
"synaptic membrane",
"dendrite",
"somatodendritic compartment",
"nervous system development",
"synaptic signaling",
"axon",
"synapse",
"neuron projection")
mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.down <- mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.down %>% filter(term_name %in% mouse_als_datasets_als_datasets.dge.up_curated_list) %>% mutate(query = "downregulated")

mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up_down <- bind_rows(mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up, mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.down) %>% 
  mutate(query = factor(query, levels = c("upregulated", "downregulated")))
mouse_als_datasets_als_datasets.go_curated <- curated_profiles(gprofiles = mouse_als_datasets_als_datasets.dge_overlap_gprofiles_filt_dge.up_down, colours = 2) + labs(subtitle = "human & mouse ALS overlap")
mouse_als_datasets_als_datasets.go_curated

```

## Merge

```{r}
figS9.merged = ggarrange(
  ggarrange(human_ALS_mouse_ALS_scatter, human_mouse_als_datasets_venn, ncol = 2, labels = c("A", "B"), widths = c(1,0.6)),
  mouse_als_datasets_als_datasets.go_curated, 
  nrow = 2, labels = c("", "C"), heights = c(1,1))
figS9.merged
ggsave(figS9.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS9.merged.human.mouse.overlap.png", height = 10, width = 8)

```


# Table S7 human & mouse overlap

```{r}
mouse_als_datasets_als_datasets.dge %>% filter(overlap_direction %in% c("overlapping up", "overlapping down")) %>% select(gene_name, overlap_direction, log2FC.mouse_ALS, FDR.mouse_ALS, log2FC.human_ALS, FDR.human_ALS) %>%
  write_csv("/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/Table.S7.human.mouse.meta_analysis.overlap.csv")

```




# Table S8. Mouse ALS & A1 gene expression

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, ensembl = gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% 
  mutate(direction.ALS = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "up", FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "down", TRUE ~ "non-significant"))
guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, ensembl = gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj) %>% 
  mutate(direction.A1 = case_when(FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "up", FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "down", TRUE ~ "non-significant"))

als_guttenplan.A1_merged.dge <- mouse_als_datasets.dge %>% full_join(guttenplan.A1.dge) %>%  
  mutate(overlap = case_when(direction.ALS == "up" & direction.A1 == "up"  ~ "overlapping up",
                             direction.ALS == "down" & direction.A1 == "down"  ~ "overlapping down",
                             direction.ALS == "up" ~ "ALS up", 
                             direction.ALS == "down" ~ "ALS down", 
                             direction.A1 == "up" ~ "", 
                             direction.A1 == "
                             
                             down" ~ "A1 down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "ALS u", "ALS down","A1 up","A1 down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, ensembl, overlap, everything()) %>% filter(overlap != "None")

write_csv(als_guttenplan.A1_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS8.mouse_overlap_als_a1.csv")
```

# Fig S10 Mouse ALS & Protective astrocytes

## MCAO & mouseALS scatter correlation

```{r}
# correlate zamanian A2 with ALS:
mouse_als_datasets.res.zamanian <- mouse_als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>%  drop_na(log2FC.ALS) %>% distinct(gene_name, .keep_all = TRUE)
zamanian.res.filt <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% drop_na(log2FC.MCAO) %>% distinct(gene_name, .keep_all = TRUE)
mouse_als_datasets_zamanian.dge <- full_join(mouse_als_datasets.res.zamanian, zamanian.res.filt, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.MCAO < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.MCAO < 0.05 ~ "MCAO specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "ALS up, MCAO down", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "ALS down, MCAO up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "MCAO specific up",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "MCAO specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS up, MCAO down", "ALS down, MCAO up", "ALS specific up", "ALS specific down", "MCAO specific up", "MCAO specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "MCAO specific", "None"))) %>%
  arrange(overlap_direction)
# table(mouse_als_datasets_zamanian.dge$overlap_direction)
# overlapping up  overlapping down   ALS specific up ALS specific down    MCAO specific up  MCAO specific down 
#               109               150               963              1198              1181              1276 
cor.test(x = mouse_als_datasets_zamanian.dge$log2FC.ALS, y = mouse_als_datasets_zamanian.dge$log2FC.MCAO) #  MCAO.day1_vs_A0.day1 0.09 

MCAO_mouse_ALS_scatter <- ggscatter(mouse_als_datasets_zamanian.dge, x = "log2FC.ALS", y = "log2FC.MCAO", cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -3, label.y = -2.5, label.sep = "\n", size = 3), 
                            color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"),
  xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~MCAO:Sham), size = 0.5) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  coord_cartesian(xlim = c(-3,3), ylim = c(-3,4)) +
  geom_smooth(data = mouse_als_datasets_zamanian.dge, aes(x = log2FC.ALS, y = log2FC.MCAO), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
  geom_text_repel(data = filter(mouse_als_datasets_zamanian.dge, overlap_direction %in%  c("ALS up, MCAO down", "ALS down, MCAO up"), gene_name %in% all.reactivity.go), aes(x = log2FC.ALS, y = log2FC.MCAO, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
  annotate(geom="text", x=1.5, y=-2.5, label="ALS up\nMCAO down", color="forestgreen", size = 3.2) + annotate(geom="text", x=-1.5, y=3.5, label="ALS down\nMCAO up", color="gold2", size = 3.2) + labs(subtitle = "mouse-ALS vs MCAO")
MCAO_mouse_ALS_scatter


# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
A2.DGE.up.genes <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
ALS.DGE.down.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
A2.DGE.down.genes <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
genome.size <- mouse_als_datasets_zamanian.dge %>% distinct(gene_name) %>% nrow

newGeneOverlap(ALS.DGE.up.genes, A2.DGE.down.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=431
# listB size=1460
# Intersection size=33
# Overlapping p-value=5.2e-04
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.down.genes, A2.DGE.up.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=625
# listB size=1312
# Intersection size=22
# Overlapping p-value=0.62
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.up.genes,A2.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=431
# listB size=1312
# Intersection size=69
# Overlapping p-value=8e-25
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.down.genes,A2.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=625
# listB size=1460
# Intersection size=62
# Overlapping p-value=2e-10
# Jaccard Index=0.0

```

## SCI & mouseALS scatter correlation

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
anderson.dge <- anderson$res %>% select(gene_name, gene_id, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
mouse_als_datasets_anderson.dge <- full_join(mouse_als_datasets.dge, anderson.dge, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.SCI < 0.05 ~ "overlapping", # down in ALS
                                                        FDR.ALS < 0.05 ~ "ALS specific",
                                                        FDR.SCI < 0.05 ~ "SCI specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "overlapping up", # down in ALS
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "overlapping down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "ALS up, SCI down",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "ALS down, SCI up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "ALS specific up",
                                                                  FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "ALS specific down",
                                                                  FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "SCI specific up",
                                                                  FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "SCI specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "ALS up, SCI down", "ALS down, SCI up", "ALS specific up", "ALS specific down", "SCI specific up", "SCI specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "ALS specific", "SCI specific", "None"))) %>%
  arrange(overlap_direction)
table(mouse_als_datasets_anderson.dge$overlap)
table(mouse_als_datasets_anderson.dge$overlap_direction)

cor.test(x = mouse_als_datasets_anderson.dge$log2FC.ALS, y = mouse_als_datasets_anderson.dge$log2FC.SCI) # 0.1088784 
t.test( x = mouse_als_datasets_anderson.dge$log2FC.ALS, y = mouse_als_datasets_anderson.dge$log2FC.SCI, paired = TRUE )

SCI_mouse_ALS_scatter <- ggscatter(mouse_als_datasets_anderson.dge, x = "log2FC.ALS", y = "log2FC.SCI", cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -3, label.y = -6, label.sep = "\n", size = 3), 
                             color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"), 
          xlab = expression( Log[2]~Fold~Change~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~SCI:CTRL), size = 0.5) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
    coord_cartesian(xlim = c(-3,3), ylim = c(-8,10)) +
    geom_smooth(data = mouse_als_datasets_anderson.dge, aes(x = log2FC.ALS, y = log2FC.SCI), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(mouse_als_datasets_anderson.dge, overlap_direction %in%  c("ALS up, SCI down", "ALS down, SCI up"), gene_name %in% all.reactivity.go, log2FC.SCI < 9), aes(x = log2FC.ALS, y = log2FC.SCI, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=2, y=-7, label="ALS up\nSCI down", color="forestgreen", size = 3.2)  + annotate(geom="text", x=-2, y=9, label="ALS down\nSCI up", color="gold2", size = 3.2) + labs(subtitle = "mouse-ALS vs SCI")
SCI_mouse_ALS_scatter

# Overlap tested using Fisher's exact test (alternative=greater)
ALS.DGE.up.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
SCI.DGE.up.genes <- anderson$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
genome.size <- mouse_als_datasets$res %>% distinct(gene_name) %>% nrow
newGeneOverlap(ALS.DGE.up.genes,SCI.DGE.up.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=429
# listB size=2622
# Intersection size=149
# Overlapping p-value=1.7e-86
# Jaccard Index=0.1
ALS.DGE.down.genes <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
SCI.DGE.down.genes <- anderson$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
newGeneOverlap(ALS.DGE.down.genes,SCI.DGE.down.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=624
# listB size=2274
# Intersection size=57
# Overlapping p-value=2.2e-08
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.up.genes,SCI.DGE.down.genes,genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=429
# listB size=2274
# Intersection size=42
# Overlapping p-value=2.4e-07
# Jaccard Index=0.0
newGeneOverlap(ALS.DGE.down.genes, SCI.DGE.up.genes, genome.size=genome.size) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=624
# listB size=2622
# Intersection size=166
# Overlapping p-value=2.6e-76
# Jaccard Index=0.1
```



## Venn mouse ALS & protective

```{r}
# 3 way overlap SCI, hiPSC ALS, mouseALS
mouse_als_datasets.res.dge.up <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.down <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
zamanian.A2.res.dge.up <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
zamanian.A2.res.dge.down <- zamanian.A2.res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
anderson.res.dge.up <- anderson$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
anderson.res.dge.down <- anderson$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)

# ggvenn
mouse_als_datasets_up.zamanian.A2.anderson_down_genes <- list("ALS Up" = mouse_als_datasets.res.dge.up, "MCAO Down" = zamanian.A2.res.dge.down, "SCI Down" = anderson.res.dge.down)
mouse_als_datasets_up.zamanian.A2.anderson_down_genes_venn <- ggvenn(mouse_als_datasets_up.zamanian.A2.anderson_down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
mouse_als_datasets_down.zamanian.A2.anderson_up_genes <- list("ALS Down" = mouse_als_datasets.res.dge.down, "MCAO Up" = zamanian.A2.res.dge.up, "SCI Up" = anderson.res.dge.up)
mouse_als_datasets_down.zamanian.A2.anderson_up_genes_venn <- ggvenn(mouse_als_datasets_down.zamanian.A2.anderson_up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
anderson_zamanian.A2_mouse_als_datasets_venn = ggarrange(mouse_als_datasets_up.zamanian.A2.anderson_down_genes_venn, mouse_als_datasets_down.zamanian.A2.anderson_up_genes_venn, nrow = 2)
anderson_zamanian.A2_mouse_als_datasets_venn

protective.dge.up = zamanian.A2.res.dge.up[zamanian.A2.res.dge.up %in% anderson.res.dge.up]
protective.dge.down = zamanian.A2.res.dge.down[zamanian.A2.res.dge.down %in% anderson.res.dge.down]
protective.dge.up[protective.dge.up %in% mouse_als_datasets.res.dge.down] 
[1] "ADAMTS4"  "CIC"      "DDX54"    "DST"      "FRMD8"   
 [6] "MARCKSL1" "MYO5A"    "NFASC"    "PDGFA"    "PHLDB1"  
[11] "PKP4"     "PLXND1"   "PUS7"     "SYNM"
protective.up.mouse.als.down = protective.dge.up[protective.dge.up %in% mouse_als_datasets.res.dge.down] 
protective.up.mouse.als.down[protective.up.mouse.als.down %in% all.reactivity.go]
"ADAMTS4" "DDX54"   "DST"     "MYO5A"   "NFASC"   "PDGFA" "PHLDB1"  "PUS7"    "SYNM" 
protective.dge.down[protective.dge.down %in% mouse_als_datasets.res.dge.up]
# "ATP6AP2"  "NDUFV3"   "PRKD1"    "PSENEN"   "SLC25A20" "SUCLG1"   "TLR3"     "TSPAN3"  

  
# Chi-squared 3 way overlap
list1 <- unique(mouse_als_datasets.res.dge.down[!is.na(mouse_als_datasets.res.dge.down)])
list2 <- unique(zamanian.A2.res.dge.up[!is.na(zamanian.A2.res.dge.up)])
list3 <- unique(anderson.res.dge.up[!is.na(anderson.res.dge.up)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
ans
# $pvalue
# [1] 0.1150455

list1 <- unique(mouse_als_datasets.res.dge.up[!is.na(mouse_als_datasets.res.dge.up)])
list2 <- unique(zamanian.A2.res.dge.down[!is.na(zamanian.A2.res.dge.down)])
list3 <- unique(anderson.res.dge.down[!is.na(anderson.res.dge.down)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anovatest <- anova(glm1,glm2,test='Chisq')
pvalue <- anovatest[['Pr(>Chi)']][2] # 0.004703483
ans <- list(xtab,ftable,glm1,glm2,pvalue)
names(ans) <- c('xtab','ftable','glm1','glm2','pvalue')
ans
# $pvalue
# [1] 0.0004816384


```

## Merge

```{r}
figS7.merged <- ggarrange(
  MCAO_mouse_ALS_scatter, SCI_mouse_ALS_scatter,
  mouse_als_datasets_up.zamanian.A2.anderson_down_genes_venn, mouse_als_datasets_down.zamanian.A2.anderson_up_genes_venn, 
  nrow = 2, ncol = 2, labels = c("A", "B", "C", "D")) #, heights = c(1,1.2,1.2))
# figS7.merged
ggsave(figS7.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS7.mouse_als_protective_astrocytes.png", height = 9, width = 9)

```




# Table S9 Mouse panALS & protective datasets

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, ensembl = gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% 
  mutate(direction.ALS = case_when(FDR.ALS < 0.05 & log2FC.ALS > 0 ~ "up", FDR.ALS < 0.05 & log2FC.ALS < 0 ~ "down", TRUE ~ "non-significant"))
anderson.dge <- anderson$res %>% select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj) %>% 
  mutate(direction.SCI = case_when(FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "up", FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "down", TRUE ~ "non-significant"))
zamanian.A2.dge <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% 
  mutate(direction.MCAO = case_when(FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "up", FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "down", TRUE ~ "non-significant"))

mouse_als_protective_datasets_merged.dge <- mouse_als_datasets.dge %>% left_join(anderson.dge) %>% left_join(zamanian.A2.dge) %>% 
  mutate(overlap = case_when(FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "ALS up, MCAO & SCI down",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "ALS down, MCAO & SCI up",
                                        FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO < 0 ~ "ALS up, MCAO down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO > 0~ "ALS down, MCAO up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI < 0 ~ "ALS up, SCI down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI > 0 ~ "ALS down, SCI up",
           FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 & log2FC.SCI > 0 ~ "overlapping up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0 & log2FC.SCI < 0 ~ "overlapping down",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS > 0 & log2FC.MCAO > 0 ~ "ALS & MCAO up",
                             FDR.ALS < 0.05 & FDR.MCAO < 0.05 & log2FC.ALS < 0 & log2FC.MCAO < 0~ "ALS & MCAO down",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS > 0 & log2FC.SCI > 0 ~ "ALS & SCI up",
                             FDR.ALS < 0.05 & FDR.SCI < 0.05 & log2FC.ALS < 0 & log2FC.SCI < 0~ "ALS & SCI down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("ALS up, MCAO & SCI down", "ALS down, MCAO & SCI up", "ALS up, MCAO down", "ALS down, MCAO up",  "ALS up, SCI down", "ALS down, SCI up", "overlapping up",  "overlapping down", "ALS MCAO SCI up", "ALS MCAO SCI down","ALS MCAO up","ALS MCAO down","ALS SCI up","ALS SCI down","MCAO SCI up","MCAO SCI down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, ensembl, overlap, everything()) %>% filter(overlap != "None")

write_csv(mouse_als_protective_datasets_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS9.overlap_mouse_als_protective_datasets.csv")


```


# Fig S11 Liddelow genes in mouse models

## Liddelow correlation

```{r}
# correlate liddelow genes:
### A1 & ALS
mouse_als_datasets.liddelow.dge <- mouse_als_datasets$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
guttenplan.A1.liddelow.dge <- guttenplan.A1$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
mouse_als_guttenplan.A1_datasets.dge <- mouse_als_datasets.liddelow.dge %>% left_join(guttenplan.A1.liddelow.dge, by = "gene_name") %>% left_join(astrocyte.reactivity.markers) %>% rename(Markers = group)

mouse_ALS_A1_scatter.liddelow <- ggscatter(mouse_als_guttenplan.A1_datasets.dge, x = "log2FC.ALS", y = "log2FC.A1", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~mouse~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~mouse~A1:A0), size = 0.5, cor.coeff.args = list(label.x = 1, label.y = -1)) + theme(legend.position = "none") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
    geom_text_repel(data = filter(mouse_als_guttenplan.A1_datasets.dge, log2FC.A1 > 0.1, log2FC.ALS > 0.1, gene_name %in% all.reactivity.go), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
  annotate(geom="text", x=1.5, y=8, label="Mouse ALS models\n& A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(A1~and~mouse~ALS~models:Liddelow~markers))
mouse_ALS_A1_scatter.liddelow

# Test overlap
mouse_als_datasets.liddelow_GEup <- mouse_als_datasets.liddelow.dge %>% filter(log2FC.ALS > 0) %>% pull(gene_name)
guttenplan.A1.liddelow_GEup <- guttenplan.A1.liddelow.dge %>% filter(log2FC.A1 > 0) %>% pull(gene_name)
newGeneOverlap(mouse_als_datasets.liddelow_GEup,guttenplan.A1.liddelow_GEup, genome.size=nrow(astrocyte.reactivity.markers)) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=34
# listB size=32
# Intersection size=29
# Overlapping p-value=6.6e-04
# Jaccard Index=0.8

# SOD1 TRAP & mouse A1
cleveland.liddelow.dge <- cleveland$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
guttenplan.A1.liddelow.dge <- guttenplan.A1$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
cleveland_guttenplan.A1_datasets.dge <- cleveland.liddelow.dge %>% left_join(guttenplan.A1.liddelow.dge, by = "gene_name") %>% left_join(astrocyte.reactivity.markers) %>% rename(Markers = group)

cleveland_A1_scatter.liddelow <- ggscatter(cleveland_guttenplan.A1_datasets.dge, x = "log2FC.ALS", y = "log2FC.A1", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
          xlab = expression( Log[2]~Fold~Change~SOD1~TRAP:CTRL), ylab = expression(Log[2]~Fold~Change~mouse~A1:A0), size = 0.5, cor.coeff.args = list(label.x = 1, label.y = -1)) + theme(legend.position = "top") +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
    geom_text_repel(data = filter(cleveland_guttenplan.A1_datasets.dge, log2FC.A1 > 0.1, log2FC.ALS > 0.1, gene_name %in% all.reactivity.go), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
  annotate(geom="text", x=2, y=8, label="SOD1 TRAP\n& A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(mouse~A1~and~SOD1~TRAP:Liddelow~markers))
cleveland_A1_scatter.liddelow

cleveland.liddelow_GEup <- cleveland.liddelow.dge %>% filter(log2FC.ALS > 0) %>% pull(gene_name)
guttenplan.A1.liddelow_GEup <- guttenplan.A1.liddelow.dge %>% filter(log2FC.A1 > 0) %>% pull(gene_name)
newGeneOverlap(cleveland.liddelow_GEup,guttenplan.A1.liddelow_GEup, genome.size=nrow(astrocyte.reactivity.markers)) %>% testGeneOverlap()
# GeneOverlap object:
# listA size=35
# listB size=32
# Intersection size=30
# Overlapping p-value=2.1e-04
# Jaccard Index=0.8

# # SOD1 TRAP & human A1
# cleveland.liddelow.dge <- cleveland$res %>% select(gene_name, gene_id, log2FC.ALS = log2FoldChange, FDR.ALS = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
# a1_datasets.liddelow.dge <- a1_datasets$res %>% select(gene_name, gene_id, log2FC.A1 = log2FoldChange, FDR.A1 = padj) %>% filter(gene_name %in% astrocyte.reactivity.markers$gene_name)
# cleveland_a1_datasets_datasets.dge <- cleveland.liddelow.dge %>% left_join(a1_datasets.liddelow.dge, by = "gene_name") %>% left_join(astrocyte.reactivity.markers) %>% rename(Markers = group)
# 
# cleveland_A1_scatter.liddelow <- ggscatter(cleveland_a1_datasets_datasets.dge, x = "log2FC.ALS", y = "log2FC.A1", color = "Markers", cor.coef = TRUE, cor.method = "pearson",
#           xlab = expression( Log[2]~Fold~Change~mouse~ALS:CTRL), ylab = expression(Log[2]~Fold~Change~mouse~A1:A0), size = 0.5, cor.coeff.args = list(label.x = 1, label.y = -4)) + theme(legend.position = "right") +
#           geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
#     geom_text_repel(data = filter(cleveland_a1_datasets_datasets.dge, log2FC.A1 > 0.1, log2FC.ALS > 0.1, gene_name %in% all.reactivity.go), aes(x = log2FC.ALS, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
#   annotate(geom="text", x=2, y=11, label="Mouse ALS models\n& A1 both Up", color="firebrick2", size = 3.2) + labs(subtitle = expression(A1~and~mouse~ALS~models:Liddelow~reactive~markers))
# cleveland_A1_scatter.liddelow
# 
# cleveland.liddelow_GEup <- cleveland.liddelow.dge %>% filter(log2FC.ALS > 0) %>% pull(gene_name)
# a1_datasets.liddelow_GEup <- a1_datasets.liddelow.dge %>% filter(log2FC.A1 > 0) %>% pull(gene_name)
# newGeneOverlap(cleveland.liddelow_GEup,a1_datasets.liddelow_GEup, genome.size=nrow(astrocyte.reactivity.markers)) %>% testGeneOverlap()
# # GeneOverlap object:
# # listA size=35
# # listB size=34
# # Intersection size=25
# # Overlapping p-value=0.96
# # Jaccard Index=0.6
```

## Liddelow heatmap

```{r}
mouse_als_datasets.dge <- mouse_als_datasets$res %>% select(gene_name, log2FC.ALS = log2FoldChange, FDR.ALS = padj)
guttenplan.sod1.dge <- guttenplan.sod1$res %>% select(gene_name, log2FC.SOD1 = log2FoldChange, FDR.SOD1 = padj)
cleveland_datasets.dge <- cleveland$res %>% select(gene_name, log2FC.SOD1.TRAP = log2FoldChange, FDR.SOD1.TRAP = padj)
peng_datasets.dge <- peng$res %>% select(gene_name, log2FC.TDP43 = log2FoldChange, FDR.TDP43 = padj)
jiang_datasets.dge <- jiang$res %>% select(gene_name, log2FC.MEM = log2FoldChange, FDR.MEM = padj)
guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.mouse.A1 = log2FoldChange, FDR.mouse.A1 = padj)
zamanian.A2.dge = zamanian.A2.res %>%  select(gene_name, log2FC.A2 = log2FoldChange, FDR.A2 = padj)
anderson.dge = anderson$res %>%  select(gene_name, log2FC.SCI = log2FoldChange, FDR.SCI = padj)

mouse_astrocyte.reactivity.marker <- mouse_als_datasets.dge %>% full_join(guttenplan.sod1.dge) %>% full_join(cleveland_datasets.dge) %>% full_join(peng_datasets.dge)  %>% full_join(jiang_datasets.dge) %>% left_join(guttenplan.A1.dge) %>% left_join(zamanian.A2.dge) %>% left_join(anderson.dge) %>%
  filter(gene_name %in% astrocyte.reactivity.markers$gene_name) %>% arrange(factor(gene_name, levels = astrocyte.reactivity.markers$gene_name)) %>%
  select(gene_name, "Sun et al.\nbacTRAP SOD1 vs CTRL" = log2FC.SOD1.TRAP, "Guttenplan et al.\nSOD1 vs CTRL" = log2FC.SOD1, "Peng et al.\nTDP43 KO vs CTRL" = log2FC.TDP43, "Jiang et al.\nMembralin KO vs CTRL" = log2FC.MEM, "Mouse\nmeta-analysis\npan-ALS vs CTRL" = log2FC.ALS, "Guttenplan et al.\nmouse TNFa IL1a C1q" = log2FC.mouse.A1, "Zamanian et al.\nmouse MCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse SCI vs CTRL" = log2FC.SCI) %>% distinct(gene_name, .keep_all = TRUE)

mouse_astrocyte.reactivity.marker.mat <- make_matrix(select(mouse_astrocyte.reactivity.marker,-gene_name), pull(mouse_astrocyte.reactivity.marker,gene_name))
mouse_astrocyte.reactivity.marker.mat.scale <- scale(mouse_astrocyte.reactivity.marker.mat, center = FALSE) # make variance equal between datasets
mouse_astrocyte.reactivity.markers.filt <- astrocyte.reactivity.markers %>% filter(gene_name %in% mouse_astrocyte.reactivity.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

mouse_astrocyte.reactivity.marker.heatmap <- Heatmap(mouse_astrocyte.reactivity.marker.mat.scale, 
          show_heatmap_legend = FALSE, col = col_ramp_reactivity.markers,
          cluster_rows = FALSE, cluster_columns = FALSE, cluster_row_slices = FALSE,
          row_split = factor(mouse_astrocyte.reactivity.markers.filt$group, levels = unique(mouse_astrocyte.reactivity.markers.filt$group)), row_order = mouse_astrocyte.reactivity.markers.filt$gene_name,
          row_names_gp = gpar(fontsize = 7), column_names_gp = gpar(fontsize = 8), border = TRUE,
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("Pan\nreactive", "A1", "A2"), labels_gp = gpar(fontsize = 7), labels_rot = 0)),
          row_title = "Liddelow et al. Reactive astrocyte markers", row_title_gp = gpar(fontsize = 8),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("mouse ALS models ", "A1", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,1,1,1,1,2,3,3))
mouse_astrocyte.reactivity.marker.heatmap
ggsave(as.ggplot(mouse_astrocyte.reactivity.marker.heatmap), filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/mouse_astrocyte.reactivity.marker.heatmap.png", height = 5, width = 7)

```

## Escartin heatmap

Table 1 <https://www.nature.com/articles/s41593-020-00783-4>

```{r}
mouse_escartin.marker <- mouse_als_datasets.dge %>% full_join(guttenplan.sod1.dge) %>% full_join(cleveland_datasets.dge) %>% full_join(peng_datasets.dge)  %>% full_join(jiang_datasets.dge) %>% left_join(guttenplan.A1.dge) %>% left_join(zamanian.A2.dge) %>% left_join(anderson.dge) %>%
  filter(gene_name %in% escartin.markers$gene_name) %>% arrange(factor(gene_name, levels = escartin.markers$gene_name)) %>%
  select(gene_name, "Sun et al.\nbacTRAP SOD1 vs CTRL" = log2FC.SOD1.TRAP, "Guttenplan et al.\nSOD1 vs CTRL" = log2FC.SOD1, "Peng et al.\nTDP43 KO vs CTRL" = log2FC.TDP43, "Jiang et al.\nMembralin KO vs CTRL" = log2FC.MEM, "Mouse\nmeta-analysis\npan-ALS vs CTRL" = log2FC.ALS, "Guttenplan et al.\nmouse TNFa IL1a C1q" = log2FC.mouse.A1, "Zamanian et al.\nmouse MCAO vs CTRL" = log2FC.A2, "Anderson et al.\nmouse SCI vs CTRL" = log2FC.SCI) %>% distinct(gene_name, .keep_all = TRUE)

mouse_escartin.marker.mat <- make_matrix(select(mouse_escartin.marker,-gene_name), pull(mouse_escartin.marker,gene_name))
mouse_escartin.marker.mat.scale <- scale(mouse_escartin.marker.mat, center = FALSE) # make variance equal between datasets
escartin.markers.filt <- escartin.markers %>% filter(gene_name %in% escartin.marker$gene_name)

mouse_escartin.markers.filt <- escartin.markers %>% filter(gene_name %in% mouse_escartin.marker$gene_name)
col_ramp_reactivity.markers = colorRamp2(c(-3, 0, 3), c("blue", "white", "red")) # set colour limits to -3 to 3 to improve colour distribution, avoid outlier distortion

mouse_escartin.marker.heatmap <- Heatmap(mouse_escartin.marker.mat.scale, 
          heatmap_legend_param = list(title = ""), col = col_ramp_reactivity.markers,
          cluster_rows = FALSE, cluster_columns = FALSE, cluster_row_slices = FALSE,
          row_split = factor(mouse_escartin.markers.filt$group, levels = unique(mouse_escartin.markers.filt$group)), row_order = mouse_escartin.markers.filt$gene_name,
          row_names_gp = gpar(fontsize = 7), column_names_gp = gpar(fontsize = 8), border = TRUE,
          right_annotation = rowAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white", "white", "white", "white")), labels = c("Cytoskeleton", "Metabolism", "Chaperone", "Secreted\nproteins", "Cell\nsignalling", "Channels -\nTransporters"), labels_gp = gpar(fontsize = 7), labels_rot = 0)),
          row_title = "Escartin et al. Reactive astrocyte markers", row_title_gp = gpar(fontsize = 8),
          bottom_annotation = columnAnnotation(markers = anno_block(gp = gpar(fill = c("white", "white", "white")), labels = c("mouse ALS models ", "A1", "Protective"), labels_gp = gpar(fontsize = 8), labels_rot = 0)),
          column_title = NULL, column_names_rot = 90, column_names_centered = FALSE, column_split =  c(1,1,1,1,1,2,3,3)) 
mouse_escartin.marker.heatmap
# merge escartin heatmaps for rebuttal
ggsave(as.ggplot(mouse_escartin.marker.heatmap), filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/mouse_escartin.marker.heatmap.png", height = 5, width = 6)
```

## Merge

```{r}
figS11.merged <- ggarrange(
  mouse_ALS_A1_scatter.liddelow, cleveland_A1_scatter.liddelow,
  # ggarrange(mouse_ALS_A1_scatter.liddelow, A2_mouse_als_scatter.liddelow, ncol = 2, labels = c("A", "B"), widths = c(0.8,1)),
  as.ggplot(mouse_astrocyte.reactivity.marker.heatmap), as.ggplot(mouse_escartin.marker.heatmap), ncol = 2, nrow = 2, labels = c("A","B","C","D"))
figS11.merged
ggsave(figS11.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS11.merged.mouse.reactive.genes.png", height = 10, width = 10)

```


# Fig S12 Sod1 TRAP & panALS

## Scatterplot

```{r}
# hiPSC A1
cleveland.dge <- cleveland$res %>% select(gene_name, log2FC.Sod1_TRAP = log2FoldChange, FDR.Sod1_TRAP = padj) %>% filter(gene_name %in% gene2ens$gene_name) 
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
cleveland_a1_datasets.dge <- full_join(cleveland.dge, a1_datasets.dge, by = c("gene_name"))

cleveland_a1_datasets.dge <- cleveland_a1_datasets.dge %>% mutate(overlap = case_when(FDR.Sod1_TRAP < 0.05 & FDR.A1 < 0.05 ~ "overlapping", # down in Sod1_TRAP
                                                        FDR.Sod1_TRAP < 0.05 ~ "Sod1_TRAP specific",
                                                        FDR.A1 < 0.05 ~ "A1 specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP > 0 & FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "overlapping up", # down in Sod1_TRAP
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP < 0 & FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "overlapping down",
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP > 0 ~ "Sod1_TRAP specific up",
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP < 0 ~ "Sod1_TRAP specific down",
                                                                  FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "A1 specific up",
                                                                  FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "A1 specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "Sod1_TRAP specific up", "Sod1_TRAP specific down", "A1 specific up", "A1 specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "Sod1_TRAP specific", "A1 specific", "None"))) %>%
  arrange(overlap_direction)
table(cleveland_a1_datasets.dge$overlap)
table(cleveland_a1_datasets.dge$overlap_direction)
cleveland_a1_datasets.dge

cor.test(x = cleveland_a1_datasets.dge$log2FC.Sod1_TRAP, y = cleveland_a1_datasets.dge$log2FC.A1) # 0.065
t.test( x = cleveland_a1_datasets.dge$log2FC.Sod1_TRAP, y = cleveland_a1_datasets.dge$log2FC.A1, paired = TRUE )

hipsc.A1_Sod1_TRAP_scatter <- ggscatter(cleveland_a1_datasets.dge, x = "log2FC.Sod1_TRAP", y = "log2FC.A1", color = "overlap_direction", palette = c("firebrick2", "dodgerblue3", "grey", "grey", "grey", "grey", "grey"), 
                                        cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -4, label.y = 9, label.sep = "\n", size = 3),
          xlab = expression( Log[2]~Fold~Change~Sod1~TRAP:CTRL), ylab = expression(Log[2]~Fold~Change~hiPSC~A1:A0), size = 0.5) +
    coord_cartesian(xlim = c(-4,4), ylim = c(-5,10)) +
  theme(axis.title=element_text(size=10)) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
    geom_smooth(data = cleveland_a1_datasets.dge, aes(x = log2FC.Sod1_TRAP, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(cleveland_a1_datasets.dge, overlap_direction %in%  c("overlapping up", "overlapping down"), gene_name %in% all.reactivity.go, log2FC.A1 < 9.5), aes(x = log2FC.Sod1_TRAP, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 20) +  
  annotate(geom="text", x=2, y=10, label="Sod1 TRAP & A1 Up", color="firebrick2", size = 3.2)  + annotate(geom="text", x=-2, y=-4, label="Sod1 TRAP & A1 Down", color="dodgerblue3", size = 3.2) #+ labs(subtitle = "Sod1 TRAP vs A1")
hipsc.A1_Sod1_TRAP_scatter

# mouse A1
cleveland.dge <- cleveland$res %>% select(gene_name, log2FC.Sod1_TRAP = log2FoldChange, FDR.Sod1_TRAP = padj) %>% filter(gene_name %in% gene2ens$gene_name) 
guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.A1 = log2FoldChange, FDR.A1 = padj)
cleveland_guttenplan.A1.dge <- full_join(cleveland.dge, guttenplan.A1.dge, by = c("gene_name"))

cleveland_guttenplan.A1.dge <- cleveland_guttenplan.A1.dge %>% mutate(overlap = case_when(FDR.Sod1_TRAP < 0.05 & FDR.A1 < 0.05 ~ "overlapping", # down in Sod1_TRAP
                                                        FDR.Sod1_TRAP < 0.05 ~ "Sod1_TRAP specific",
                                                        FDR.A1 < 0.05 ~ "A1 specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP > 0 & FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "overlapping up", # down in Sod1_TRAP
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP < 0 & FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "overlapping down",
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP > 0 ~ "Sod1_TRAP specific up",
                                                                  FDR.Sod1_TRAP < 0.05 & log2FC.Sod1_TRAP < 0 ~ "Sod1_TRAP specific down",
                                                                  FDR.A1 < 0.05 & log2FC.A1 > 0 ~ "A1 specific up",
                                                                  FDR.A1 < 0.05 & log2FC.A1 < 0 ~ "A1 specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "Sod1_TRAP specific up", "Sod1_TRAP specific down", "A1 specific up", "A1 specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "Sod1_TRAP specific", "A1 specific", "None"))) %>%
  arrange(overlap_direction)
table(cleveland_guttenplan.A1.dge$overlap)
table(cleveland_guttenplan.A1.dge$overlap_direction)
cleveland_guttenplan.A1.dge

cor.test(x = cleveland_guttenplan.A1.dge$log2FC.Sod1_TRAP, y = cleveland_guttenplan.A1.dge$log2FC.A1) # 0.1088784 
t.test( x = cleveland_guttenplan.A1.dge$log2FC.Sod1_TRAP, y = cleveland_guttenplan.A1.dge$log2FC.A1, paired = TRUE )

mouse.A1_Sod1_TRAP_scatter <- ggscatter(cleveland_guttenplan.A1.dge, x = "log2FC.Sod1_TRAP", y = "log2FC.A1", color = "overlap_direction", palette = c("firebrick2", "dodgerblue3", "grey", "grey", "grey", "grey", "grey"),
                                        cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -3, label.y = 7, label.sep = "\n", size = 3),
          xlab = expression( Log[2]~Fold~Change~Sod1~TRAP:CTRL), ylab = expression(Log[2]~Fold~Change~mouse~A1:A0), size = 0.5) +
      coord_cartesian(xlim = c(-4,4), ylim = c(-5,8)) +
    theme(axis.title=element_text(size=10)) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   xlim(-5,5) + ylim(-10,11) +
    geom_smooth(data = cleveland_guttenplan.A1.dge, aes(x = log2FC.Sod1_TRAP, y = log2FC.A1), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(cleveland_guttenplan.A1.dge, overlap_direction %in%  c("overlapping up", "overlapping down"), gene_name %in% all.reactivity.go, log2FC.A1 < 9.5), aes(x = log2FC.Sod1_TRAP, y = log2FC.A1, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 20) +  
  annotate(geom="text", x=2, y=8, label="Sod1 TRAP & A1 Up", color="firebrick2", size = 3.2)  + annotate(geom="text", x=-2, y=-5, label="Sod1 TRAP & A1 Down", color="dodgerblue3", size = 3.2) #+ labs(subtitle = "Sod1 TRAP vs A1")
mouse.A1_Sod1_TRAP_scatter

# MCAO
cleveland.res.zamanian <- cleveland$res %>% select(gene_name, log2FC.Sod1.TRAP = log2FoldChange, FDR.Sod1.TRAP = padj) %>%  drop_na(log2FC.Sod1.TRAP) %>% distinct(gene_name, .keep_all = TRUE)
zamanian.res.filt <- zamanian.A2.res %>% select(gene_name, log2FC.MCAO = log2FoldChange, FDR.MCAO = padj) %>% drop_na(log2FC.MCAO) %>% distinct(gene_name, .keep_all = TRUE)
cleveland_zamanian.dge <- full_join(cleveland.res.zamanian, zamanian.res.filt, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.Sod1.TRAP < 0.05 & FDR.MCAO < 0.05 ~ "overlapping", # down in Sod1.TRAP
                                                        FDR.Sod1.TRAP < 0.05 ~ "Sod1.TRAP specific",
                                                        FDR.MCAO < 0.05 ~ "MCAO specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "overlapping up", # down in Sod1.TRAP
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "overlapping down",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 & FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "Sod1.TRAP up, MCAO down", # down in Sod1.TRAP
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 & FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "Sod1.TRAP down, MCAO up",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 ~ "Sod1.TRAP specific up",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 ~ "Sod1.TRAP specific down",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO > 0 ~ "MCAO specific up",
                                                                  FDR.MCAO < 0.05 & log2FC.MCAO < 0 ~ "MCAO specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "Sod1.TRAP up, MCAO down", "Sod1.TRAP down, MCAO up", "Sod1.TRAP specific up", "Sod1.TRAP specific down", "MCAO specific up", "MCAO specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "Sod1.TRAP specific", "MCAO specific", "None"))) %>%
  arrange(overlap_direction)
# table(cleveland_zamanian.dge$overlap_direction)
# overlapping up  overlapping down   Sod1.TRAP specific up Sod1.TRAP specific down    MCAO specific up  MCAO specific down 
#               109               150               963              1198              1181              1276 
cor.test(x = cleveland_zamanian.dge$log2FC.Sod1.TRAP, y = cleveland_zamanian.dge$log2FC.MCAO) #  MCAO.day1_vs_A0.day1 0.09 

MCAO_Sod1.TRAP_scatter <- ggscatter(cleveland_zamanian.dge, x = "log2FC.Sod1.TRAP", y = "log2FC.MCAO", 
                                    cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -4, label.y = -2.5, label.sep = "\n", size = 3), 
                            color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"),
  xlab = expression( Log[2]~Fold~Change~Sod1~TRAP:CTRL), ylab = expression(Log[2]~Fold~Change~MCAO:Sham), size = 0.5) +
  theme(axis.title=element_text(size=10)) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
  coord_cartesian(xlim = c(-4,4), ylim = c(-3,5)) +
  geom_smooth(data = cleveland_zamanian.dge, aes(x = log2FC.Sod1.TRAP, y = log2FC.MCAO), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
  geom_text_repel(data = filter(cleveland_zamanian.dge, overlap_direction %in%  c("Sod1.TRAP up, MCAO down", "Sod1.TRAP down, MCAO up"), gene_name %in% all.reactivity.go), aes(x = log2FC.Sod1.TRAP, y = log2FC.MCAO, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) + 
  annotate(geom="text", x=2, y=-2.5, label="Sod1.TRAP up\nMCAO down", color="forestgreen", size = 3.2) + annotate(geom="text", x=-2, y=4.5, label="Sod1.TRAP down\nMCAO up", color="gold2", size = 3.2) #+ labs(subtitle = "Sod1 TRAP vs MCAO")
MCAO_Sod1.TRAP_scatter


## SCI & Sod1.TRAP scatter correlation
cleveland.dge <- cleveland$res %>% select(gene_name, gene_id, log2FC.Sod1.TRAP = log2FoldChange, FDR.Sod1.TRAP = padj)
anderson.dge <- anderson$res %>% select(gene_name, gene_id, log2FC.SCI = log2FoldChange, FDR.SCI = padj)
cleveland_anderson.dge <- full_join(cleveland.dge, anderson.dge, by = "gene_name") %>% 
  mutate(overlap = case_when(FDR.Sod1.TRAP < 0.05 & FDR.SCI < 0.05 ~ "overlapping", # down in Sod1.TRAP
                                                        FDR.Sod1.TRAP < 0.05 ~ "Sod1.TRAP specific",
                                                        FDR.SCI < 0.05 ~ "SCI specific",
                                                        TRUE ~ "None"),
                                    overlap_direction = case_when(FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "overlapping up", # down in Sod1.TRAP
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "overlapping down",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 & FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "Sod1.TRAP up, SCI down",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 & FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "Sod1.TRAP down, SCI up",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 ~ "Sod1.TRAP specific up",
                                                                  FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 ~ "Sod1.TRAP specific down",
                                                                  FDR.SCI < 0.05 & log2FC.SCI > 0 ~ "SCI specific up",
                                                                  FDR.SCI < 0.05 & log2FC.SCI < 0 ~ "SCI specific down",
                                                                  TRUE ~ "None"),
                                    overlap_direction = factor(overlap_direction, levels = c("overlapping up", "overlapping down", "Sod1.TRAP up, SCI down", "Sod1.TRAP down, SCI up", "Sod1.TRAP specific up", "Sod1.TRAP specific down", "SCI specific up", "SCI specific down", "None")),
                                    overlap = factor(overlap, levels = c("overlapping",  "Sod1.TRAP specific", "SCI specific", "None"))) %>%
  arrange(overlap_direction)
table(cleveland_anderson.dge$overlap)
table(cleveland_anderson.dge$overlap_direction)

cor.test(x = cleveland_anderson.dge$log2FC.Sod1.TRAP, y = cleveland_anderson.dge$log2FC.SCI) # 0.1088784 
t.test( x = cleveland_anderson.dge$log2FC.Sod1.TRAP, y = cleveland_anderson.dge$log2FC.SCI, paired = TRUE )

SCI_Sod1.TRAP_scatter <- ggscatter(cleveland_anderson.dge, x = "log2FC.Sod1.TRAP", y = "log2FC.SCI", 
                                   cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = -4, label.y = -5, label.sep = "\n", size = 3), 
                             color = "overlap_direction", palette = c("firebrick2", "dodgerblue2", "forestgreen", "gold2", "grey", "grey", "grey", "grey", "grey"), 
          xlab = expression( Log[2]~Fold~Change~Sod1~TRAP:CTRL), ylab = expression(Log[2]~Fold~Change~SCI:CTRL), size = 0.5) +
    theme(axis.title=element_text(size=10)) +
          geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") +   
    coord_cartesian(xlim = c(-4,4), ylim = c(-6,8)) +
    geom_smooth(data = cleveland_anderson.dge, aes(x = log2FC.Sod1.TRAP, y = log2FC.SCI), method = "lm", se = FALSE, show.legend = TRUE, colour = "black", linetype = 2) + theme(legend.position = "none") +
    geom_text_repel(data = filter(cleveland_anderson.dge, overlap_direction %in%  c("Sod1.TRAP up, SCI down", "Sod1.TRAP down, SCI up"), gene_name %in% all.reactivity.go, log2FC.SCI < 9), aes(x = log2FC.Sod1.TRAP, y = log2FC.SCI, label = gene_name), fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.7, max.overlaps = 30) +  
  annotate(geom="text", x=2, y=-5.5, label="Sod1.TRAP up\nSCI down", color="forestgreen", size = 3.2)  + annotate(geom="text", x=-2, y=7.5, label="Sod1.TRAP down\nSCI up", color="gold2", size = 3.2) #+ labs(subtitle = "Sod1 TRAP vs SCI")
SCI_Sod1.TRAP_scatter

```

## Venn

```{r}
cleveland.res.dge.up <- cleveland$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
cleveland.res.dge.down <- cleveland$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
als_datasets.res.dge.up <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
als_datasets.res.dge.down <- als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.up <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
mouse_als_datasets.res.dge.down <- mouse_als_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
a1_datasets.res.dge.up <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
a1_datasets.res.dge.down <- a1_datasets$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)
guttenplan.A1.res.dge.up <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange > 0) %>% pull(gene_name)
guttenplan.A1.res.dge.down <- guttenplan.A1$res %>% filter(padj < 0.05, log2FoldChange < 0) %>% pull(gene_name)


# 3 way overlap Sod1 TRAP, mouse A1, hiPSC A1
cleveland.a1_datasets.guttenplan.A1_up_genes <- list("Sod1 TRAP Up" = cleveland.res.dge.up, "hiPSC A1 Up" = a1_datasets.res.dge.up, "mouse A1 Up" = guttenplan.A1.res.dge.up)
cleveland.a1_datasets.guttenplan.A1_up_genes_venn <- ggvenn(cleveland.a1_datasets.guttenplan.A1_up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
cleveland.a1_datasets.guttenplan.A1_down_genes <- list("Sod1 TRAP Down" = cleveland.res.dge.down, "hiPSC A1 Down" = a1_datasets.res.dge.down, "mouse A1 Down" = guttenplan.A1.res.dge.down)
cleveland.a1_datasets.guttenplan.A1_down_genes_venn <- ggvenn(cleveland.a1_datasets.guttenplan.A1_down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
guttenplan.A1_a1_datasets_cleveland_venn = ggarrange(cleveland.a1_datasets.guttenplan.A1_up_genes_venn, cleveland.a1_datasets.guttenplan.A1_down_genes_venn, ncol = 2)
guttenplan.A1_a1_datasets_cleveland_venn

# Chi-squared 3 way overlap
list1 <- unique(cleveland.res.dge.up[!is.na(cleveland.res.dge.up)])
list2 <- unique(a1_datasets.res.dge.up[!is.na(a1_datasets.res.dge.up)])
list3 <- unique(guttenplan.A1.res.dge.up[!is.na(guttenplan.A1.res.dge.up)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anova(glm1,glm2,test='Chisq')[['Pr(>Chi)']][2] 
# [1] 4.715679e-11

list1 <- unique(cleveland.res.dge.down[!is.na(cleveland.res.dge.down)])
list2 <- unique(a1_datasets.res.dge.down[!is.na(a1_datasets.res.dge.down)])
list3 <- unique(guttenplan.A1.res.dge.down[!is.na(guttenplan.A1.res.dge.down)])
univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
anova(glm1,glm2,test='Chisq')[['Pr(>Chi)']][2] 
# [1] 5.940412e-09

# # 3 way overlap mouse ALS, hiPSC ALS, Sod1 TRAP
# cleveland.mouse_human_ALS.up_genes <- list("Sod1 TRAP Up" = cleveland.res.dge.up, "hiPSC ALS Up" = als_datasets.res.dge.up, "mouse ALS Up" = mouse_als_datasets.res.dge.up)
# cleveland.mouse_human_ALS.down_genes <- list("Sod1 TRAP Down" = cleveland.res.dge.down, "hiPSC ALS Down" = als_datasets.res.dge.down, "mouse ALS Down" = mouse_als_datasets.res.dge.down)
# cleveland.mouse_human_ALS.up_genes_venn <- ggvenn(cleveland.mouse_human_ALS.up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
# cleveland.mouse_human_ALS.down_genes_venn <- ggvenn(cleveland.mouse_human_ALS.down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen"), text_size = 3, show_percentage = FALSE, stroke_size = 0.4, set_name_size = 2.8, set_name_color = c("dodgerblue3", "firebrick1", "forestgreen")) +  theme(plot.margin = unit(c(0, -1, 0, -1), "lines"))
# cleveland.mouse_human_ALS.genes_venn = ggarrange(cleveland.mouse_human_ALS.up_genes_venn, cleveland.mouse_human_ALS.down_genes_venn, nrow = 2)
# cleveland.mouse_human_ALS.genes_venn
# 
# # Chi-squared 3 way overlap
# list1 <- unique(cleveland.res.dge.up[!is.na(cleveland.res.dge.up)])
# list2 <- unique(als_datasets.res.dge.up[!is.na(als_datasets.res.dge.up)])
# list3 <- unique(mouse_als_datasets.res.dge.up[!is.na(mouse_als_datasets.res.dge.up)])
# univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
# xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
# ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
# glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
# glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
# anova(glm1,glm2,test='Chisq')[['Pr(>Chi)']][2] # P value 2.023613e-08
# 
# list1 <- unique(cleveland.res.dge.down[!is.na(cleveland.res.dge.down)])
# list2 <- unique(als_datasets.res.dge.down[!is.na(als_datasets.res.dge.down)])
# list3 <- unique(mouse_als_datasets.res.dge.down[!is.na(mouse_als_datasets.res.dge.down)])
# univ <- unique(gtf$gene_name[!is.na(gtf$gene_name)])
# xtab <- data.frame(Univ=univ, List1=as.integer(univ %in% list1), List2=as.integer(univ %in% list2), List3=as.integer(univ %in% list3))
# ftable <- as.data.frame(table(xtab[,c('List1','List2','List3')]))
# glm1 <- glm(Freq ~ List1 * List2 * List3, family='poisson',data=ftable)
# glm2 <- glm(Freq ~ List1*List2 + List1*List3 + List2*List3, family='poisson',data=ftable)
# anova(glm1,glm2,test='Chisq')[['Pr(>Chi)']][2] # 1.59116e-07


# # 4 way overlap Sod1 TRAP, hiPSC ALS, mouse A1, hiPSC A1
# als.cleveland.a1_datasets.guttenplan.A1_up_genes <- list("ALS\nhiPSC" = als_datasets.res.dge.up, "Sod1\nbacTRAP" = cleveland.res.dge.up, "hiPSC\nA1" = a1_datasets.res.dge.up, "mouse\nA1" = guttenplan.A1.res.dge.up)
# als.cleveland.a1_datasets.guttenplan.A1_up_genes_venn <- ggvenn(als.cleveland.a1_datasets.guttenplan.A1_up_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen", "gold2"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.3, text_size = 3) +
#   theme(plot.subtitle = element_text(hjust = 0.5, colour = "firebrick2"))#, plot.margin = unit(c(0, -1, 0, -1), "lines"))
# als.cleveland.a1_datasets.guttenplan.A1_down_genes <- list("ALS\nhiPSC" = als_datasets.res.dge.down, "Sod1\nbacTRAP" = cleveland.res.dge.down, "hiPSC\nA1" = a1_datasets.res.dge.down, "mouse\nA1" = guttenplan.A1.res.dge.down)
# als.cleveland.a1_datasets.guttenplan.A1_down_genes_venn <- ggvenn(als.cleveland.a1_datasets.guttenplan.A1_down_genes, fill_color = c("dodgerblue3", "firebrick1", "forestgreen", "gold2"), show_percentage = FALSE, stroke_size = 0.4, set_name_size = 3.3, text_size = 3) +
#   theme(plot.subtitle = element_text(hjust = 0.5, colour = "dodgerblue2"))#, plot.margin = unit(c(0, -1, 0, -1), "lines"))
# als.guttenplan.A1_a1_datasets_cleveland_venn = ggarrange(als.cleveland.a1_datasets.guttenplan.A1_up_genes_venn, als.cleveland.a1_datasets.guttenplan.A1_down_genes_venn, ncol = 2)
# als.guttenplan.A1_a1_datasets_cleveland_venn

```

## GO overlap

```{r}
Sod1.trap.hipsc.a1.overlap.up = cleveland.res.dge.up[cleveland.res.dge.up %in% a1_datasets.res.dge.up]
Sod1.trap.hipsc.mouse.a1.overlap.up = Sod1.trap.hipsc.a1.overlap.up[Sod1.trap.hipsc.a1.overlap.up %in% guttenplan.A1.res.dge.up]
Sod1.trap.hipsc.a1.overlap.down = cleveland.res.dge.down[cleveland.res.dge.down %in% a1_datasets.res.dge.down]
Sod1.trap.hipsc.mouse.a1.overlap.down = Sod1.trap.hipsc.a1.overlap.down[Sod1.trap.hipsc.a1.overlap.down %in% guttenplan.A1.res.dge.down]

Sod1.trap.hipsc.mouse.a1.overlap.up.gost = gost(Sod1.trap.hipsc.mouse.a1.overlap.up)
Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt <- Sod1.trap.hipsc.mouse.a1.overlap.up.gost$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% mutate( term_name = as.factor(term_name)) 
Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt

Sod1.trap.hipsc.mouse.a1.overlap.down.gost = gost(Sod1.trap.hipsc.mouse.a1.overlap.down)
Sod1.trap.hipsc.mouse.a1.overlap.down_gprofiles_filt <- Sod1.trap.hipsc.mouse.a1.overlap.down.gost$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% mutate( term_name = as.factor(term_name)) 
Sod1.trap.hipsc.mouse.a1.overlap.down_gprofiles_filt

paste('"',unique(Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt$term_name),'",', sep = "", collapse = '\n') %>% cat()
Sod1.trap.hipsc.mouse.a1.overlap.up_curated_list <- c("immune system process",
# "protein folding in endoplasmic reticulum",
# "response to stimulus",
"extracellular matrix",
"collagen fibril organization",
# "blood vessel development",
# "Metabolism of proteins",
"cell adhesion",
"collagen fibril organization",
"response to stress",
"immune system process",
"Collagen formation",
"Protein processing in endoplasmic reticulum",
"focal adhesion",
"angiogenesis",
"extracellular matrix organization",
"endoplasmic reticulum",
"wound healing",
"Interferon Signaling",
"response to interferon-gamma",
"Interferon alpha/beta signaling",
"TNF signaling pathway",
"immune response",
"inflammatory response",
"immune system process",
"defense response",
"response to stress",
"response to cytokine")
Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt.up <- Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt %>% filter(term_name %in% Sod1.trap.hipsc.mouse.a1.overlap.up_curated_list) %>% mutate(query = "A1 & Sod1 TRAP Up")
paste('"',unique(Sod1.trap.hipsc.mouse.a1.overlap.down_gprofiles_filt$term_name),'",', sep = "", collapse = '\n') %>% cat()
cleveland_a1.go_curated <- curated_profiles(gprofiles = Sod1.trap.hipsc.mouse.a1.overlap.up_gprofiles_filt.up, colours = 1) + labs(subtitle = "A1 & pan-ALS\noverlap")
cleveland_a1.go_curated

# 
# # Sod1 TRAP
# cleveland_a1_datasets.dge_overlap_genes <- cleveland_a1_datasets.dge %>% filter(overlap_direction == "overlapping up" | overlap_direction == "overlapping down" ) %>% split(.$overlap_direction) %>%  map("gene_name")
# cleveland_a1_datasets.dge_overlap_genes <- gost(cleveland_a1_datasets.dge_overlap_genes) # run gprofiler2 on all groups - runs on all KEGG, GO, REAC,TF, WP pathways simultaneously
# cleveland_a1_datasets.dge_overlap_gprofiles_filt <- cleveland_a1_datasets.dge_overlap_genes$result %>% filter(str_detect(source, "KEGG|GO:BP|GO:MF|GO:CC|REAC|CORUM")) %>% arrange( -log10(p_value) ) %>% mutate( term_name = as.factor(term_name)) 
# cleveland_a1_datasets.dge_overlap_gprofiles_filt
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up <- cleveland_a1_datasets.dge_overlap_gprofiles_filt %>% filter(query == "overlapping up")
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down <- cleveland_a1_datasets.dge_overlap_gprofiles_filt %>% filter(query == "overlapping down")
# paste('"',unique(cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up$term_name),'",', sep = "", collapse = '\n') %>% cat()
# cleveland_a1_datasets.dge.up_curated_list <- c(
# "cell communication",
# "Signaling by Interleukins",
# "cell surface receptor signaling pathway",
# "inflammatory response",
# "immune response",
# "Interferon alpha/beta signaling",
# "immune system process",
# "defense response",
# "response to stress",
# "response to cytokine")
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up <- cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up %>% filter(term_name %in% cleveland_a1_datasets.dge.up_curated_list) %>% mutate(query = "upregulated")
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up$term_name <- gsub("cell surface receptor", "receptor", cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up$term_name) %>% gsub("alpha/beta ", "", .)
# 
# paste('"',unique(cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down$term_name),'",', sep = "", collapse = '\n') %>% cat()
# cleveland_a1_datasets.dge.up_curated_list <- c(
# "spinal cord development",
# "actin cytoskeleton",
# "generation of neurons",
# "adherens junction",
# "neuron differentiation",
# "Deactivation of the beta-catenin transactivating complex",
# "nervous system development",
# "cell cortex")
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down <- cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down %>% filter(term_name %in% cleveland_a1_datasets.dge.up_curated_list) %>% mutate(query = "downregulated")
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down$term_name <- gsub("Deactivation of the beta-catenin transactivating complex", "beta-catenin complex", cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down$term_name)
# 
# cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up_down <- bind_rows(cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up, cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.down) %>% 
#   mutate(query = factor(query, levels = c("upregulated", "downregulated")))
# cleveland_a1_datasets.go_curated <- curated_profiles(gprofiles = cleveland_a1_datasets.dge_overlap_gprofiles_filt_dge.up_down, colours = 2) + labs(subtitle = "A1 & Sod1 TRAP")
# cleveland_a1_datasets.go_curated
# 
# cleveland_a1_datasets.dge_overlap_gprofiles_filt <- apply(cleveland_a1_datasets.dge_overlap_gprofiles_filt,2,as.character)
# write.csv(cleveland_a1_datasets.dge_overlap_gprofiles_filt, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/cleveland_a1_datasets_overlap_go_terms.csv")
```

## Merge

```{r}
figS12.merged <- ggarrange(
  ggarrange(hipsc.A1_Sod1_TRAP_scatter, mouse.A1_Sod1_TRAP_scatter, MCAO_Sod1.TRAP_scatter, SCI_Sod1.TRAP_scatter, ncol = 2, nrow = 2, labels = c("B", "C", "D", "E")),
  ggarrange(guttenplan.A1_a1_datasets_cleveland_venn, cleveland_a1.go_curated, ncol = 2, labels = c("F", "G"), widths = c(2,1)),
  nrow = 2, heights = c(2,0.8))
figS12.merged
ggsave(figS12.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/figS12.Sod1.trap.png", height = 10, width = 9)
```


# Table S10 Sod1 TRAP

```{r}
cleveland.dge <- cleveland$res %>% select(gene_name, log2FC.Sod1.TRAP = log2FoldChange, FDR.Sod1.TRAP = padj) %>% 
  mutate(direction.Sod1.TRAP = case_when(FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP > 0 ~ "up", FDR.Sod1.TRAP < 0.05 & log2FC.Sod1.TRAP < 0 ~ "down", TRUE ~ "non-significant"))
guttenplan.A1.dge <- guttenplan.A1$res %>% select(gene_name, log2FC.mouse.A1 = log2FoldChange, FDR.mouse.A1 = padj) %>% 
  mutate(direction.mouse.A1 = case_when(FDR.mouse.A1 < 0.05 & log2FC.mouse.A1 > 0 ~ "up", FDR.mouse.A1 < 0.05 & log2FC.mouse.A1 < 0 ~ "down", TRUE ~ "non-significant"))
a1_datasets.dge <- a1_datasets$res %>% select(gene_name, log2FC.hipsc.A1 = log2FoldChange, FDR.hipsc.A1 = padj) %>% 
  mutate(direction.hipsc.A1 = case_when(FDR.hipsc.A1 < 0.05 & log2FC.hipsc.A1 > 0 ~ "up", FDR.hipsc.A1 < 0.05 & log2FC.hipsc.A1 < 0 ~ "down", TRUE ~ "non-significant"))

Sod1.TRAP_guttenplan.A1_merged.dge <- cleveland.dge %>% full_join(guttenplan.A1.dge) %>%  full_join(a1_datasets.dge) %>%
  mutate(overlap = case_when(direction.Sod1.TRAP == "up" & direction.hipsc.A1 == "up" & direction.mouse.A1 == "up"   ~ "overlapping up",
                             direction.Sod1.TRAP == "down" & direction.hipsc.A1 == "down" & direction.mouse.A1 == "down" ~ "overlapping down",
                             direction.Sod1.TRAP == "up" & direction.hipsc.A1 == "up"  ~ "Sod1 TRAP & hipsc A1 up",
                             direction.Sod1.TRAP == "down" & direction.hipsc.A1 == "down" ~ "Sod1 TRAP & hipsc A1  down",
                             direction.Sod1.TRAP == "up" & direction.mouse.A1 == "up"   ~ "Sod1 TRAP & mouse A1 up",
                             direction.Sod1.TRAP == "down" & direction.mouse.A1 == "down" ~ "Sod1 TRAP & mouse A1 down",
                             direction.Sod1.TRAP == "up" ~ "Sod1.TRAP up", 
                             direction.Sod1.TRAP == "down" ~ "Sod1.TRAP down",
                             TRUE ~ "None"),
         overlap = factor(overlap, levels = c("overlapping up",  "overlapping down", "Sod1.TRAP up", "Sod1.TRAP down","A1 up","A1 down","None"))) %>%  
  arrange(overlap) %>%  select(gene_name, overlap, everything()) %>% filter(overlap != "None")

write_csv(Sod1.TRAP_guttenplan.A1_merged.dge, "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/expression/deseq2/TableS10.overlap_Sod1.TRAP_A1.csv")


```


# Additional analyses

## IR meta-analysis

### hiPSC ALS

```{r}

ir.als_datasets = IRFinder.analysis(metadata = als_datasets, sample.names = "sample", condition = "group", ctrl = "ctrl", mut = "als", file.var = "irfinder", dir = TRUE, ge.res = als_datasets.res,
                                               irfinder.dir = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder")

ir.als_datasets$irfinder
ir.als_datasets$ir.ge

### Density 
ir.als_datasets.irfinder.filt <- ir.als_datasets$irfinder %>% filter(baseMean > 10, log2FoldChange != 0) %>% drop_na(log2FoldChange) %>% mutate(condition = "ALS vs CTRL")
mu <- ir.als_datasets.irfinder.filt %>% summarise(grp.mean=mean(log2FoldChange, na.rm = TRUE)) %>% mutate(condition = "ALS vs CTRL")
ir.als_datasets.irfinder.filt.density <- ggplot(ir.als_datasets.irfinder.filt, aes(x = log2FoldChange, color = condition, fill = condition)) + 
  geom_density(alpha = 0.5) +
  scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8))+
  geom_vline(data = mu, aes(xintercept=grp.mean, color=condition), linetype="dashed") +
  xlab(label = expression(IR~Log[2]~FC~ALS:CTRL) )  + geom_vline(xintercept =0, linetype = 2) +  
  coord_cartesian(xlim=c(-2.5,2.5), ylim=c(0,1.0)) +
  # facet_grid(. ~ condition) + 
  geom_segment(aes(x = 1, xend = 2.5, y= 0.6, yend= 0.6), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  geom_segment(aes(x = -1, xend = -2.5, y= 0.6, yend= 0.6),arrow=arrow(length=unit(0.3,"cm")), color = "black") +
  annotate("text", x = 1.7, y = 0.65, label = "IR increased\nin ALS", colour = "black", size = 2.7) +   
  annotate("text", x = -1.7, y =  0.65, label = "IR decreased\nin ALS", colour = "black", size = 2.7)
ir.als_datasets.irfinder.filt.density


### Violin
irfinder.als_vs_ctrl.one.sample.stats_test <- ir.als_datasets.irfinder.filt %>% group_by(condition) %>% wilcox_test(log2FoldChange ~ 1, mu = 0) %>% add_significance()
irfinder.als_vs_ctrl.one.sample.stats_test
# condition .y.    group1 group2     n statistic        p p.signif
# * <chr>     <chr>  <chr>  <chr>  <int>     <dbl>    <dbl> <chr>   
# 1 A1 vs A0  log2F? 1      null ? 90497    2.00e9 2.65e-10 ****    

ir.als_datasets.irfinder.filt %>% cohens_d(log2FoldChange ~ 1, var.equal = TRUE) # Cohens d effect size indicates direction of effect
# .y.            group1 group2     effsize      n magnitude
# * <chr>          <chr>  <chr>        <dbl>  <int> <ord>    
# 1 log2FoldChange 1      null model  -0.316 101136 small    

# Sina violin plot: one sample stats nuc & cyto IR ratio LFC VCP vs CTRL
irfinder.als_vs_ctrl.sina_plot <- ggplot(ir.als_datasets.irfinder.filt, aes(x = condition, y= log2FoldChange, color = condition)) + 
      geom_violin() + geom_sina(size = 0.5) + geom_boxplot(aes(fill = condition), colour = "black", width=0.2, outlier.shape = NA) +
      scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +  
      theme_classic() + theme(legend.position = "none", axis.text=element_text(size=10), axis.title=element_text(size=10)) +
  coord_cartesian(ylim=c(-2,2)) +  
  geom_hline(yintercept = 0, linetype = 2) + 
  stat_pvalue_manual(irfinder.als_vs_ctrl.one.sample.stats_test, label = "p.signif", xmin = "condition", xmax = NULL, y.position = 1.8, hide.ns = FALSE) +
  ylab(label = expression(IR~Log[2]~FC~ALS:CTRL)) + xlab("") +
  geom_segment(aes(x = 1.5, xend = 1.5, y= 0.5, yend= 2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + geom_segment(aes(x = 1.5, xend = 1.5, y= -0.5, yend= -2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  annotate("text", x = 1.3, y = 1.2, label = "IR up in ALS", colour = "black", size = 2.7, angle = 90) + annotate("text", x = 1.3, y = -1.2, label = "IR down in ALS", colour = "black", size = 2.7, angle = 90)
irfinder.als_vs_ctrl.sina_plot


# Scatterplot
lifearc.labels = c("PLOD3", "MCAM", "CHERP", "ERAP2", "FN1", "ILK", "OSMR", "FLNA", "MRC2", "ACTN4", "C3")

ir.ge.als_vs_ctrl.scatter <- ggscatter(ir.als_datasets$ir.ge, x = "IR.log2FoldChange.norm", y = "GE.log2FoldChange", color = "significant", 
                                                      palette = c("firebrick2", "forestgreen", "dodgerblue2", "grey"),
                                            cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = 1, label.y = 4),
          xlab = expression(Intron~Retention~LFC~ALS:CTRL), ylab = expression(Gene~Expression~LFC~ALS:CTRL), size = 0.5) + 
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8), axis.title=element_text(size=10)) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
  coord_cartesian(ylim=c(-4,4), xlim = c(-3.5,3.5)) +
  # geom_text_repel(data = filter(ir.als_datasets$ir.ge, significant == "both", gene_name %in% all.reactivity.go), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
  #                 fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.als_datasets$ir.ge, significant == "both", gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name, glutamate.uptake.go, lifearc.labels)), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.als_datasets$ir.ge, significant == "both", abs(IR.log2FoldChange.norm) > 1.5, abs(GE.log2FoldChange) > 1.5), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_smooth(data = ir.als_datasets$ir.ge, aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange), method = "lm", se = F, show.legend = TRUE, colour = "black", linetype = 2)  + 
  annotate(geom="text", x=2, y=-3.5, label="IR up\nmRNA down", color="darkgrey", size = 2.8)  + annotate(geom="text", x=2, y=3.55, label="IR up\nmRNA up", color="darkgrey", size = 2.8)  + 
  annotate(geom="text", x=-2, y=3.5, label="IR down\nmRNA up", color="firebrick2", size = 2.8) +   annotate(geom="text", x=-2, y=-3.5, label="IR down\nmRNA down", color="darkgrey", size = 2.8)
ir.ge.als_vs_ctrl.scatter
ggsave(ir.ge.als_vs_ctrl.scatter, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.als_vs_ctrl.scatter.png")


### IR & GE GO terms
ir.ge.als_vs_ctrl.gost <- ir.als_datasets$ir.ge %>% filter(GE.pvalue < 0.05, IR.pvalue < 0.05) %>% group_split(direction) %>%  map("gene_id") %>% gost()
ir.ge.als_vs_ctrl.gost.filt <- ir.ge.als_vs_ctrl.gost$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange(-log10(p_value)) %>% 
  mutate(query = case_when(query == "query_1" ~ "IR down\nGE down", query == "query_2" ~ "IR down\nGE up",query == "query_3" ~ "IR up\nGE down", query == "query_4" ~ "IR up\nGE up"), term_name = as.factor(term_name)) 
IRdown.GEup <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE up")
IRup.GEdown <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE down")
IRdown.GEdown <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE down")
IRup.GEup <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE up")
paste('"',unique(IRdown.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup_list <- c(
"Integrin cell surface interactions",
"anchoring junction",
"Protein processing in endoplasmic reticulum",
"cell adhesion molecule binding",
"response to wounding",
"wound healing",
"collagen fibril organization",
"ECM proteoglycans",
"endoplasmic reticulum",
"Collagen formation",
"focal adhesion",
"extracellular matrix organization"
)
paste('"',unique(IRup.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRup.GEdown_list <- c(
"cell projection",
"axon",
"neuron projection")
paste('"',unique(IRdown.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
paste('"',unique(IRup.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup.ac_a1_vs_a0 <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE up")  %>% filter(term_name %in% IRdown.GEup_list)
IRup.GEdown.ac_a1_vs_a0 <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE down")  %>% filter(term_name %in% IRup.GEdown_list)
ir.ge.als_vs_ctrl_filt_combined <- bind_rows(IRdown.GEup.ac_a1_vs_a0, IRup.GEdown.ac_a1_vs_a0) %>% 
  mutate(query = factor(query, levels = c("IR down\nGE up", "IR up\nGE down")))
# ir.ge.als_vs_ctrl_filt_combined$term_name <- gsub("SARS-CoV-2 Innate Immunity Evasion and ", "", ir.ge.als_vs_ctrl_filt_combined$term_name) %>% gsub("Viral protein interaction with cytokine and cytokine receptor", "Viral protein cytokine interaction", .) %>% gsub("Cells and Molecules involved in local ", "", .) %>% gsub("positive regulation of cell-", "", .)
ir.ge.als_vs_ctrl.go_curated <- curated_profiles(gprofiles = ir.ge.als_vs_ctrl_filt_combined) + theme(legend.position = "none")
ir.ge.als_vs_ctrl.go_curated
ggsave(ir.ge.als_vs_ctrl.go_curated, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.als_vs_ctrl.go_curated.png")


ir.ge.als.merged = ggarrange(ir.als_datasets.irfinder.filt.density, irfinder.als_vs_ctrl.sina_plot, ir.ge.als_vs_ctrl.scatter, ir.ge.als_vs_ctrl.go_curated)
ggsave(ir.ge.als.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.als.merged.png")

```

### hiPSC A1

```{r}
### Density 
ir.a1_datasets.irfinder.filt <- ir.a1_datasets$irfinder %>% filter(baseMean > 10, log2FoldChange != 0) %>% drop_na(log2FoldChange) %>% mutate(condition = "A1 vs A0")
mu <- ir.a1_datasets.irfinder.filt %>% summarise(grp.mean=mean(log2FoldChange, na.rm = TRUE)) %>% mutate(condition = "A1 vs A0")
ir.a1_datasets.irfinder.filt.density <- ggplot(ir.a1_datasets.irfinder.filt, aes(x = log2FoldChange, color = condition, fill = condition)) + 
  geom_density(alpha = 0.5) +
  scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8))+
  geom_vline(data = mu, aes(xintercept=grp.mean, color=condition), linetype="dashed") +
  xlab(label = expression(IR~Log[2]~FC~A1:A0) )  + geom_vline(xintercept =0, linetype = 2) +  
  coord_cartesian(xlim=c(-2.5,2.5), ylim=c(0,1.0)) +
  # facet_grid(. ~ condition) + 
  geom_segment(aes(x = 1, xend = 2.5, y= 0.6, yend= 0.6), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  geom_segment(aes(x = -1, xend = -2.5, y= 0.6, yend= 0.6),arrow=arrow(length=unit(0.3,"cm")), color = "black") +
  annotate("text", x = 1.7, y = 0.65, label = "IR increased\nin A1", colour = "black", size = 2.7) +   
  annotate("text", x = -1.7, y =  0.65, label = "IR decreased\nin A1", colour = "black", size = 2.7)
ir.a1_datasets.irfinder.filt.density


### Violin
irfinder.a1_vs_a0.one.sample.stats_test <- ir.a1_datasets.irfinder.filt %>% group_by(condition) %>% wilcox_test(log2FoldChange ~ 1, mu = 0) %>% add_significance()
irfinder.a1_vs_a0.one.sample.stats_test
# condition  .y.            group1 group2         n statistic     p p.signif
# * <chr>      <chr>          <chr>  <chr>      <int>     <dbl> <dbl> <chr>   
# 1 a1 vs CTRL log2FoldChange 1      null model 28777 209248594 0.116 ns    

ir.a1_datasets.irfinder.filt %>% cohens_d(log2FoldChange ~ 1, var.equal = TRUE) # Cohens d effect size indicates direction of effect
# .y.            group1 group2     effsize      n magnitude
# * <chr>          <chr>  <chr>        <dbl>  <int> <ord>    
# 1 log2FoldChange 1      null model  -0.316 101136 small    

# Sina violin plot: one sample stats nuc & cyto IR ratio LFC VCP vs CTRL
irfinder.a1_vs_a0.sina_plot <- ggplot(ir.a1_datasets.irfinder.filt, aes(x = condition, y= log2FoldChange, color = condition)) + 
      geom_violin() + geom_sina(size = 0.5) + geom_boxplot(aes(fill = condition), colour = "black", width=0.2, outlier.shape = NA) +
      scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +  
      theme_classic() + theme(legend.position = "none", axis.text=element_text(size=10), axis.title=element_text(size=10)) +
  coord_cartesian(ylim=c(-2,2)) +  
  geom_hline(yintercept = 0, linetype = 2) + 
  stat_pvalue_manual(irfinder.a1_vs_a0.one.sample.stats_test, label = "p.signif", xmin = "condition", xmax = NULL, y.position = 1.8, hide.ns = FALSE) +
  ylab(label = expression(IR~Log[2]~FC~A1:A0)) + xlab("") +
  geom_segment(aes(x = 1.5, xend = 1.5, y= 0.5, yend= 2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + geom_segment(aes(x = 1.5, xend = 1.5, y= -0.5, yend= -2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  annotate("text", x = 1.3, y = 1.2, label = "IR up in A1", colour = "black", size = 2.7, angle = 90) + annotate("text", x = 1.3, y = -1.2, label = "IR down in A1", colour = "black", size = 2.7, angle = 90)
irfinder.a1_vs_a0.sina_plot


# Scatterplot
ir.ge.a1_vs_a0.scatter <- ggscatter(ir.a1_datasets$ir.ge, x = "IR.log2FoldChange.norm", y = "GE.log2FoldChange", color = "significant", 
                                                      palette = c("firebrick2", "forestgreen", "dodgerblue2", "grey"),
                                            cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = 1, label.y = -3),
          xlab = expression(Intron~Retention~LFC~A1:A0), ylab = expression(Gene~Expression~LFC~A1:A0), size = 0.5) + 
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8), axis.title=element_text(size=10)) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
  coord_cartesian(ylim=c(-4,10), xlim = c(-10,10)) +
  # geom_text_repel(data = filter(ir.a1_datasets$ir.ge, significant == "both", gene_name %in% all.reactivity.go), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
  #                 fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.a1_datasets$ir.ge, significant == "both", gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name, glutamate.uptake.go, lifearc.labels)), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.a1_datasets$ir.ge, significant == "both", abs(IR.log2FoldChange.norm) > 5, abs(GE.log2FoldChange) > 5), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_smooth(data = ir.a1_datasets$ir.ge, aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange), method = "lm", se = F, show.legend = TRUE, colour = "black", linetype = 2)  + 
  annotate(geom="text", x=5, y=-4, label="IR up\nmRNA down", color="darkgrey", size = 2.8)  + annotate(geom="text", x=5, y=10, label="IR up\nmRNA up", color="darkgrey", size = 2.8)  + 
  annotate(geom="text", x=-5, y=10, label="IR down\nmRNA up", color="firebrick2", size = 2.8) +   annotate(geom="text", x=-5, y=-4, label="IR down\nmRNA down", color="darkgrey", size = 2.8)
ir.ge.a1_vs_a0.scatter
ggsave(ir.ge.a1_vs_a0.scatter, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.a1_vs_a0.scatter.png")


### IR & GE GO terms
ir.ge.a1_vs_a0.gost <- ir.a1_datasets$ir.ge %>% filter(GE.pvalue < 0.05, IR.pvalue < 0.05) %>% group_split(direction) %>%  map("gene_id") %>% gost()
ir.ge.a1_vs_a0.gost.filt <- ir.ge.a1_vs_a0.gost$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange(-log10(p_value)) %>% 
  mutate(query = case_when(query == "query_1" ~ "IR down\nGE down", query == "query_2" ~ "IR down\nGE up",query == "query_3" ~ "IR up\nGE down", query == "query_4" ~ "IR up\nGE up"), term_name = as.factor(term_name)) 
IRdown.GEup <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE up")
IRup.GEdown <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE down")
IRdown.GEdown <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE down")
IRup.GEup <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE up")
paste('"',unique(IRdown.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup_list <- c(
"Integrin cell surface interactions",
"anchoring junction",
"Protein processing in endoplasmic reticulum",
"cell adhesion molecule binding",
"response to wounding",
"wound healing",
"collagen fibril organization",
"ECM proteoglycans",
"endoplasmic reticulum",
"Collagen formation",
"focal adhesion",
"extracellular matrix organization"
)
paste('"',unique(IRup.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRup.GEdown_list <- c(
"cell projection",
"axon",
"neuron projection")
paste('"',unique(IRdown.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
paste('"',unique(IRup.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup.ac_a1_vs_a0 <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE up")  %>% filter(term_name %in% IRdown.GEup_list)
IRup.GEdown.ac_a1_vs_a0 <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE down")  %>% filter(term_name %in% IRup.GEdown_list)
ir.ge.a1_vs_a0_filt_combined <- bind_rows(IRdown.GEup.ac_a1_vs_a0, IRup.GEdown.ac_a1_vs_a0) %>% 
  mutate(query = factor(query, levels = c("IR down\nGE up", "IR up\nGE down")))
# ir.ge.a1_vs_a0_filt_combined$term_name <- gsub("SARS-CoV-2 Innate Immunity Evasion and ", "", ir.ge.a1_vs_a0_filt_combined$term_name) %>% gsub("Viral protein interaction with cytokine and cytokine receptor", "Viral protein cytokine interaction", .) %>% gsub("Cells and Molecules involved in local ", "", .) %>% gsub("positive regulation of cell-", "", .)
ir.ge.a1_vs_a0.go_curated <- curated_profiles(gprofiles = ir.ge.a1_vs_a0_filt_combined) + theme(legend.position = "none")
ir.ge.a1_vs_a0.go_curated
ggsave(ir.ge.a1_vs_a0.go_curated, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.a1_vs_a0.go_curated.png")


ir.ge.a1.merged = ggarrange(ir.a1_datasets.irfinder.filt.density, irfinder.a1_vs_a0.sina_plot, ir.ge.a1_vs_a0.scatter, ir.ge.a1_vs_a0.go_curated)
ggsave(ir.ge.a1.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-a1-meta/splicing/irfinder/figures/ir.ge.a1.merged.png")

```


### Mouse ALS


```{r}
### Density 
ir.mouse_als_datasets.irfinder.filt <- ir.mouse_als_datasets$irfinder %>% filter(baseMean > 10, log2FoldChange != 0) %>% drop_na(log2FoldChange) %>% mutate(condition = "ALS vs CTRL")
mu <- ir.mouse_als_datasets.irfinder.filt %>% summarise(grp.mean=mean(log2FoldChange, na.rm = TRUE)) %>% mutate(condition = "ALS vs CTRL")
ir.mouse_als_datasets.irfinder.filt.density <- ggplot(ir.mouse_als_datasets.irfinder.filt, aes(x = log2FoldChange, color = condition, fill = condition)) + 
  geom_density(alpha = 0.5) +
  scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8))+
  geom_vline(data = mu, aes(xintercept=grp.mean, color=condition), linetype="dashed") +
  xlab(label = expression(IR~Log[2]~FC~ALS:CTRL) )  + geom_vline(xintercept =0, linetype = 2) +  
  coord_cartesian(xlim=c(-2.5,2.5), ylim=c(0,1.0)) +
  # facet_grid(. ~ condition) + 
  geom_segment(aes(x = 1, xend = 2.5, y= 0.6, yend= 0.6), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  geom_segment(aes(x = -1, xend = -2.5, y= 0.6, yend= 0.6),arrow=arrow(length=unit(0.3,"cm")), color = "black") +
  annotate("text", x = 1.7, y = 0.65, label = "IR increased\nin ALS", colour = "black", size = 2.7) +   
  annotate("text", x = -1.7, y =  0.65, label = "IR decreased\nin ALS", colour = "black", size = 2.7)
ir.mouse_als_datasets.irfinder.filt.density


### Violin
irfinder.als_vs_ctrl.one.sample.stats_test <- ir.mouse_als_datasets.irfinder.filt %>% group_by(condition) %>% wilcox_test(log2FoldChange ~ 1, mu = 0) %>% add_significance()
irfinder.als_vs_ctrl.one.sample.stats_test
# condition   .y.            group1 group2         n  statistic     p p.signif
# * <chr>       <chr>          <chr>  <chr>      <int>      <dbl> <dbl> <chr>   
# 1 ALS vs CTRL log2FoldChange 1      null model 96336 1153457212     0 ****

ir.mouse_als_datasets.irfinder.filt %>% cohens_d(log2FoldChange ~ 1, var.equal = TRUE) # Cohens d effect size indicates direction of effect
# .y.            group1 group2     effsize      n magnitude
# * <chr>          <chr>  <chr>        <dbl>  <int> <ord>    
# 1 log2FoldChange 1      null model  -0.316 101136 small    

# Sina violin plot: one sample stats nuc & cyto IR ratio LFC VCP vs CTRL
irfinder.als_vs_ctrl.sina_plot <- ggplot(ir.mouse_als_datasets.irfinder.filt, aes(x = condition, y= log2FoldChange, color = condition)) + 
      geom_violin() + geom_sina(size = 0.5) + geom_boxplot(aes(fill = condition), colour = "black", width=0.2, outlier.shape = NA) +
      scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +  
      theme_classic() + theme(legend.position = "none", axis.text=element_text(size=10), axis.title=element_text(size=10)) +
  coord_cartesian(ylim=c(-2,2)) +  
  geom_hline(yintercept = 0, linetype = 2) + 
  stat_pvalue_manual(irfinder.als_vs_ctrl.one.sample.stats_test, label = "p.signif", xmin = "condition", xmax = NULL, y.position = 1.8, hide.ns = FALSE) +
  ylab(label = expression(IR~Log[2]~FC~ALS:CTRL)) + xlab("") +
  geom_segment(aes(x = 1.5, xend = 1.5, y= 0.5, yend= 2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + geom_segment(aes(x = 1.5, xend = 1.5, y= -0.5, yend= -2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  annotate("text", x = 1.3, y = 1.2, label = "IR up in ALS", colour = "black", size = 2.7, angle = 90) + annotate("text", x = 1.3, y = -1.2, label = "IR down in ALS", colour = "black", size = 2.7, angle = 90)
irfinder.als_vs_ctrl.sina_plot


# Scatterplot
lifearc.labels = c("PLOD3", "MCAM", "CHERP", "ERAP2", "FN1", "ILK", "OSMR", "FLNA", "MRC2", "ACTN4", "C3")

mouse.ir.ge.als_vs_ctrl.scatter <- ggscatter(ir.mouse_als_datasets$ir.ge, x = "IR.log2FoldChange.norm", y = "GE.log2FoldChange", color = "significant", 
                                                      palette = c("firebrick2", "forestgreen", "dodgerblue2", "grey"),
                                            cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = 0, label.y = 1.7),
          xlab = expression(Intron~Retention~LFC~mouse~ALS:CTRL), ylab = expression(Gene~Expression~LFC~mouse~ALS:CTRL), size = 0.5) + 
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8), axis.title=element_text(size=10)) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
  coord_cartesian(ylim=c(-1,2), xlim = c(-2,1)) +
  # geom_text_repel(data = filter(ir.mouse_als_datasets$ir.ge, significant == "both", gene_name %in% all.reactivity.go), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
  #                 fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.mouse_als_datasets$ir.ge, significant == "both", gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name, glutamate.uptake.go, lifearc.labels)), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.mouse_als_datasets$ir.ge, significant == "both", abs(IR.log2FoldChange.norm) > 0.8, abs(GE.log2FoldChange) > 0.8), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_smooth(data = ir.mouse_als_datasets$ir.ge, aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange), method = "lm", se = F, show.legend = TRUE, colour = "black", linetype = 2)  + 
  annotate(geom="text", x=0.5, y=-1, label="IR up\nmRNA down", color="darkgrey", size = 2.8)  + annotate(geom="text", x=0.5, y=2, label="IR up\nmRNA up", color="darkgrey", size = 2.8)  + 
  annotate(geom="text", x=-1, y=2, label="IR down\nmRNA up", color="firebrick2", size = 2.8) +   annotate(geom="text", x=-1, y=-1, label="IR down\nmRNA down", color="darkgrey", size = 2.8)
mouse.ir.ge.als_vs_ctrl.scatter
ggsave(mouse.ir.ge.als_vs_ctrl.scatter, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/mouse.ir.ge.als_vs_ctrl.scatter.png")


### IR & GE GO terms
ir.ge.als_vs_ctrl.gost <- ir.mouse_als_datasets$ir.ge %>% filter(GE.pvalue < 0.05, IR.pvalue < 0.05) %>% group_split(direction) %>%  map("gene_id") %>% gost(organism = "mmusculus")
ir.ge.als_vs_ctrl.gost.filt <- ir.ge.als_vs_ctrl.gost$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange(-log10(p_value)) %>% 
  mutate(query = case_when(query == "query_1" ~ "IR down\nGE down", query == "query_2" ~ "IR down\nGE up",query == "query_3" ~ "IR up\nGE down", query == "query_4" ~ "IR up\nGE up"), term_name = as.factor(term_name)) 
IRdown.GEup <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE up")
IRup.GEdown <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE down")
IRdown.GEdown <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE down")
IRup.GEup <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE up")
paste('"',unique(IRdown.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup_list <- c(
# "L-leucine transmembrane transporter activity",
# "fibroblast growth factor-activated receptor activity",
"mitochondrial envelope",
"neuronal cell body",
# "organelle envelope",
# "envelope",
"mitochondrial inner membrane",
# "kininogen binding",
# "vacuole",
"mitochondrial membrane",
# "proton transmembrane transporter activity",
# "phenylalanine transport",
# "perikaryon",
# "lysosome",
# "lytic vacuole",
"Lysosome",
"amino acid transport complex",
"cytoplasm",
"mitochondrion"
)
paste('"',unique(IRup.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
paste('"',unique(IRdown.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
paste('"',unique(IRup.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup.ac_a1_vs_a0 <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR down\nGE up")  %>% filter(term_name %in% IRdown.GEup_list)
IRup.GEdown.ac_a1_vs_a0 <- ir.ge.als_vs_ctrl.gost.filt %>% filter(query == "IR up\nGE down")  %>% filter(term_name %in% IRup.GEdown_list)
# ir.ge.als_vs_ctrl_filt_combined$term_name <- gsub("SARS-CoV-2 Innate Immunity Evasion and ", "", ir.ge.als_vs_ctrl_filt_combined$term_name) %>% gsub("Viral protein interaction with cytokine and cytokine receptor", "Viral protein cytokine interaction", .) %>% gsub("Cells and Molecules involved in local ", "", .) %>% gsub("positive regulation of cell-", "", .)
ir.ge.als_vs_ctrl.go_curated <- curated_profiles(gprofiles = IRdown.GEup.ac_a1_vs_a0) + theme(legend.position = "none")
ir.ge.als_vs_ctrl.go_curated
ggsave(ir.ge.als_vs_ctrl.go_curated, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.als_vs_ctrl.go_curated.png")


mouse.ir.ge.als.merged = ggarrange(ir.mouse_als_datasets.irfinder.filt.density, irfinder.als_vs_ctrl.sina_plot, ir.ge.als_vs_ctrl.scatter, ir.ge.als_vs_ctrl.go_curated)
ggsave(ir.ge.als.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.als.merged.png")

```


### Mouse A1

```{r}
### Density 
ir.guttenplan.A1.irfinder.filt <- ir.guttenplan.A1$irfinder %>% filter(baseMean > 10, log2FoldChange != 0) %>% drop_na(log2FoldChange) %>% mutate(condition = "A1 vs A0")
mu <- ir.guttenplan.A1.irfinder.filt %>% summarise(grp.mean=mean(log2FoldChange, na.rm = TRUE)) %>% mutate(condition = "A1 vs A0")
ir.guttenplan.A1.irfinder.filt.density <- ggplot(ir.guttenplan.A1.irfinder.filt, aes(x = log2FoldChange, color = condition, fill = condition)) + 
  geom_density(alpha = 0.5) +
  scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8))+
  geom_vline(data = mu, aes(xintercept=grp.mean, color=condition), linetype="dashed") +
  xlab(label = expression(IR~Log[2]~FC~A1:A0) )  + geom_vline(xintercept =0, linetype = 2) +  
  coord_cartesian(xlim=c(-2.5,2.5), ylim=c(0,1.0)) +
  # facet_grid(. ~ condition) + 
  geom_segment(aes(x = 1, xend = 2.5, y= 0.6, yend= 0.6), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  geom_segment(aes(x = -1, xend = -2.5, y= 0.6, yend= 0.6),arrow=arrow(length=unit(0.3,"cm")), color = "black") +
  annotate("text", x = 1.7, y = 0.65, label = "IR increased\nin A1", colour = "black", size = 2.7) +   
  annotate("text", x = -1.7, y =  0.65, label = "IR decreased\nin A1", colour = "black", size = 2.7)
ir.guttenplan.A1.irfinder.filt.density


### Violin
irfinder.a1_vs_a0.one.sample.stats_test <- ir.guttenplan.A1.irfinder.filt %>% group_by(condition) %>% wilcox_test(log2FoldChange ~ 1, mu = 0) %>% add_significance()
irfinder.a1_vs_a0.one.sample.stats_test
# condition  .y.            group1 group2         n statistic     p p.signif
# * <chr>      <chr>          <chr>  <chr>      <int>     <dbl> <dbl> <chr>   
# 1 a1 vs CTRL log2FoldChange 1      null model 28777 209248594 0.116 ns    

ir.guttenplan.A1.irfinder.filt %>% cohens_d(log2FoldChange ~ 1, var.equal = TRUE) # Cohens d effect size indicates direction of effect
# .y.            group1 group2     effsize      n magnitude
# * <chr>          <chr>  <chr>        <dbl>  <int> <ord>    
# 1 log2FoldChange 1      null model  -0.316 101136 small    

# Sina violin plot: one sample stats nuc & cyto IR ratio LFC VCP vs CTRL
irfinder.a1_vs_a0.sina_plot <- ggplot(ir.guttenplan.A1.irfinder.filt, aes(x = condition, y= log2FoldChange, color = condition)) + 
      geom_violin() + geom_sina(size = 0.5) + geom_boxplot(aes(fill = condition), colour = "black", width=0.2, outlier.shape = NA) +
      scale_colour_manual(values = c("dodgerblue2", "firebrick2")) + scale_fill_manual(values = c("dodgerblue2", "firebrick2")) +  
      theme_classic() + theme(legend.position = "none", axis.text=element_text(size=10), axis.title=element_text(size=10)) +
  coord_cartesian(ylim=c(-2,2)) +  
  geom_hline(yintercept = 0, linetype = 2) + 
  stat_pvalue_manual(irfinder.a1_vs_a0.one.sample.stats_test, label = "p.signif", xmin = "condition", xmax = NULL, y.position = 1.8, hide.ns = FALSE) +
  ylab(label = expression(IR~Log[2]~FC~A1:A0)) + xlab("") +
  geom_segment(aes(x = 1.5, xend = 1.5, y= 0.5, yend= 2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + geom_segment(aes(x = 1.5, xend = 1.5, y= -0.5, yend= -2), arrow=arrow(length=unit(0.3,"cm")), color = "black") + 
  annotate("text", x = 1.3, y = 1.2, label = "IR up in A1", colour = "black", size = 2.7, angle = 90) + annotate("text", x = 1.3, y = -1.2, label = "IR down in A1", colour = "black", size = 2.7, angle = 90)
irfinder.a1_vs_a0.sina_plot


# Scatterplot
mouse.ir.ge.a1_vs_a0.scatter <- ggscatter(ir.guttenplan.A1$ir.ge, x = "IR.log2FoldChange.norm", y = "GE.log2FoldChange", color = "significant", 
                                                      palette = c("firebrick2", "forestgreen", "dodgerblue2", "grey"),
                                            cor.coef = TRUE, cor.coeff.args = list(method = "pearson", label.x = 1, label.y = -2.5),
          xlab = expression(Intron~Retention~LFC~mouse~A1:A0), ylab = expression(Gene~Expression~LFC~mouse~A1:A0), size = 0.5) + 
  theme_classic() + theme(legend.position = "none", axis.text=element_text(size=8), axis.title=element_text(size=10)) +
  geom_hline(yintercept = 0, linetype = 3, colour = "darkgrey") + geom_vline(xintercept = 0, linetype = 3, colour = "darkgrey") + 
  coord_cartesian(ylim=c(-3,7), xlim = c(-4,4)) +
  # geom_text_repel(data = filter(ir.guttenplan.A1$ir.ge, significant == "both", gene_name %in% all.reactivity.go), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
  #                 fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  # geom_text_repel(data = filter(ir.guttenplan.A1$ir.ge, significant == "both", gene_name %in% c(astrocyte.reactive.genes, escartin.markers$gene_name, glutamate.uptake.go, lifearc.labels)), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  # fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_text_repel(data = filter(ir.guttenplan.A1$ir.ge, significant == "both", abs(IR.log2FoldChange.norm) > 1, abs(GE.log2FoldChange) > 1), aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange, label = gene_name),
                  fontface = "italic", colour = "black", min.segment.length = 0, box.padding = 0.5, point.padding = 0.5, size = 2.8, max.overlaps = Inf) +
  geom_smooth(data = ir.guttenplan.A1$ir.ge, aes(x = IR.log2FoldChange.norm, y = GE.log2FoldChange), method = "lm", se = F, show.legend = TRUE, colour = "black", linetype = 2)  + 
  annotate(geom="text", x=2, y=-3, label="IR up\nmRNA down", color="darkgrey", size = 2.8)  + annotate(geom="text", x=2, y=7, label="IR up\nmRNA up", color="darkgrey", size = 2.8)  + 
  annotate(geom="text", x=-2, y=7, label="IR down\nmRNA up", color="firebrick2", size = 2.8) +   annotate(geom="text", x=-2, y=-3, label="IR down\nmRNA down", color="darkgrey", size = 2.8)
mouse.ir.ge.a1_vs_a0.scatter
ggsave(mouse.ir.ge.a1_vs_a0.scatter, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/mouse.ir.ge.a1_vs_a0.scatter.png")


### IR & GE GO terms
ir.ge.a1_vs_a0.gost <- ir.guttenplan.A1$ir.ge %>% filter(GE.pvalue < 0.05, IR.pvalue < 0.05) %>% group_split(direction) %>%  map("gene_id") %>% gost()
ir.ge.a1_vs_a0.gost.filt <- ir.ge.a1_vs_a0.gost$result %>% filter(!str_detect(source, "TF|CORUM")) %>% arrange(-log10(p_value)) %>% 
  mutate(query = case_when(query == "query_1" ~ "IR down\nGE down", query == "query_2" ~ "IR down\nGE up",query == "query_3" ~ "IR up\nGE down", query == "query_4" ~ "IR up\nGE up"), term_name = as.factor(term_name)) 
IRdown.GEup <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE up")
IRup.GEdown <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE down")
IRdown.GEdown <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE down")
IRup.GEup <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE up")
paste('"',unique(IRdown.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup_list <- c(
"Integrin cell surface interactions",
"anchoring junction",
"Protein processing in endoplasmic reticulum",
"cell adhesion molecule binding",
"response to wounding",
"wound healing",
"collagen fibril organization",
"ECM proteoglycans",
"endoplasmic reticulum",
"Collagen formation",
"focal adhesion",
"extracellular matrix organization"
)
paste('"',unique(IRup.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRup.GEdown_list <- c(
"cell projection",
"axon",
"neuron projection")
paste('"',unique(IRdown.GEdown$term_name),'",', sep = "", collapse = '\n') %>% cat()
paste('"',unique(IRup.GEup$term_name),'",', sep = "", collapse = '\n') %>% cat()
IRdown.GEup.ac_a1_vs_a0 <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR down\nGE up")  %>% filter(term_name %in% IRdown.GEup_list)
IRup.GEdown.ac_a1_vs_a0 <- ir.ge.a1_vs_a0.gost.filt %>% filter(query == "IR up\nGE down")  %>% filter(term_name %in% IRup.GEdown_list)
ir.ge.a1_vs_a0_filt_combined <- bind_rows(IRdown.GEup.ac_a1_vs_a0, IRup.GEdown.ac_a1_vs_a0) %>% 
  mutate(query = factor(query, levels = c("IR down\nGE up", "IR up\nGE down")))
# ir.ge.a1_vs_a0_filt_combined$term_name <- gsub("SARS-CoV-2 Innate Immunity Evasion and ", "", ir.ge.a1_vs_a0_filt_combined$term_name) %>% gsub("Viral protein interaction with cytokine and cytokine receptor", "Viral protein cytokine interaction", .) %>% gsub("Cells and Molecules involved in local ", "", .) %>% gsub("positive regulation of cell-", "", .)
ir.ge.a1_vs_a0.go_curated <- curated_profiles(gprofiles = ir.ge.a1_vs_a0_filt_combined) + theme(legend.position = "none")
ir.ge.a1_vs_a0.go_curated
ggsave(ir.ge.a1_vs_a0.go_curated, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-als-meta/splicing/irfinder/figures/ir.ge.a1_vs_a0.go_curated.png")


ir.ge.a1.merged = ggarrange(ir.guttenplan.A1.irfinder.filt.density, irfinder.a1_vs_a0.sina_plot, ir.ge.a1_vs_a0.scatter, ir.ge.a1_vs_a0.go_curated)
ggsave(ir.ge.a1.merged, filename = "/camp/home/ziffo/home/projects/astrocyte-a1-a1-meta/splicing/irfinder/figures/ir.ge.a1.merged.png")

```
