---
title: "Demultiplexing HTOs"
author: Anushka Gupta
date: February 16th 2021
---

# This notebook is for demultiplexing scRNA-seq dataset of white and brown adipocytes that were pooled using Hashtagged antibodies (HTOs). HTO assignment could be found in Table S1A.   

```{r setup}
knitr::opts_knit$set(root.dir = '~/Desktop/scRNA-seq_snRNA-seq_adipocyte_lineages/')
```

```{r}
# Load libraries
library(Seurat) # v4.0.0
library(Matrix)

# Load umi-count-matrices for HTOs and genes
load(file = "rdata/umi.count.hto.rds")
load(file = "rdata/umi.count.preadipocytes.rds")

# Make barcode structure in umi.count.hto similar to umi.count.preadipocytes
colnames(mat_HTO)=paste(colnames(mat_HTO),"1",sep="-")

# Select cell barcodes detected in both umi.count.preadipocytes and umi.count.hto 
# Subset umi.count.preadipocytes and umi.count.hto counts by joint cell barcodes
joint.bcs = intersect(colnames(mat_genes), colnames(mat_HTO))
mat_genes = mat_genes[, joint.bcs]
mat_HTO = as.matrix(mat_HTO[, joint.bcs])

# Setup Seurat object with umi.count.preadipocytes and follow steps mentioned in https://satijalab.org/seurat/archive/v3.1/hashing_vignette.html
hashtag = CreateSeuratObject(counts = mat_genes)
hashtag = NormalizeData(hashtag)
hashtag = FindVariableFeatures(hashtag, selection.method = "mean.var.plot")
hashtag = ScaleData(hashtag, features = VariableFeatures(hashtag))

# Add umi.count.hto data as a new assay independent from RNA
hashtag[["HTO"]] = CreateAssayObject(counts = mat_HTO)
hashtag = NormalizeData(hashtag, assay = "HTO", normalization.method = "CLR")

# Demultiplex cells based on HTO enrichment
hashtag = HTODemux(hashtag, assay = "HTO", positive.quantile = 0.99)
table(hashtag$HTO_classification.global)
Idents(hashtag) = "HTO_classification.global"
HTOHeatmap(hashtag, assay = "HTO")

# Output barcodes as white or brown preadipocytes
# HTO_251 and 252 are brown preadipocytes and HTO_253 and 254 are white preadipocytes
WAT.barcodes=rownames(hashtag@meta.data)[hashtag@meta.data$hash.ID=="HTO-253" | hashtag@meta.data$hash.ID=="HTO-254"]
BAT.barcodes=rownames(hashtag@meta.data)[hashtag@meta.data$hash.ID=="HTO-251" | hashtag@meta.data$hash.ID=="HTO-252"]

# Export singlet barcodes annotated as white or brown after demultiplexing
save(WAT.barcodes,file="rdata/barcodes.post.demultiplexing.white.rds")
save(BAT.barcodes,file="rdata/barcodes.post.demultiplexing.brown.rds")
```

