Luise-Seeker-Human-WM-Glia / src / 42_vascular_cells.Rmd
42_vascular_cells.Rmd
Raw
---
title: "HCA vascular cells"
author: "Luise A. Seeker"
date: "03/09/2021"
output: html_document
---

```{r}
library(Seurat)
library(here)
library(ggsci)
library(dplyr)
library(future)
#library(scclusteval)
library(clustree)
library(tidyr)
library(SCINA)
library(scSorter)
library(msigdbr)
library(fgsea)
library(tibble)

```

```{r, echo = F}
mypal <- pal_npg("nrc", alpha = 0.7)(10)
mypal2 <-pal_tron("legacy", alpha = 0.7)(7)
mypal3 <- pal_lancet("lanonc", alpha = 0.7)(9)
mypal4 <- pal_simpsons(palette = c("springfield"), alpha = 0.7)(16)
mypal5 <- pal_rickandmorty(palette = c("schwifty"), alpha = 0.7)(6)
mypal6 <- pal_futurama(palette = c("planetexpress"), alpha = 0.7)(5)
mypal7 <- pal_startrek(palette = c("uniform"), alpha = 0.7)(5)

mycoloursP<- c(mypal, mypal2, mypal3, mypal4, mypal5, mypal6, mypal7)

```

```{r}
e <- 40000 * 1024^2
options(future.globals.maxSize = e)

```

```{r}
seur_comb <- readRDS(here("data", 
                          "single_nuc_data", 
                          "all_cell_types",
                          "srt_anno_01.RDS"))



```


```{r}
DimPlot(seur_comb, cols = mycoloursP, label = TRUE) + NoLegend()

```

```{r}
Idents(seur_comb) <- "clusters_named"
  seur_comb <-  RenameIdents(
    seur_comb,
    "Oligo" = "Oligodendroglia", 
    "Neuron_RELN+_1" = "Neurons",
    "Astrocyte_1" = "Astrocytes", 
    "Microglia-Macrophages_1" = "Immune Cells", 
    "Endothelial-Pericyte_1" = "EC_PC",
    "Endothelial-Pericyte_2" = "EC_PC",
    "OPC"  = "Oligodendroglia", 
    "Microglia-Macrophages_2"= "Immune Cells",
    "Neuron_In_1" = "Neurons",
    "Neuron_RELN+_2" = "Neurons",
    "Neuron_In_2" = "Neurons",
    "Neuron_Ex_1" = "Neurons", 
    "Neuron_Ex_2" = "Neurons", 
    "Neuron_RELN+_3" = "Neurons", 
    "Astrocyte_2" = "Astrocytes", 
    "Neuron_In_3" = "Neurons", 
    "Immune" = "Immune Cells", 
    "Neuron_Ex_3" = "Neurons", 
    "Stromal_1" = "Stromal cells", 
    "Stromal_2"  = "Stromal cells", 
    "Astrocyte_3" = "Astrocytes", 
    "Neuron_In_4" = "Neurons",
    "Astrocyte_4"  = "Astrocytes")  

DimPlot(seur_comb, cols = mycoloursP, label = TRUE) + NoLegend()    
DimPlot(seur_comb, cols = mycoloursP[10:50], label = FALSE) + NoLegend()
```

```{r}
Idents(seur_comb) <- "clusters_named"
vasc_srt <- subset(seur_comb, idents = c("Endothelial-Pericyte_1",
                                          "Endothelial-Pericyte_2",
                                          "Stromal_1",
                                          "Stromal_2"))
```


```{r}

vasc_srt <- FindVariableFeatures(vasc_srt, 
                               selection.method = "vst", 
                               nfeatures = 2000)
all_genes <- rownames(vasc_srt)
vasc_srt <- ScaleData(vasc_srt, features= all_genes)

vasc_srt <- RunPCA(vasc_srt, features = VariableFeatures(object = vasc_srt))
ElbowPlot(vasc_srt)




```


```{r}

vasc_srt <- FindNeighbors(vasc_srt, dims = 1:10)

# test different resolutions for clustering
vasc_srt <- FindClusters(vasc_srt, resolution = 0.7)


# non-linear reduction
vasc_srt <- RunUMAP(vasc_srt, dims = 1:10)

DimPlot(vasc_srt, cols = mycoloursP[18:40], label = TRUE) + NoLegend()
```





```{r}
vasc_srt <- FindClusters(vasc_srt, resolution = c(0.01, 0.04, 0.05, 
                                              seq(from = 0.1, to = 1.5, by = 0.1)))


#Generate DimPlot of all tested clustering resolutions in metadata
# requires gtools library and Seurat
plot_list_func <- function(seur_obj,
                           col_pattern, 
                           plot_cols, 
                           clust_lab = TRUE,
                           label_size = 8,
                           num_col = 4,
                           save_dir = getwd(),
                           width=7,
                           height=5){
  extr_res_col <- grep(pattern = col_pattern, names(seur_obj@meta.data))
  res_names <- names(seur_obj@meta.data[extr_res_col])
  # gtools function, sorts gene_names alphanumeric:
  res_names <- gtools::mixedsort(res_names) 
  plot_l <-list()
  for(i in 1: length(res_names)){
  pdf(paste0(save_dir, "/",
               res_names[i], "_umap.pdf"), width=width, height=height)
  dim_plot <- DimPlot(seur_obj, 
                          reduction = "umap", 
                          cols= plot_cols,
                          group.by = res_names[i],
                          label = clust_lab,
                          label.size = label_size) + NoLegend()
  print(dim_plot)
  dev.off()
  print(dim_plot)
  }
}


save_dir_vasc <- here("outs",
                       "vascular_cells",
                       "cluster_resolutions")
dir.create(save_dir_vasc, recursive = TRUE)

plot_list_func(seur_obj = vasc_srt, 
               col_pattern = "RNA_snn_res.",
               plot_cols = mycoloursP[18:50],
               save_dir = save_dir_vasc)

```

```{r, fig.with = 10, fig.height = 4}
DimPlot(vasc_srt, 
        cols = mycoloursP[10:50], 
        label = TRUE,
        group.by = "RNA_snn_res.0.3",
        split.by = "Tissue") + NoLegend()

```

```{r, fig.width = 10, fig.hight = 4}
DimPlot(vasc_srt, 
        cols = mycoloursP[18:40], 
        label = TRUE,
        group.by = "RNA_snn_res.0.3",
        split.by = "AgeGroup") + NoLegend()

```

```{r, fig.width = 10, fig.hight = 4}
DimPlot(vasc_srt, 
        cols = mycoloursP[18:40], 
        label = TRUE,
        group.by = "RNA_snn_res.0.3",
        split.by = "gender") + NoLegend()

```


