---
title: "Preparing the Parabiosis 10x droplet dataset for ExperimentHub"
author: "Tram Nguyen"
date: "`r Sys.Date()`"
output: html_document
editor_options: 
  markdown: 
    wrap: 72
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(width = 80)
```

# Data pre-processing

Basic processing using the R package Seurat has already been performed
on this data to remove low-quality cells and animals following the
methods described in Ximerakis & Holton et al. 2023. Briefly, the
initial dataset contained 158,767 cells with data for 21,876 genes. The
data were log-normalized and scaled to 10,000 transcripts per cell. This
was used to create a UMAP using the first 50 PCs from a Principal
Components Analysis to find cell clusters with the function
`FindClusters()`. All clusters with only one cell, \>8% mitochondrial
genes, or minimum number of RNA transcripts counts \< 1,000 were
removed. Animals with number of genes \< 700, percent mitochondrial \>
1.5 and not having any cell contribution to each clusters were
identified for exclusion.

The second round of quality control (QC) filtering removed clusters with
minimum percentage mitochondria 0, maximum percentage mitochondria 5%,
min_nFeature_RNA 250, max_nFeature_RNA 6000, min_nCount_RNA 200,
max_nCount_RNA 30000, min_cells=5. After this second round of QC, the
final dataset retained 130,889 cells and 20,905 genes.

Finally, probable doublet artifacts were removed. Doublets/multiplets
were marked as any cluster in which \>40% of its cells express seven of
the top ten genes specific to an initially identified cell type and any
other outside of the class of the cell type with which it is associated.

The final processed dataset includes 105,329 cells and 20,905 genes
which can be downloaded from GEO.

# Download processed data

The [un-normalized count
table](https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE222510&format=file&file=GSE222510%5Fraw%5Fmatrix%2Emtx%2Egz),
[cell
barcodes](https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE222510&format=file&file=GSE222510%5Fraw%5Fbarcodes%2Etsv%2Egz),
[gene
symbols](https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE222510&format=file&file=GSE222510%5Fraw%5Fgenes%2Etsv%2Egz),
and
[metadata](https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE222510&format=file&file=GSE222510%5Ffiltered%5Fmetadata%2Etxt%2Egz)
were all downloaded from GEO [accession number
GSE222510](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE222510)
(accessed January 3, 2024).

UMAP, TSNE, PCA coordinates were provided courtesy of the authors.

# Generate `SingleCellExperiment` object

```{r}
suppressPackageStartupMessages({
  library(Matrix)
  library(SingleCellExperiment)
  library(DropletUtils)
  library(readr)
  library(dplyr)
})

barcodes <- read.table("barcodes.tsv", header = FALSE, stringsAsFactors = FALSE)
genes <- read.table("genes.tsv", header = FALSE, stringsAsFactors = FALSE)
metadata <- read.table("filtered.metadata.txt", header = TRUE, sep = "")

# Put all file into one directory called raw_files/10X/ and read them in with
# DropletUtils

sce <- read10xCounts("raw_files/10X/", col.names = FALSE)

# Check that loaded sce matches genes on GEO
stopifnot(all(rownames(counts(sce)) == genes))

dim(sce) # 20905 105329

# Manipulate the metadata and rownames to remove duplicate, irrelevant info
colnames(sce) <- NULL # Remove barcodes in the colnames
colData(sce)$orig.ident <- NULL
colData(sce)$sample_order <- NULL

# metadata(sce)$Samples autopopulates to the file prefix. 
metadata(sce)$Samples <- NULL

# Rename column names of metadata
names(colData(sce))[which(names(colData(sce)) =="animal_name")] <- 
  "animal_type"
names(colData(sce))[which(names(colData(sce)) =="percent.mito")] <- 
  "percent_mito"
names(colData(sce))[which(names(colData(sce)) =="percent.ribo")] <- 
  "percent_ribo"
names(colData(sce))[which(names(colData(sce)) =="percent.ribo")] <- 
  "percent_ribo"

counts(sce)[1:10, 1:10]

# Load in HVG from the authors
hvg <- readRDS("~/all_lin_hvg.v1.rds")

# Create a new column using dplyr's mutate function
rowData(sce)$geneID <- rownames(sce)
rowData(sce)$HVG <- ""

c.df <- as.data.frame(rowData(sce))

c.df <- c.df %>%
  mutate(HVG = if_else(rownames(c.df) %in% hvg, "TRUE", "FALSE"))

# Check that we've captured all 2000 HVG
stopifnot(sort(c.df$geneID[which(c.df$HVG == "TRUE")]) == sort(hvg))

rowData(sce)$HVG <- as.factor(c.df$HVG)


