## ---- echo=FALSE, results="hide", message=FALSE-------------------------------
knitr::opts_chunk$set(error=FALSE, message=FALSE, warning=FALSE,
    dev="jpeg", dpi = 72, fig.width = 4.5, fig.height = 3.5)
library(BiocStyle)

## ---- eval=FALSE--------------------------------------------------------------
#  # Install BiocManager if needed
#  if (!requireNamespace("BiocManager", quietly = TRUE))
#      install.packages("BiocManager")
#  
#  # Install dittoSeq
#  BiocManager::install("dittoSeq")

## -----------------------------------------------------------------------------
library(dittoSeq)
library(scRNAseq)
library(SingleCellExperiment)
library(Seurat)
# Download data
sce <- BaronPancreasData()
# Trim to only 5 of the celltypes for simplicity of vignette
sce <- sce[,meta("label",sce) %in% c(
    "acinar", "endothelial", "gamma", "delta", "ductal")]

## -----------------------------------------------------------------------------
# Make Seurat and grab metadata
seurat <- CreateSeuratObject(counts(sce))
seurat <- AddMetaData(seurat, sce$label, col.name = "celltype")
seurat <- AddMetaData(seurat, sce$donor, col.name = "Sample")
seurat <- AddMetaData(seurat,
                      PercentageFeatureSet(seurat, pattern = "^MT"),
                      col.name = "percent.mt")
# Basic Seurat workflow (possibly outdated, but fine for this vignette)
seurat <- NormalizeData(seurat, verbose = FALSE)
seurat <- FindVariableFeatures(object = seurat, verbose = FALSE)
seurat <- ScaleData(object = seurat, verbose = FALSE)
seurat <- RunPCA(object = seurat, verbose = FALSE)
seurat <- RunTSNE(object = seurat)
seurat <- FindNeighbors(object = seurat, verbose = FALSE)
seurat <- FindClusters(object = seurat, verbose = FALSE)

## -----------------------------------------------------------------------------
# Grab PCA, TSNE, clustering, log-norm data, and metadata to sce

# sce <- as.SingleCellExperiment(seurat)
# At the time this vignette was made, the above function gave warnings

# So... manual method
sce <- addDimReduction(
  sce, embeddings = Embeddings(seurat, reduction = "pca"), name = "PCA")
sce <- addDimReduction(
  sce, embeddings = Embeddings(seurat, reduction = "tsne"), name = "TSNE")
sce$idents <- seurat$seurat_clusters
assay(sce, "logcounts") <- GetAssayData(seurat)
sce$percent.mt <- seurat$percent.mt
sce$celltype <- seurat$celltype
sce$Sample <- seurat$Sample

## -----------------------------------------------------------------------------
dittoDimPlot(seurat, "Sample")
dittoPlot(seurat, "ENO1", group.by = "celltype")
dittoBarPlot(sce, "celltype", group.by = "Sample")

## -----------------------------------------------------------------------------
# First, lets make some mock expression and conditions data
exp <- matrix(rpois(20000, 5), ncol=20)
colnames(exp) <- paste0("sample", seq_len(ncol(exp)))
rownames(exp) <- paste0("gene", seq_len(nrow(exp)))
logexp <- logexp <- log2(exp + 1)

conditions <- factor(rep(1:4, 5))
sex <- c(rep("M", 9), rep("F", 11))

## -----------------------------------------------------------------------------
# Import
myRNA <- importDittoBulk(
    # x can be a DGEList, a DESeqDataSet, a SummarizedExperiment,
    #   or a list of data matrices
    x = list(counts = exp,
             logcounts = logexp),
    # Optional inputs:
    #   For adding metadata
    metadata = data.frame(conditions = conditions,
                          sex = sex),
    #   For adding dimensionality reductions
    reductions = list(pca = matrix(rnorm(20000), nrow=20)))

# Add metadata (metadata can alternatively be added in this way)
myRNA$conditions <- conditions
myRNA$sex <- sex

# Add dimensionality reductions (can alternatively be added this way)
# (We aren't actually calculating PCA here.)
myRNA <- addDimReduction(
    object = myRNA,
    embeddings = matrix(rnorm(20000), nrow=20),
    name = "pca",
    key = "PC")