```{r, fig.width = 6, fig.height = 12}
DimPlot(vasc_srt, 
        cols = mycoloursP[18:40], 
        label = TRUE,
        group.by = "RNA_snn_res.0.3",
        split.by = "caseNO",
        ncol = 3) + NoLegend()

```

```{r, fig.width = 10, fig.height=20}

pdf(here(save_dir_vasc, "vascular_cells_clustree.pdf"), 
    paper="a4", width=8, height=11.5)
clustree(
  vasc_srt,
  prefix = paste0("RNA", "_snn_res."),
  exprs = c("data", "counts", "scale.data"),
  assay = NULL
)

dev.off()


clustree(
  vasc_srt,
  prefix = paste0("RNA", "_snn_res."),
  exprs = c("data", "counts", "scale.data"),
  assay = NULL
)

```

# Deciding for the a clustering resolution

I looked for variable genes between all markers and pairwise at resolution 
0.7, filtered the markers and plotted them in a heat map. I did have a look at
the cluster QC below at that resolution as well which looked fine. 
```{r}
Idents(vasc_srt) <- "RNA_snn_res.0.3"
  vasc_srt <-  RenameIdents(
    vasc_srt,
    "0" = "EC_cap_1",
    "1" = "PC_cap_1",
    "2" = "M_AV_1",
    "3" = "EC_cap_2",
    "4" = "PC_cap_2",
    "5" = "EC_AV_2",
    "6" = "EC_AV_1",
    "7" = "vSMC",
    "8" = "EC_AV_3",
    "9" = "EC_cap_5",
    "10" = "EC_cap_3",
    "11" = "EC_cap_4")
  
# Plot result
DimPlot(vasc_srt,label = TRUE, repel=TRUE)

DimPlot(vasc_srt,label = TRUE, repel=TRUE, cols = mycoloursP[35:50],
                  label.size = 4.5)+ NoLegend()

# Save result
vasc_srt$vascular_cells_clu <- Idents(vasc_srt)

```

```{r}
DimPlot(vasc_srt,label = FALSE, repel=TRUE, cols = mycoloursP[31:50],
                  label.size = 4.5)+ NoLegend()

```

Find markers for all interesting resolutions
```{r}
int_res_all_mark <- function(seur_obj, 
                             int_cols,
                             only_pos = TRUE,
                             min_pct = 0.25,
                             logfc_threshold = 0.25,
                             fil_pct_1 = 0.25,
                             fil_pct_2 = 0.6,
                             avg_log = 1.2,
                             save_dir = getwd(),
                             test_use = "MAST"
                             ){
  for(i in 1:length(int_cols)){
    Idents(seur_obj) <- int_cols[i]
    all_mark <- FindAllMarkers(seur_obj, 
                               only.pos = only_pos, 
                               min.pct = min_pct, 
                               logfc.threshold = logfc_threshold,
                               test.use = test_use)
    fil_mark<- subset(all_mark, 
                      all_mark$pct.1 > fil_pct_1 & 
                        all_mark$pct.2 < fil_pct_2 )
    
    write.csv(all_mark, paste(save_dir, "/all_mark", int_cols[i], ".csv", sep = "" ))
    write.csv(fil_mark, paste(save_dir, "/fil_mark", int_cols[i], ".csv", sep = "" ))
    
  }
}

```


```{r}

save_dir_vasc <- here("outs",
                       "vascular_cells",
                       "cluster_marker_lists")
```


```{r, eval = FALSE}


dir.create(save_dir_vasc, recursive = TRUE)



int_res_all_mark(vasc_srt, 
                 int_cols = c("RNA_snn_res.0.01",
                              "RNA_snn_res.0.04",
                              "RNA_snn_res.0.05",
                              "RNA_snn_res.0.1",
                              "RNA_snn_res.0.2",
                              "RNA_snn_res.0.3",
                              "RNA_snn_res.0.4",
                              "vascular_cells_clu"),
                 save_dir = save_dir_vasc)





```


```{r}

Idents(vasc_srt) <-"vascular_cells_clu"

all_mark <- FindAllMarkers(vasc_srt, only.pos = TRUE, 
                               min.pct = 0.25, 
                               logfc.threshold = 0.25,
                               test.use = "MAST")

write.csv(all_mark, here(save_dir_vasc, "vasc_cells_all_mark.csv"))


```

# Pairwise cluster comparison for markers

```{r, eval = FALSE}


Idents(vasc_srt) <- "vascular_cells_clu"

clust_id_list_2 <- list(list("EC_1", "EC_2"), list("EC_2", "EC_1"), 
                      list("EC_1", "EC_3"), list("EC_3", "EC_1"),
                      list("EC_3", "ST_2"), list("ST_2", "EC_3"), 
                      list("ST_2", "ST_3"), list("ST_3", "ST_2"),
                      list("EC_2", "EC_6"), list("EC_6", "EC_2"), 
                      list("EC_2", "EC_5"), list("EC_5", "EC_2"),
                      list("EC_5", "EC_6"), list("EC_6", "EC_5"),
                      list("PC_1", "PC_2"), list("PC_2", "PC_1"),
                      list("PC_1", "PC_3"), list("PC_3", "PC_1"),
                      list("PC_3", "ST_1"), list("ST_1", "PC_3"),
                      list("EC_4", "ST_1"), list("ST_1", "EC_4"),
                      list("EC_4", "EC_6"), list("EC_6", "EC_4"),
                      list("EC_4", "ST_3"), list("ST_3", "EC_4"),
                      list("EC_4", "ST_2"), list("ST_2", "EC_4"))

```





```{r}

pairwise_mark <- function(seur_obj, 
                             int_cols,
                             clust_id_list,
                             only_pos = TRUE,
                             min_pct = 0.25,
                             logfc_threshold = 0.25,
                             fil_pct_1 = 0.25,
                             fil_pct_2 = 0.1,
                             save_dir = getwd(),
                             test_use = "MAST"){
  for(k in 1:length(int_cols)){
    Idents(seur_obj) <- int_cols[k]
    for(i in 1: length(clust_id_list)){
      clust_mark <- FindMarkers(seur_obj, 
                                ident.1 = clust_id_list[[i]][[1]], 
                                ident.2 = clust_id_list[[i]][[2]],
                                min.pct = min_pct, 
                                test.use = test_use)
      clust_mark$cluster <- clust_id_list[[i]][[1]]
      clust_mark$comp_to_clust <- clust_id_list[[i]][[2]]
      write.csv(clust_mark, 
                paste(save_dir, 
                      "/", 
                      int_cols[k],
                      "_",
                      clust_id_list[[i]][[1]],
                      "_",
                      clust_id_list[[i]][[2]],
                      ".csv", sep = "" ))
    }
  }
}



save_dir_vasc_pw <- here("outs",
                       "vascular_cells",
                       "pairwise_cluster_marker_lists")



```