# Coerce columns to factors
cols <- 
  c("animal", "batch", "parabiosis_category", "cell_type", "subpopulation")

colData(sce)[cols] <- lapply(colData(sce)[cols], factor)


# Add Cell Ontology labels provided by authors
CO <- read.csv("~/2023na_co.csv")

# Relabel csv column names. CO class and id are switched
colnames(CO) <- c("cell_type", "cell_ontology_class", "cell_ontology_id")

# Match levels to match CO cell type order
cell_levels <- CO$cell_type

# left join CO terms
colData(sce) <- DataFrame(colData(sce) %>% as_tibble() %>% 
                                left_join(CO, by = "cell_type"))

# Set levels for cell_type, cell_ontology_id, and cell_ontology_class
# Reorder levels based on aging biology and authors' study
colData(sce)$cell_type <- factor(colData(sce)$cell_type, levels = cell_levels)
levels(colData(sce)$cell_type) # check

colData(sce)$cell_ontology_class <- factor(colData(sce)$cell_ontology_class, 
                                             levels = unique(CO$cell_ontology_class), 
                                             exclude = NULL)

colData(sce)$cell_ontology_id <- factor(colData(sce)$cell_ontology_id, 
                                          levels = unique(CO$cell_ontology_id), 
                                          exclude = NULL)

# If we want log normalized counts, use scuttle Not included here.
# sce <- scuttle::logNormCounts(sce)
# saveRDS(sce, "parabiosis_iSee_sce.rds")

# Incorporate UMAP, TSNE, and PCA coordinates provided by the authors
TSNE_coord <- readRDS("~/tsne_original.rds")

UMAP_coord <- readRDS("~/umap_original.rds")

pca_coord <- readRDS("../pca_original.rds")
pc50 <- pca_coord@cell.embeddings 
# We want cell.embedding which stores the coordinates for each cell in
# low-dimensional space.

reducedDim(sce, "TSNE") <- TSNE_coord # Add another component to reducedDims
reducedDim(sce, "UMAP") <- UMAP_coord
reducedDim(sce, "PCA") <- pc50 

# reorder the list
reducedDims(sce) <- reducedDims(sce)[c("PCA", "UMAP", "TSNE")] 

# Change PCA, UMAP, TSNE column names
colnames(reducedDim(sce, "UMAP")) <- c("UMAP1", "UMAP2")
colnames(reducedDim(sce, "TSNE")) <- c("TSNE1", "TSNE2")
colnames(reducedDim(sce, "PCA")) <-  
  sub("_", "", colnames(reducedDim(sce, "PCA")))

# A cell colors matching Ximerakis & Holton et al. 2023

color.map.list_All_Lin=c(
  #"OPC","OLG","OEG",
  "olivedrab4", "olivedrab3", "olivedrab1",
  #"NSC","ARP","ASC",
  "royalblue4", "steelblue4", "steelblue1",
  #"EPC","HypEPC,"TNC","CPC",
  "lightgoldenrod4", "lightgoldenrod3", "lightgoldenrod2","gold",
  #,"NRP","ImmN","GABA", DOPA", "GLUT","CHOL","NendC"
  "darkmagenta", "purple3","mediumorchid3", "violetred3", "palevioletred", 
  "violet","lightpink",
  #,"EC","PC","VSMC","Hb-VC","VLMC","ABC",
  "sienna4", "sienna3", "sienna1", "peru","peachpuff4","peachpuff3",
  #"MG","MAC","MNC","DC","NEUT","T_cell","NK", "B_Cell"
  "red4","red3","tomato3", "red1","tomato1","salmon3", "indianred2", "coral")

names(color.map.list_All_Lin) <- c("OPC","OLG","OEG",
                                 "NSC","ARP","ASC", "EPC", "HypEPC", "TNC", 
                                 "CPC", "NRP","ImmN","GABA", "DOPA", "GLUT",
                                 "CHOL", "NendC", "EC","PC","VSMC","Hb_VC",
                                 "VLMC","ABC", "MG","MAC","MNC","DC","NEUT",
                                 "T_cell","NK", "B_cell")

# All cell colors into metadata slot
metadata(sce)$cell_colors <- color.map.list_All_Lin 
sce
```

# Save `SingleCellExperiment` object

```{r}
saveRDS(sce, "~/MouseAgingData_data/parabiosis_sce_v2.rds")
```

# References

Ximerakis & Holton et al. (2023) Heterochronic parabiosis reprograms the
mouse brain transcriptome by shifting aging signatures in multiple cell
types. *Nat Aging* 3, 327--345.
<DOI:https://doi.org/10.1038/s43587-023-00373-6>.

# Session info

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