## -----------------------------------------------------------------------------
# Now making plots operates the exact same way as for single-cell data
dittoDimPlot(myRNA, "sex", size = 3, do.ellipse = TRUE)
dittoBarPlot(myRNA, "sex", group.by = "conditions")
dittoBoxPlot(myRNA, "gene1", group.by = "sex")
dittoHeatmap(myRNA, getGenes(myRNA)[1:10],
    annot.by = c("conditions", "sex"))

## -----------------------------------------------------------------------------
# Retrieve all metadata slot names
getMetas(seurat)
# Query for the presence of a metadata slot
isMeta("nCount_RNA", seurat)
# Retrieve metadata values:
meta("celltype", seurat)[1:10]
# Retrieve unique values of a metadata
metaLevels("celltype", seurat)

## -----------------------------------------------------------------------------
# Retrieve all gene names
getGenes(seurat)[1:10]
# Query for the presence of a gene(s)
isGene("CD3E", seurat)
isGene(c("CD3E","ENO1","INS","non-gene"), seurat, return.values = TRUE)
# Retrieve gene expression values:
gene("ENO1", seurat)[1:10]

## -----------------------------------------------------------------------------
# Retrieve all dimensionality reductions
getReductions(seurat)

## -----------------------------------------------------------------------------
# Getter
isBulk(sce)
isBulk(myRNA)

# Setter
mock_bulk <- setBulk(sce) # to bulk
mock_sc <- setBulk(myRNA, set = FALSE) # to single-cell

## ---- results = "hold"--------------------------------------------------------
dittoDimPlot(seurat, "celltype")
dittoDimPlot(sce, "ENO1")

## ---- results = "hold"--------------------------------------------------------
dittoScatterPlot(
    object = sce,
    x.var = "ENO1", y.var = "INS",
    color.var = "celltype", shape.by = "Sample",
    size = 3)
dittoScatterPlot(
    object = seurat,
    x.var = "nCount_RNA", y.var = "nFeature_RNA",
    color.var = "percent.mt",
    size = 3)

## -----------------------------------------------------------------------------
dittoDimPlot(seurat, "ident",
             do.label = TRUE, labels.repel = FALSE)
dittoDimPlot(seurat, "ident",
             add.trajectory.lineages = list(
                 c("3","4","11","8","2","10"),
                 c("3","9","6","12"),
                 c("3","9","7", "1"),
                 c("3","9","7","5")),
             trajectory.cluster.meta = "ident")

## ---- results = "hold"--------------------------------------------------------
dittoPlot(seurat, "ENO1", group.by = "celltype",
    plots = c("vlnplot", "jitter"))
dittoRidgePlot(sce, "ENO1", group.by = "celltype")
dittoBoxPlot(seurat, "ENO1", group.by = "celltype")

## -----------------------------------------------------------------------------
dittoPlot(seurat, "ENO1", group.by = "celltype",
    plots = c("vlnplot", "jitter", "boxplot"),
    # change the color and size of jitter points
    jitter.color = "blue", jitter.size = 0.5,
    # change the outline color and width, and remove the fill of boxplots
    boxplot.color = "white", boxplot.width = 0.1,
    boxplot.fill = FALSE,
    # change how the violinplot widths are normalized across groups
    vlnplot.scaling = "count"
    )

## ---- results = "hold"--------------------------------------------------------
dittoBarPlot(seurat, "celltype", group.by = "Sample")
dittoBarPlot(seurat, "ident", group.by = "Sample",
    scale = "count")

## ---- results = "hold"--------------------------------------------------------
# Pick Genes
genes <- c("SST", "REG1A", "PPY", "INS", "CELA3A", "PRSS2", "CTRB1",
    "CPA1", "CTRB2" , "REG3A", "REG1B", "PRSS1", "GCG", "CPB1",
    "SPINK1", "CELA3B", "CLPS", "OLFM4", "ACTG1", "FTL")

# Annotating and ordering cells by some meaningful feature(s):
dittoHeatmap(seurat, genes,
    annot.by = c("celltype", "Sample"))
dittoHeatmap(seurat, genes,
    annot.by = c("celltype", "Sample"),
    order.by = "Sample")

## -----------------------------------------------------------------------------
# Add annotations
dittoHeatmap(seurat, genes,
    annot.by = c("celltype", "Sample"),
    scaled.to.max = TRUE,
    show_colnames = FALSE,
    show_rownames = FALSE)

## -----------------------------------------------------------------------------
# Highlight certain genes
dittoHeatmap(seurat, genes,
    annot.by = c("celltype", "Sample"),
    highlight.genes = genes[1:3])