```{r, eval = FALSE}

dir.create(save_dir_vasc_pw, recursive = TRUE)


pairwise_mark(vasc_srt, 
              int_cols = "vascular_cells_clu",
              save_dir = save_dir_vasc_pw,
              clust_id_list = clust_id_list_2)

```

Read in data for plotting differentially expressed genes
```{r}

gen_mark_list <-function(file_dir = getwd(),
                         avg_log = 1.2,
                         pct_1 = 0.25,
                         pct_2 = 0.6,
                         pairwise = FALSE
                         ){
  temp = list.files(path = file_dir,
                    pattern="*.csv")
  myfiles = lapply(paste(file_dir, temp, sep = "/"), read.csv)
  
  for(i in 1:length(myfiles)){
    dat <- myfiles[[i]]
    av_log_fil <- subset(dat, dat$avg_log2FC > avg_log & 
                       dat$pct.1 > pct_1 & 
                       dat$pct.2 < pct_2)
    if(pairwise == TRUE){
      
      top10 <- av_log_fil %>% top_n(10, avg_log2FC)
      top10$gene <- top10$X
    }else{
    av_log_fil$cluster <- as.character(av_log_fil$cluster)
    top10 <- av_log_fil %>% group_by(cluster) %>% 
      top_n(10, avg_log2FC)
    }
    
    if(i ==1){
      fil_genes <- top10
    }else{
      fil_genes <- rbind(fil_genes, top10)
    }
    
    fil_genes <- fil_genes[!duplicated(fil_genes$gene),]
    
  }
  
  return(fil_genes)
}


fil_genes <- gen_mark_list(file_dir = save_dir_vasc)

fil_genes_pw <- gen_mark_list(file_dir = save_dir_vasc_pw,
                              pairwise = TRUE)

int_genes <- c(fil_genes$gene, fil_genes_pw$gene)
int_genes <- unique(int_genes)




```

```{r, fig.height = 25, fig.width=10}
# every cell name



Idents(vasc_srt) <- "vascular_cells_clu"

cluster_averages <- AverageExpression(vasc_srt, 
                                      group.by = "vascular_cells_clu",
                                      return.seurat = TRUE)


cluster_averages@meta.data$cluster <- levels(as.factor(vasc_srt@meta.data$vascular_cells_clu))
order <- c(38, 37, 40, 
           32,33, 42, 43, 41, 
           33, 36, 34,
           39)
hm_av <- DoHeatmap(object = cluster_averages, 
          features = int_genes, 
          label = TRUE,
          group.by = "cluster",
          group.colors = mycoloursP[order],
          draw.lines = F)

hm_av
```

```{r}

save_dir <- here("outs", "vascular_cells", "cluster_heatmap")
dir.create(save_dir)
png(here("outs", "vascular_cells", "cluster_heatmap", "cluster_hm_vasc.png"), 
    width=600, height=2300)
print(hm_av)
dev.off()

```

```{r}
pdf(here("outs", "vascular_cells", "cluster_heatmap", "cluster_hm_vasc.pdf"), 
    width=8, height=16)
print(hm_av)
dev.off()

```

```{r}
setEPS()
postscript(here("outs", 
                "vascular_cells", 
                "cluster_heatmap", 
                "cluster_hm_vasc.eps"))
plot(hm_av)
dev.off()

```


# Plot cluster markers

## 
```{r}

#, fig.width=10, fig.height=20}
FeaturePlot(vasc_srt, features = c(
  "CLDN5"))

```



=

```{r, fig.height = 25, fig.width = 12}
FeaturePlot(vasc_srt,
            features =c(
              "PVALB",
              "GPC5",
              "CSMD3",
              "SCG2",
              "PEG3",
              "NEFH",
              "NEFM",
              "VAMP1",
              "PVALB",
              "NXPH1",
              "GAD1",
              "GRIK1",
              "SPOCK3",
              "ADARB2",
              "CXCL14",
              "PRELID2",
              "FOXP2",
              "CALB1",
              "CALB2",
              "RPL11",
              "FBXL7",
              "INPP4B",
              "CLMP",
              "AL589740.1",
              "AC120193.1",
              "FHIT",
              "C1QL1",
              "GPR88",
              "TIAM1",
              "FSTL5",
              "RPL3",
              "MBP",
              "PLP1",
              "MOBP"
            ),
            ncol = 3)

```


```{r, fig.height = 12, fig.width = 12}
FeaturePlot(seur_comb,
            features =c(
              "NRXN3",
              "AQP1",
              "BHLHE40",
              "HSPB1",
              "CCDC85A",
              "APLNR",
              "TTN",
              "PLEKHA5",
              "RNF19A",
              "AEBP1",
              "CDC42EP4",
              "ROBO2"
            ),
            ncol = 3)

```

# Plot cluster markers

#EC_cap_1
                           "ATP10A",
                           "SPOCK3",
                           "SLC39A10",
           #EC_cap_2
           "JCAD",
           "ITM2A",
           "NRXN1",
           "SLC26A3",
           "INO80D",
           #EC_cap3
           "SLC9A9",
           "HDAC9",
           "RBM47",
           #EC_cap_4
           "PCDH9",
           "TF",
           "IL1RAPL1",
           "ARL15",
           #EC_cap_5
           "PTPRC",
           "SKAP1",
           "ARHGAP15",
           "CD247",
           #EC_art_1
           "PELI1",
           "ARL15",
           "RALGAPA2",
           "BACE2",
           "IL1R1",
           #EC_art_2
           "ACKR1",
           "AQP1",
           #EC_art_3
           "S100A6",
           "TIMP1",
           "CTSL",
           "TFPI2",
           "MGP",
           #Mural_cap_1 abd Mural_cap_2
           "GPC5",
           "GRM3",
           "GRM8",
           "SLC38A11",
           "SLC20A2",
           "FRMD3",
           #Mural_vein_1
           "CEMIP",
           "FLRT2",
           "BICC1",
           "MIR99AHG",
           "NTRK3",
           #vSMC
           "ACTA2",
           "MYH11",
           "TAGLN",
           "ZFHX3",
           "SLIT3",

```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("ATP10A", "JCAD"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```

```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("PCDH9", "SLC9A9"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```


```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("PELI1", "PTPRC"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```

```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("ACKR1", "TIMP1"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```

```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("GPC5", "CEMIP"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```

```{r, fig.width = 8, fig.height = 2}

FeaturePlot(vasc_srt, features = c("PLP1", "ACTA2"), order = T, 
            min.cutoff = "q1",
            max.cutoff = "q99", blend = T, 
            cols = c("darkblue", "green", "magenta"), 
            blend.threshold = 0)  &NoAxes()
```

# Find tissue markers
```{r}
Idents(vasc_srt) <- "Tissue"

tissue_dir <- here("outs",
                   "vascular_cells",
                   "tissue_marker_list_vasc")


```


```{r, eval = FALSE}


tissue_markers <- FindAllMarkers(vasc_srt,
                                 only.pos = TRUE, 
                                 min.pct = 0.25, 
                                 logfc.threshold = 0.25)


dir.create(tissue_dir)
write.csv(tissue_markers, here(tissue_dir, 
                               "vasc_tissue_mark.csv"))
```


```{r}
tissue_markers <- read.csv(here(tissue_dir, 
                               "vasc_tissue_mark.csv"))

tissue_markers



```
```{r}
sig_tissue_mark <- subset(tissue_markers, tissue_markers$p_val_adj < 0.05)

top_tissue<- sig_tissue_mark %>%
    group_by(cluster) %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_tissue$gene), group.by = "Tissue") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```
BA4
```{r, fig.width = 12, fig.height = 9}
FeaturePlot(vasc_srt, features = c("CST3",
                                    "MGP",
                                   "SLC26A3"),
            split.by = "Tissue")

```


```{r, fig.width = 12, fig.height = 21}
FeaturePlot(vasc_srt, features = c("PITPNC1",
                                    "COL4A2",
                                   "FAM155A",
                                   "APOE",
                                   "RNF152",
                                   "RIMKLB",
                                   "VMP1"),
            split.by = "Tissue")

```

```{r, fig.width = 12, fig.height = 66}
FeaturePlot(vasc_srt, features = c("PLP1",
                                    "S100B",
                                   "RPS28",
                                   "MBP",
                                   "CLU",
                                   "SLC7A11",
                                   "FMNL2",
                                   "PTGDS",
                                   "NDRG1",
                                   "CEMIP",
                                   "MIR99AHG",
                                   "HSPA5",
                                   "CACNB2",
                                   "BACE2",
                                   "ZFP36",
                                   "IL1R1",
                                   "ATP13A3",
                                   "NTRK3",
                                   "PRKCA",
                                   "FOXO1",
                                   "DCN",
                                   "LAMA2"),
            split.by = "Tissue")

```

# anterior (BA4) vs posterior (CB, CSC) tissue regions

```{r}
Idents(vasc_srt) <- "Tissue"

```


```{r, eval = FALSE}


ba4_markers <- FindMarkers(vasc_srt,
                           ident.1 = "BA4",
                           ident.2 = c("CB", "CSC"),
                           only.pos = TRUE, 
                           min.pct = 0.25, 
                           logfc.threshold = 0.25)



write.csv(ba4_markers, here(tissue_dir, 
                               "vasc_ba4_mark_vs_cb_csc.csv"))
```


```{r}
sig_ba4_mark <- subset(ba4_markers, ba4_markers$p_val_adj < 0.05)

sig_ba4_mark$gene <- rownames(sig_ba4_mark)

top_ba4<- sig_ba4_mark %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_ba4$gene), group.by = "Tissue") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```



```{r}
sig_ba4_mark <- subset(ba4_markers, ba4_markers$p_val_adj < 0.05)

sig_ba4_mark$gene <- rownames(sig_ba4_mark)

top_ba4<- sig_ba4_mark %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_ba4$gene), group.by = "Tissue") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```

# posterior tissue regions (CB, CSC) vs anterior (BA4) tissue regions



```{r, eval = FALSE}


posterior_markers <- FindMarkers(vasc_srt,
                           ident.1 = c("CB", "CSC"),
                           ident.2 = "BA4",
                           only.pos = TRUE, 
                           min.pct = 0.25, 
                           logfc.threshold = 0.25)



write.csv(posterior_markers, here(tissue_dir, 
                               "vasc_posterior_mark_vs_ba4.csv"))
```


```{r}
sig_posterior_mark <- subset(posterior_markers, posterior_markers$p_val_adj < 0.05)

sig_posterior_mark$gene <- rownames(sig_posterior_mark)

top_ba4<- sig_posterior_mark %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_ba4$gene), group.by = "Tissue") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```

# From Bono

## Artery genes

```{r, fig.width = 8, fig.height = 8}
FeaturePlot(vasc_srt, features = c("BMX",     #According to Vanlandewijck paper (Mouse)
                                 "SEMA3G", #According to Vanlandewijck paper (Mouse)
                                 "VEGFC",  #According to Vanlandewijck paper (Mouse)
                                 "EFNB2",  #Preferentially on arterial endothelium (Human & mouse)
                                 "NOTCH1", #Arterial specificaiton and angiogenic potential (Mouse)
                                 "NOTCH4", 
                                 "DLL4",   #Canonical NOTCH ligand strongly expressed in arterial ECs
                                 "HEY2"))


```

## Vein genes

```{r, fig.width = 8, fig.height = 8}

FeaturePlot(vasc_srt, features = c("NR2F2",   #Expressed in vein ECs (Mouse)
                                 "VCAM1",   #According to Vanlandewijck paper (Mouse)
                                 "VWF",     #According to Vanlandewijck paper (Mouse)
                                 "SLC38A5", #According to Vanlandewijck paper (Mouse)
                                 "EPHB4", #Preferentially expressed in vein ECs (Human & mouse),
                                 "EMCN",  #Expressed in humans
                                 "IL1R1"  #Expressed in Humans
                                 ))
```

## Capillary genes

```{r, fig.width = 8, fig.height = 8}
FeaturePlot(vasc_srt, features = c("SLC16A1",  #According to Vanlandewijck paper (Mouse)
                                 "MFSD2A",   #According to Vanlandewijck paper (Mouse)
                                 "SLC7A5",   #According to Vanlandewijck paper (Mouse)
                                 "TFRC",     #According to Vanlandewijck paper (Mouse)
                                 "ABCB1",    #P-glycoprotein (MDR) is often expressed in brain capillary ECs (ABC transporter)(Mouse)
                                 "ABCG2",    #BCRP also demonstrated before is excessively expressed in brain capillary ECs (ABC transporter)(Human & Mouse)
                                 "SLC7A5",   #LAT-1 expressed in BBB models, responsible for transport of large neutral AAs, L-dopa and gabapentin by brain capillary ECs (Human & Mouse)
                                 "SLC2A1"   #GLUT-1 expressed in BBB models, responsible for drug transporter in the brain capillary (Human & Mouse)
                                 ))

```