## -----------------------------------------------------------------------------
# Idents(seurat) <- "celltype"
# delta.marker.table <- FindMarkers(seurat, ident.1 = "delta")
# delta.genes <- rownames(delta.marker.table)[1:20]
# Idents(seurat) <- "seurat_clusters"

delta.genes <- c("SST", "RBP4", "PCSK1", "CPE", "GPX3",
    "NLRP1", "PPP1R1A", "PCP4", "CHGB", "DHRS2", "LEPR", 
    "PTPRN", "BEX1", "SCGN", "PCSK1N", "SCG5", "UCHL1",
    "CHGA", "GAD2", "SEC11C")

## -----------------------------------------------------------------------------
multi_dittoPlot(seurat, delta.genes[1:6], group.by = "celltype",
    vlnplot.lineweight = 0.2, jitter.size = 0.3)
dittoPlotVarsAcrossGroups(seurat, delta.genes, group.by = "celltype",
    main = "Delta-cell Markers")

## ---- results = "hold"--------------------------------------------------------
multi_dittoDimPlot(seurat, delta.genes[1:6])
multi_dittoDimPlotVaryCells(seurat, delta.genes[1],
    vary.cells.meta = "celltype")
multi_dittoDimPlotVaryCells(seurat, "celltype",
    vary.cells.meta = "celltype")

## -----------------------------------------------------------------------------
# Original
dittoBarPlot(seurat, "celltype", group.by = "Sample", scale = "count")

# String method, first 10 cells
dittoBarPlot(seurat, "celltype", group.by = "Sample", scale = "count",
    cells.use = colnames(seurat)[1:10])

# Logical method, only acinar cells
dittoBarPlot(seurat, "celltype", group.by = "Sample", scale = "count",
    cells.use = meta("celltype", seurat) == "acinar")

## -----------------------------------------------------------------------------
dittoDimPlot(seurat, "celltype", split.by = "Sample")
dittoDimPlot(seurat, "ENO1", split.by = c("Sample", "celltype"))

## -----------------------------------------------------------------------------
dittoBarPlot(seurat, "celltype", group.by = "Sample",
    main = "Encounters",
    sub = "By Type",
    xlab = NULL, # NULL = remove
    ylab = "Generation 1",
    x.labels = c("Ash", "Misty", "Jessie", "James"),
    legend.title = "Types",
    var.labels.rename = c("Fire", "Water", "Grass", "Electric", "Psychic"),
    x.labels.rotate = FALSE)

## ---- results="hold"----------------------------------------------------------
# original - discrete
dittoDimPlot(seurat, "celltype")
# swapped colors
dittoDimPlot(seurat, "celltype",
    colors = 5:1)
# different colors
dittoDimPlot(seurat, "celltype",
    color.panel = c("red", "orange", "purple", "yellow", "skyblue"))

## ---- results="hold"----------------------------------------------------------
# original - expression
dittoDimPlot(seurat, "INS")
# different colors
dittoDimPlot(seurat, "INS",
    max.color = "red", min.color = "gray90")

## -----------------------------------------------------------------------------
dittoBarPlot(seurat, "celltype", group.by = "Sample",
    data.out = TRUE)

## -----------------------------------------------------------------------------
dittoHeatmap(seurat, c("SST","CPE","GPX3"), cells.use = colnames(seurat)[1:5],
    data.out = TRUE)

## ---- eval = FALSE------------------------------------------------------------
#  # These can be finicky to render in knitting, but still, example code:
#  dittoDimPlot(seurat, "INS",
#      do.hover = TRUE,
#      hover.data = c("celltype", "Sample", "ENO1", "ident", "nCount_RNA"))
#  dittoPlot(seurat, "INS", group.by = "celltype", plots = c("vlnplot", "jitter"),
#      do.hover = TRUE,
#      hover.data = c("celltype", "Sample", "ENO1", "ident", "nCount_RNA"))

## ---- eval = FALSE------------------------------------------------------------
#  # These can be finicky to render in knitting, but still, example code:
#  dittoBarPlot(seurat, "celltype", group.by = "Sample",
#      do.hover = TRUE)
#  dittoPlotVarsAcrossGroups(seurat, delta.genes, group.by = "celltype",
#      do.hover = TRUE)

## -----------------------------------------------------------------------------
sessionInfo()