## predict labels with SCINA (BONO)
```{r}

Capillary <- c("MFSD2A", "SLC16A1", "SLC7A5", "TFRC", "ABCB1")
Arterial <- c("SEMA3G", "EFNB2", "VEGFC", "HEY2", "BMX")
Vein <- c("EPHB4", "IL1R1", "VCAM1", "EMCN", "NR2F2")
Markers <- cbind(Capillary, Arterial, Vein)
Mark <- as.data.frame(Markers)
annot_EC <- SCINA(GetAssayData(vasc_srt, slot = "data"), signature = Mark, allow_unknown = FALSE, rm_overlap = FALSE)

Idents(vasc_srt) <- annot_EC$cell_labels
vasc_srt$SCINA_annot <- annot_EC$cell_labels
DimPlot(vasc_srt, reduction = "umap", group.by = "SCINA_annot")
```


## predict labels with scSorter (BONO)
```{r}

Type <- c("Capillary", "Capillary", "Capillary", "Capillary", "Capillary", "Arterial", "Arterial", "Arterial", "Arterial", "Arterial", "Vein", "Vein", "Vein", "Vein", "Vein", "Mural", "Mural", "Mural", "Mural", "vSMC")

Marker <- c("MFSD2A", "SLC16A1", "SLC7A5", "TFRC", "ABCB1","MGP", "VEGFC", "HEY2","BMX", "EFNB2", "ICAM1", "IL1R1","EPHB4", "NR2F2", "VCAM1", "PDGFRB", "NOTCH3", "CSPG4", "VEGFA", "ACTA2")

Weight <- c(2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 2, 5, 5, 5, 2, 2, 5)
Markerr <- cbind(Type, Marker, Weight)
Markerss <- as.data.frame(Markerr)

annot_EC_2 <- scSorter(vasc_srt@assays$RNA@data, Markerss, alpha = 0)
vasc_srt$scSorter <- annot_EC_2$Pred_Type
Idents(vasc_srt) <- "scSorter"
DimPlot(vasc_srt, cols = mycoloursP)
```


```{r, fig.width= 8, fig.height = 8}
DimPlot(vasc_srt, split.by = "scSorter", ncol = 2, cols = mycoloursP)


```

##

```{r}
art <- vasc_srt[,vasc_srt@meta.data$scSorter == "Arterial"]

capi <- vasc_srt[,vasc_srt@meta.data$scSorter == "Capillary"]

veins <- vasc_srt[,vasc_srt@meta.data$scSorter == "Vein"]

mural <- vasc_srt[,vasc_srt@meta.data$scSorter == "Mural"]

vSMC <- vasc_srt[,vasc_srt@meta.data$scSorter == "vSMC"]
  
  
tgt <- merge(art, c(capi, veins, mural, vSMC), 
             add.cell.ids = c("Arterial", "Capillary", "Vein", "Mural", "vSMC"))
```


```{r, echo = TRUE}
CellsPerSubtype <- as.data.frame(tapply(
    vasc_srt@meta.data$Barcode, vasc_srt@meta.data$scSorter, function(x) length(x) ))

names(CellsPerSubtype) <- "NumberOfCells"

CellsPerSubtype$Subtype <- rownames(CellsPerSubtype)

CellsPerSubtype$Subtype <- rownames(CellsPerSubtype)

CellsPerSubtype
```


```{r}
col_art <- rep(mycoloursP[3],ncol(tgt[,tgt@meta.data$scSorter=="Arterial"]))

col_capi <- rep(mycoloursP[2],ncol(tgt[,tgt@meta.data$scSorter=="Capillary"]))

col_vein <- rep(mycoloursP[5],ncol(tgt[,tgt@meta.data$scSorter=="Vein"]))

col_mural <- rep(mycoloursP[6],ncol(tgt[,tgt@meta.data$scSorter=="Mural"]))

col_vSMC <- rep(mycoloursP[1],ncol(tgt[,tgt@meta.data$scSorter=="vSMC"]))

palette <- c(col_art, col_capi, col_vein, col_mural, col_vSMC)

tgt$color <- palette
```


```{r, fig.width= 8, fig.height= 10}
par(mfrow = c(3, 1))
barplot(tgt@assays$RNA@data["HEY2",], main = "HEY2", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["VEGFC",], main = "VEGFC", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
#barplot(tgt@assays$RNA@data["SEMA3G",], main = "SEMA3G", axisnames = FALSE, ylab = "count", border = tgt$color, cex.axis = 2, cex.main = 2, cex.lab = 2)
barplot(tgt@assays$RNA@data["MGP",], main = "MGP", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["MFSD2A",], main = "MFSD2A", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["SLC16A1",], main = "SLC16A1", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["TFRC",], main = "TFRC", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["VCAM1",], main = "VCAM1", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["IL1R1",], main = "IL1R1", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)
barplot(tgt@assays$RNA@data["NR2F2",], main = "NR2F2", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)

barplot(tgt@assays$RNA@data["PDGFRB",], main = "PDGFRB", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)

barplot(tgt@assays$RNA@data["NOTCH3",], main = "NOTCH3", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)

barplot(tgt@assays$RNA@data["CSPG4",], main = "CSPG4", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)

barplot(tgt@assays$RNA@data["VEGFA",], main = "VEGFA", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)

barplot(tgt@assays$RNA@data["ACTA2",], main = "ACTA2", axisnames = FALSE, ylab = "Expression", border = tgt$color, cex.axis = 2, cex.main = 3, cex.lab = 1.5)



```

# Find age  markers
```{r}
Idents(vasc_srt) <- "AgeGroup"

age_dir <- here("outs",
                   "vascular_cells",
                   "age_marker_list_neuron")
```


```{r, eval = FALSE}

age_markers <- FindAllMarkers(vasc_srt,
                                 only.pos = TRUE, 
                                 min.pct = 0.25, 
                                 logfc.threshold = 0.25)




dir.create(age_dir)
write.csv(age_markers, here(age_dir, 
                               "vasc_age_marker.csv"))

```

```{r}
age_markers <- read.csv(here(age_dir, "vasc_age_marker.csv"))

age_markers


```


```{r}
sig_age_mark <- subset(age_markers, age_markers$p_val_adj < 0.05)

top_age<- sig_age_mark %>%
    group_by(cluster) %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_age$gene), group.by = "AgeGroup") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```

## More in young:

```{r, fig.width = 12, fig.height = 4}
FeaturePlot(vasc_srt, features = c("PLP1"), split.by = "AgeGroup")

```

## More in old:

```{r, fig.width = 12, fig.height = 27}
FeaturePlot(vasc_srt, features = c("HLA-C",
                                    "HIF1A-AS2",
                                   "FLT1",
                                   "ARL15",
                                   "S100A6",
                                   "ANXA1"), 
            split.by = "AgeGroup")

```






# Find sex markers
```{r}
Idents(vasc_srt) <- "gender"

sex_dir <- here("outs",
                   "vascular_cells",
                   "sex_marker_list_vasc")

```


```{r, eval = FALSE}
sex_markers <- FindAllMarkers(vasc_srt,
                                 only.pos = TRUE, 
                                 min.pct = 0.25, 
                                 logfc.threshold = 0.25)
sex_markers

dir.create(sex_dir)

write.csv(sex_markers, here(sex_dir,  "vasc_sex_marker.csv"))

```

```{r}

sex_markers <- read.csv(here(sex_dir,  "vasc_sex_marker.csv"))
sex_markers
```

```{r}
sig_sex_markers <- subset(sex_markers, sex_markers$p_val_adj <0.05)

top_sex<- sig_sex_markers %>%
    group_by(cluster) %>%
    top_n(n = 20, wt = avg_log2FC)

DotPlot(vasc_srt, features = unique(top_sex$gene), group.by = "gender") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```

# Find age*sex
```{r}
Idents(vasc_srt) <- "ageSex"

age_sex_dir <- here("outs",
                   "vascular_cells",
                   "age_sex_marker_list_vasc")


```


```{r, eval = FALSE}


age_sex_markers <- FindAllMarkers(vasc_srt,
                                 only.pos = TRUE, 
                                 min.pct = 0.25, 
                                 logfc.threshold = 0.25)


dir.create(age_sex_dir)
write.csv(age_sex_markers, here(age_sex_dir, 
                               "vasc_age_sex_mark.csv"))
```


```{r}
age_sex_markers <- read.csv(here(age_sex_dir, 
                               "vasc_age_sex_mark.csv"))

age_sex_markers



```


```{r}
sig_age_sex_mark <- subset(age_sex_markers, age_sex_markers$p_val_adj < 0.05)

top_age_sex<- sig_age_sex_mark %>%
    group_by(cluster) %>%
    top_n(n = 20, wt = avg_log2FC)

top_age_sex <- top_age_sex %>% arrange(factor(top_age_sex$cluster, levels = c("Old men",
                                                              "Old women",
                                                              "Young men",
                                                              "Young women")))

vasc_srt$ageSex <- factor(vasc_srt$ageSex, levels = c("Old men",
                                                      "Old women",
                                                      "Young men",
                                                      "Young women"))


Idents(vasc_srt) <- "ageSex"

DotPlot(vasc_srt, features = unique(top_age_sex$gene), group.by = "ageSex") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

```

## More in women

```{r, fig.width = 12, fig.height = 140}
FeaturePlot(vasc_srt, features = c("XIST",
                                    "RPS4X",
                                    "TIMP1",
                                    "ACTG1",
                                    "ANXA2",
                                    "TPT1",
                                   "RPS8",
                                   "RPS3",
                                   "RPS24",
                                   "RPS12",
                                   "MT2A",
                                   "GAPDH",
                                   "RPS27A",
                                   "S100A11",
                                   "S100A6",
                                   "C11orf96",
                                   "COL4A1",
                                   "RPL29",
                                   "VIM",
                                   "YBX1",
                                   "ADAMTS9",
                                   "RPL37",
                                   "LGALS1",
                                   "ATP1B3",
                                   "RPL5",
                                   "RPL30",
                                   "CD63",
                                   "RPL14",
                                   "PPIB",
                                   "SH3BGRL3",
                                   "LDHA",
                                   "RPS13",
                                   "FTL",
                                   "S100A10",
                                   "ANXA1",
                                   "SRP14",
                                   "PRDX1",
                                   "MGP",
                                   "TUBA1B",
                                   "EEF1B2",
                                   "COL4A2",
                                   "AKAP12"), 
            split.by = "gender")
# first encoded by inactivated X-chromosome
```


## More in men

```{r, fig.width = 12, fig.height = 15}
FeaturePlot(vasc_srt, features = c("UTY",
                                   "USP9Y",
                                   "PRKY",
                                   "HSPA1A",
                                   "ARL15"
                                    ), 
            split.by = "gender")
# first 2 are encoded on Y-chromosome
```




# Cluster QC based on resolution 0.7

# Cluster QC

#### Individuals per cluster
How many individuals contribute to each cluster?

```{r indiv-per-cluster}
# count how many cells there are in each group and cluster
sum_caseNO_cluster <- table(vasc_srt$vascular_cells_clu, vasc_srt$caseNO)
# For each cluster (on the rows) sum of individuals that do have cells on that cluster
rowSums(sum_caseNO_cluster > 0)
```
Nothing stands out except for maybe cluster 9 (but tissues need to be considered
as well)

#### Percentage of cells that come from each individual

Some of the clusters might be mainly from one person, even though other subjects
do have some cells that cluster with it. To address this question we calculate
for each cluster the proportion of cells that come from each caseNO.

```{r prop-per-cluster}

# calculate the proportions, for each cluster (margin 1 for rows)
prop_caseNO_table <- prop.table(sum_caseNO_cluster, margin = 1)
# change the format to be a data.frame, this also expands to long formatting
prop_caseNO <- as.data.frame(prop_caseNO_table)
colnames(prop_caseNO) <- c("cluster", "caseNO", "proportion")
```

Flag the clusters where one of the individuals covers more than 40% of the
cluster. The expected would be around `1/20= 5%`

```{r}
prop_caseNO[prop_caseNO$proportion > 0.4, ]
```


#### Minimum threshold of 2% contribution to count individuals
Another interesting variable is the number of individuals that contribute to
more than a certain threshold (15%) to each cluster

```{r min-pct}
# Calculuate for each cluster the number of individuals that fulfill the condition of contributing more than a 15%
num_individuals_gt_30pt <- rowSums(prop_caseNO_table > 0.30)
# Sort the clusters by ascending order of number of individuals that contribute more than 2%
sort(num_individuals_gt_30pt)
#And a general overview of the data
summary(num_individuals_gt_30pt)
# Save the ones that are formed by less than 8 individuals that fulfill the condition
clusters_fail <- rownames(prop_caseNO_table)[which(num_individuals_gt_30pt < 8)]

clusters_fail
```



Plot the proportions for caseNo

```{r prop-plot}
# plot a barplot


ggplot(data = prop_caseNO, aes(x = cluster, y = proportion, fill = caseNO)) +
  geom_bar(stat = "identity") + theme_classic() + 
  scale_fill_manual(values=mycoloursP[1:20]) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```

It is also worth keeping in mind the size of the cluster, there are in ascending
order (0 is the biggest cluster and 10 the smallest).

#### Samples instead of individuals

The proportions are again calculated but taking into consideration the samples 
instead of the individuals

```{r}
# count how many cells there are in each group and cluster
sum_caseNOtissue_cluster <- table(vasc_srt$vascular_cells_clu, vasc_srt$process_number)
# calculate the proportions, for each cluster (margin 1 for rows)
prop_caseNOtissue_table <- prop.table(sum_caseNOtissue_cluster, margin = 1)
# change the format to be a data.frame, this also expands to long formatting
prop_caseNOtissue <- as.data.frame(prop_caseNOtissue_table)
colnames(prop_caseNOtissue) <- c("cluster", "process_number", "proportion")
prop_caseNOtissue[prop_caseNOtissue$proportion > 0.3, ]
```
## Conclusion of cluster QC





# Compositional differences with age, sex and regions 

Some general distributions about the data. We started with equal number of
sex/age/tissues but because we deleted samples these are not equal any more.
Also the number of cells from each one might differ

```{r general}
# Number of samples per ageSex
colSums(table(vasc_srt$process_number, vasc_srt$ageSex)>0)
# Number of samples per tissue
colSums(table(vasc_srt$process_number, vasc_srt$Tissue)>0)
# Both things combined (there might be another way of doing this, but it works)#
colSums(table(vasc_srt$caseNO, vasc_srt$ageSex, vasc_srt$Tissue)>0)
# Number of nuclei per sexage group
table(vasc_srt$ageSex)

#number of nuclei per tissue
table(vasc_srt$Tissue)
#number of nuclei per age group
table(vasc_srt$AgeGroup)
#number of nuclei per sex group
table(vasc_srt$gender)

# both things combined
table(vasc_srt$ageSex, vasc_srt$Tissue)


```



## Age and Sex Grouping

Separate by both things in 4 plots. The plots are corrected by number of cells
per sexage group first (looking at the distribution of each group across
clusters) and then corrected for the number of cells per cluster (to visualize
the small and big clusters equally).

```{r, fig.width=12, fig.height=12}
# Sex
# DimPlot(nad_ol, split.by = "ageSex", group.by = "Tissue", ncol = 5)
DimPlot(vasc_srt, split.by = "ageSex", group.by = "vascular_cells_clu", ncol = 2,
        cols = mycoloursP, pt.size = 2, label = TRUE, label.size = 6)
```

Calculate proportion clusters for each AgeSex

```{r}
# count how many cells there are in each group and cluster
sum_ageSex_cluster <- table(vasc_srt$vascular_cells_clu, vasc_srt$ageSex)
# Calculate the proportions for each group: 
# allows to normalise the groups and give the same weight to all groups, 
# even though they might have different cell numbers (margin 2 for cols)
prop_ageSex_table_2 <- prop.table(sum_ageSex_cluster, margin = 2)
# calculate the proportions, for each cluster, 
# allows to visualize on a scale from 0 to 1 (margin 1 for rows)
prop_ageSex_table_2_1 <- prop.table(prop_ageSex_table_2, margin = 1)
# change the format to be a data.frame, this also expands to long formatting

prop_ageSex <- as.data.frame(prop_ageSex_table_2)
colnames(prop_ageSex) <- c("cluster", "ageSex", "proportion")

level_list <- c("Young women", "Old women", "Young men", "Old men")
prop_ageSex$ageSex <- factor(prop_ageSex$ageSex, levels = level_list)


# plot a barplot proportion
ggplot(data = prop_ageSex, aes(x = cluster, y = proportion, fill = ageSex)) +
  geom_bar(stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[1:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  ylab("Normalised counts")


ggplot(data = prop_ageSex, aes(x = cluster, y = proportion, fill = ageSex)) +
  geom_bar(position = "fill", stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[1:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  ylab("Normalised counts")



```

Plot the same for Sex and Age separate

```{r}
# separate the sex and age
prop_ageSex_sep <- separate(prop_ageSex, 
                            col = ageSex, 
                            into = c("age", "sex"), 
                            sep = " ")




# plot a barplot for the sex
ggplot(data = prop_ageSex_sep, aes(x = cluster, y = proportion, fill = sex)) +
  geom_bar(stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[10:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

ggplot(data = prop_ageSex_sep, aes(x = cluster, y = proportion, fill = sex)) +
  geom_bar(position = "fill", stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[10:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

# And for the age
ggplot(data = prop_ageSex_sep, aes(x = cluster, y = proportion, fill = age)) +
  geom_bar(stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[15:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

ggplot(data = prop_ageSex_sep, aes(x = cluster, y = proportion, fill = age)) +
  geom_bar(position = "fill", stat = "identity") + theme_classic() + scale_fill_manual(values=mycoloursP[15:20]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```

## Tissue

split the clustering by the original tissues

```{r, fig.width=9, fig.height=3}
Idents(vasc_srt) <- "vascular_cells_clu"
umap_clusters <- DimPlot(vasc_srt, split.by = "Tissue", 
                         cols = mycoloursP, pt.size = 2, label = T) +NoLegend()
umap_clusters
```

Calculate proportion clusters for each Tissue

```{r}
# count how many cells there are in each group and cluster
sum_tissue_cluster <- table(vasc_srt$vascular_cells_clu, vasc_srt$Tissue)

keep <- rowSums(sum_tissue_cluster) > 0
sum_tissue_cluster <- sum_tissue_cluster[keep,]

# Calculate the proportions for each group: 
# allows to normalise the groups and give the same weight to all groups, 
# even though they might have different cell numbers (margin 2 for cols)
prop_tissue_table_2 <- prop.table(sum_tissue_cluster, margin = 2)
# calculate the proportions, for each cluster, 
# allows to visualize on a scale from 0 to 1 (margin 1 for rows)
prop_tissue_table_2_1 <- prop.table(prop_tissue_table_2, margin = 1)
# change the format to be a data.frame, this also expands to long formatting
prop_tissue <- as.data.frame(prop_tissue_table_2)
colnames(prop_tissue) <- c("cluster", "Tissue", "proportion")


#plot
ggplot(data = prop_tissue, aes(x = cluster, y = proportion, fill = Tissue)) +
  geom_bar(stat = "identity") + theme_classic() + 
  scale_fill_manual(values=mycoloursP[24:40]) +
  ylab("Normalised counts") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```

```{r}

ggplot(data = prop_tissue, aes(x = cluster, y = proportion, fill = Tissue)) +
  geom_bar(position = "fill", stat = "identity") + theme_classic() + 
  scale_fill_manual(values=mycoloursP[24:40]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```




### tables shown with numbers

To better understand the proportions I show the different steps with tables

```{r}
sum_ageSex_cluster
(prop_ageSex_table_2)*100
prop_ageSex_table_2_1*100
```

# Gene set enrichment analysis

## Age
Only genes that were enriched in older individuals were statistically significant.

```{r}

Teams %>% 
    filter(yearID %in% 1961:2001 ) %>%
    select(HR, BB, R) %>% 
    head()


hallmark <- msigdbr(species = "Homo sapiens", category = "H")
geneset <- hallmark %>% split(x = .$gene_symbol, f = .$gs_name)

# Prepare input data
ranks <- sig_age_mark %>% dplyr::select(gene, avg_log2FC)
ranks <- deframe(ranks)
# Run fgsea
old_gsea_sig <- fgsea(pathways = geneset, stats = ranks, scoreType= "pos")
# Tidy output
old_gsea_sig_tidy <- old_gsea_sig %>% as_tibble() %>% arrange(desc(NES))
old_gsea_sig_tidy %>% dplyr::select(-leadingEdge, -ES) %>% arrange(padj)

# Create barplot 
ggplot(old_gsea_sig_tidy, aes(reorder(pathway, NES), NES)) + geom_col(aes(fill=padj<0.05)) + theme_minimal() + coord_flip()

```

## Sex

### Male

```{r}
sig_sex_markers_male <- subset(sig_sex_markers, sig_sex_markers$cluster == "M")

hallmark <- msigdbr(species = "Homo sapiens", category = "H")
geneset <- hallmark %>% split(x = .$gene_symbol, f = .$gs_name)

# Prepare input data
ranks <- sig_sex_markers_male %>% dplyr::select(gene, avg_log2FC)
ranks <- deframe(ranks)
# Run fgsea
male_gsea_sig <- fgsea(pathways = geneset, stats = ranks, scoreType= "pos")
# Tidy output
male_gsea_sig_tidy <- male_gsea_sig %>% as_tibble() %>% arrange(desc(NES))
male_gsea_sig_tidy %>% dplyr::select(-leadingEdge, -ES) %>% arrange(padj)

# Create barplot 
ggplot(male_gsea_sig_tidy, aes(reorder(pathway, NES), NES)) + geom_col(aes(fill=padj<0.05)) + theme_minimal() + coord_flip()

```
### Female

```{r}
sig_sex_markers_female <- subset(sig_sex_markers, sig_sex_markers$cluster == "F")


# Prepare input data
ranks <- sig_sex_markers_female %>% dplyr::select(gene, avg_log2FC)
ranks <- deframe(ranks)
# Run fgsea
female_gsea_sig <- fgsea(pathways = geneset, stats = ranks, scoreType= "pos")
# Tidy output
female_gsea_sig_tidy <- female_gsea_sig %>% as_tibble() %>% arrange(desc(NES))
female_gsea_sig_tidy %>% dplyr::select(-leadingEdge, -ES) %>% arrange(padj)

# Create barplot 
ggplot(female_gsea_sig_tidy, aes(reorder(pathway, NES), NES)) + geom_col(aes(fill=padj<0.05)) + theme_minimal() + coord_flip()

```




  
  
# Save dataset

```{r}
dir.create(here("data",
                "single_nuc_data",
                "vascular_cells"))
           
saveRDS(vasc_srt, here("data",
                        "single_nuc_data",
                        "vascular_cells",
                        "HCA_vascular_cells.RDS"))

```


# Subset for ECs of BA4 and CSC

```{r}

ECs <- subset(vasc_srt, ident = c("EC_cap_1", "EC_cap_2"))

Idents(ECs) <- "Tissue"

ec_ba4_csc <- subset(ECs, ident = c("BA4", "CSC"))


all_mark_ec <- FindAllMarkers(ec_ba4_csc, 
                               only.pos = TRUE, 
                               min.pct = 0.25, 
                               logfc.threshold = 0.25,
                               test.use = "MAST")

ba4 <- FindMarkers(ec_ba4_csc, 
                   ident.1 = "BA4",
                   ident.2 = "CSC",
                   only.pos = FALSE, 
                   min.pct = 0.25, 
                   logfc.threshold = 0.25,
                   test.use = "MAST")
   
```

```{r, fig.width = 8, fig.height = 8}

EnhancedVolcano(ba4,
    lab = rownames(ba4),
    x = 'avg_log2FC',
    y = 'p_val_adj',
    FCcutoff = 0.5,
    title = "BA4 vs. CSC",
    subtitle = "Endothelial cells")


```


```{r}
VlnPlot(ec_ba4_csc, features = "SERF2", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```

```{r}
VlnPlot(ec_ba4_csc, features = "EIF1", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```

```{r}
VlnPlot(ec_ba4_csc, features = "SERF2", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```

```{r}
VlnPlot(ec_ba4_csc, features = "HOPX", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "TMSB10", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "TMSB4X", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "MT1E", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "TPT1", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
TPT1 is oinvolved in controlling cell cycle. Also important for calcium 
homeostasis and microtubule stabilisation.
```{r}
VlnPlot(ec_ba4_csc, features = "SPARC", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "SPARCL1", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "GNG11", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
GNG11 induced cellular senescence. 
(https://www.sciencedirect.com/science/article/pii/S0006291X06023291?casa_token=oxjQGaca1YgAAAAA:mRWfkr96qDW9FdCpazKh-N_XNozmsHInt4Wan0GptPZPGQMETOWjQJ_Cqhj0YHpWJ-E-mdhi0rQ)


```{r}
VlnPlot(ec_ba4_csc, features = "CLU", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
```{r}
VlnPlot(ec_ba4_csc, features = "RPS28", split.by = "Tissue")+ 
  scale_fill_manual(values=c(mycoloursP[24], mycoloursP[26]))

```
# PCs

is there more evidence for pericytes that are less tightly connected?

```{r}

pcs <- subset(vasc_srt, ident = c("Mural_cap_1", "Mural_cap_2"))

Idents(pcs) <- "Tissue"

pcs_ba4_csc <- subset(pcs, ident = c("BA4", "CSC"))


pc_ba4 <- FindMarkers(pcs_ba4_csc, 
                   ident.1 = "BA4",
                   ident.2 = "CSC",
                   only.pos = FALSE, 
                   min.pct = 0.25, 
                   logfc.threshold = 0.25,
                   test.use = "MAST")
```



   


```{r, fig.width = 8, fig.height = 8}

EnhancedVolcano(pc_ba4,
    lab = rownames(pc_ba4),
    x = 'avg_log2FC',
    y = 'p_val_adj',
    FCcutoff = 0.5,
    title = "BA4 vs. CSC",
    subtitle = "Pericytes")


```

# Session Info


```{r}
sessionInfo()
```