## ----knitr, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    dev = "ragg_png"
)

## ----loadLibraries, results = "hide", message = FALSE, warning = FALSE--------
library(tidyverse) # needed for data wrangling (or use base R instead)
library(scRepertoire) # needed for downstream analysis

## ----githubInstall, eval = FALSE----------------------------------------------
# if (!require("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# 
# BiocManager::install("ECLIPSE")

## ----loadECLIPSE, eval = FALSE------------------------------------------------
# library(ECLIPSE)

## ----githubInstallDevel, eval = FALSE-----------------------------------------
# remotes::install_github("eburns10/ECLIPSE")

## ----loadECLIPSEDevel---------------------------------------------------------
library(ECLIPSE)

## ----loadKnitr, echo = FALSE, message = FALSE---------------------------------
require(knitr)

## ----loadSeuratObject---------------------------------------------------------
data("vignette_object", package = "ECLIPSE")

## ----getFolderPath------------------------------------------------------------
# Finding where the vignette data for ECLIPSE is stored
vignette_dir <- system.file("extdata/vignette", package = "ECLIPSE")

# Generates the vector of folder paths and excludes the current directory
tcr_folder_paths <- list.dirs(path = vignette_dir, full.names = TRUE)[-1]
print(tcr_folder_paths)

## ----getFilePath--------------------------------------------------------------
# Generates the vector of file paths
contig_paths <- list.files(path = vignette_dir,
                           pattern = "all_contig", 
                           recursive = TRUE, 
                           full.names = TRUE)
contig_paths

## ----checkBarcodes------------------------------------------------------------
# Existing cell barcodes. They aren't the original!
head(rownames(vignette_object[[]]))

## ----makeBarcodeColumn--------------------------------------------------------
# Making a column with these barcodes where there is no prefix
vignette_object$cell_barcode <- str_replace(rownames(vignette_object[[]]),
                                            pattern = "^.*_", 
                                            replacement = "")
head(vignette_object$cell_barcode) %>% as.vector()

## ----checkContigPaths---------------------------------------------------------
# Looking at the vector of file_paths
contig_paths

## ----makeBatchColumn----------------------------------------------------------
# Since normal tissue from sample 15 is first (S15N), it is 1.
# Tumor tissue from 15 is next (S15T), so it is 2, etc...
vignette_object[[]] <- vignette_object[[]] %>% 
                       mutate(index = case_when(
                                                Sample == "D3B" ~ 1,
                                                Sample == "D3L" ~ 2,
                                                Sample == "D5B" ~ 3,
                                                Sample == "D5L" ~ 4))
    
# Checking the column
table(vignette_object$index)

## ----checkDonorColumn---------------------------------------------------------
# Show donor column
table(vignette_object$donor)

## ----checkSampleColumn--------------------------------------------------------
# Show Sample column
table(vignette_object$Sample)

## ----runEclipseFolder---------------------------------------------------------
# Option 1: Running with paths of folders containing contigs
object_after_ECLIPSE <- ECLIPSE(contig_type = "all",
                                contig_folder_paths = tcr_folder_paths,
                                seurat_object = vignette_object,
                                batch = "index",
                                donor = "donor",
                                group = "Sample",
                                original_barcode = "cell_barcode",
                                verbose = FALSE,
                                format = "None")

## ----runEclipseFile, fig.alt = "Plot from ECLIPSE"----------------------------
# Option 2: Running with contig paths
object_after_ECLIPSE <- ECLIPSE(contig_type = "manual",
                                contig_file_paths = contig_paths,
                                seurat_object = vignette_object,
                                batch = "index",
                                donor = "donor",
                                group = "Sample",
                                original_barcode = "cell_barcode",
                                format = "None")

## ----checkClonotypes----------------------------------------------------------
# Final ECLIPSE clonotype
head(object_after_ECLIPSE$CTaa) %>% as.vector()

## ----checkTraditionalClonotypes-----------------------------------------------
# Clonotype from traditional analysis
head(object_after_ECLIPSE$scR_CTaa) %>% as.vector()

## ----runArtifactDetect, fig.alt = "Plots from tcrArtifactDetect"--------------
object_after_ECLIPSE <- tcrArtifactDetect(object_after_ECLIPSE,
                                          singleChainLimit = 2,
                                          totalChainLimit = 4)

## ----runCompareClonotypes, fig.alt = "Plot showing clone sharing"-------------
clonalCompare(object_after_ECLIPSE,
              top.clones = 5,
              graph = "alluvial",
              cloneCall = "aa",
              group.by = "Sample") +
    theme(legend.position = "none")


## ----runClonalHomeostasis, fig.alt = "Plot showing clone sizes"---------------
clonalHomeostasis(object_after_ECLIPSE,
                  cloneCall = "aa",
                  group.by = "Sample")

## ----runClonalDiversity, fig.alt = "Plot showing TCR diversity"---------------
clonalDiversity(object_after_ECLIPSE,
                metric = "shannon",
                cloneCall = "aa",
                group.by = "Sample")

## ----loadScePackage, results = "hide", message = FALSE, warning = FALSE-------
library(SingleCellExperiment)
library(Seurat)

## ----makeSCE, echo = FALSE, results = "hide", message = FALSE, warning = FALSE----
### Make a SingleCellExperiment object that mirrors our vignette object
sce_obj <- as.SingleCellExperiment(vignette_object)

## ----run sceECLIPSE-----------------------------------------------------------
sce_after_ECLIPSE <- sceECLIPSE(sce_object = sce_obj,
                                contig_type = "all",
                                contig_folder_paths = tcr_folder_paths,
                                batch = "index",
                                donor = "donor",
                                group = "Sample",
                                original_barcode = "cell_barcode",
                                verbose = TRUE,
                                format = "None")

## ----checkColData-------------------------------------------------------------
### Check the original columns in colData
colnames(colData(sce_obj))

### Check that correct columns are added to colData
colnames(colData(sce_after_ECLIPSE))

## ----makeContigs--------------------------------------------------------------
postqc_contigs <- ECLIPSE(contig_type = "all",
                          contig_folder_paths = tcr_folder_paths,
                          seurat_object = vignette_object,
                          batch = "index",
                          donor = "donor",
                          group = "Sample",
                          original_barcode = "cell_barcode",
                          verbose = FALSE,
                          returnFilteredContigs = TRUE,
                          format = "None")

## ----runFindThreeChainClones--------------------------------------------------
d3_contigs <- postqc_contigs %>% filter(donor == "D3")

three_chain_clones <- findThreeChainClones(d3_contigs,
                                           chain = "a",
                                           mode = "show",
                                           printStats = TRUE)

## ----getOutput1---------------------------------------------------------------
three_chain_clones[[1]]

## ----getOutput2---------------------------------------------------------------
three_chain_clones[[2]]

## ----makeArgsTable, echo = FALSE----------------------------------------------
args <- c("`verbose`",
            "`returnFilteredContigs`",
            "`allowDoubleChains`",
            "`combineTcrArgs`",
            "`detailedEclipseStats`",
            "`format`")

descriptions <- c(
    paste(
        "By default `TRUE`. Prints stats such as QC filtering efficacy,",
        "how many clones were called with 3 chains, and final percentages",
        "of cells with a TCR called"
    ),
    paste(
        "By default `FALSE`. `TRUE` would return the contigs after",
        "QC filtering"
    ),
    paste(
        "By default `\"both\"`, whereby clones can have 2 TCRα or",
        "TCRβ chains. If `\"alpha\"` or `\"beta\"` is provided, only",
        "clones with 2 of that type will be permitted. If `\"neither\"` is", 
        "provided, then only clones with 2 chains will be called"
    ),
    paste(
        "A list that determines how `scRepertoire::combineTCR()` is called.",
        "As `ECLIPSE` runs `combineTCR/combineExpression` to allow users to",
        "combine the predicted `ECLIPSE` clonotype with a",
        "traditionally-defined clonotype, this tells which arguments",
        "`combineTCR` should be run with. Specifically, it tells the 4",
        "arguments 1) `removeNA`, 2) `removeMulti`, 3) `filterMulti`, and 4)", 
        "`filterNonproductive` in that order. If `ECLIPSE` cannot call a",
        "clonotype with high accuracy, the clonal annotation from this will",
        "be used as the final clonotype. By default, this is",
        "`list(FALSE, FALSE, FALSE, TRUE)`, which calls `combineTCR` with its",
        "default arguments (i.e. no non-productive contigs are retained but",
        "clones with 1 TCR chain or >2 are allowed)"
    ),
    paste(
        "By default `FALSE`. This adds information about the EM algorithm",
        "assignment to the Seurat object (e.g. what proportion of the cell",
        "was assigned to the clone listed, etc...)"
    ),
    paste(
        "By default `\"Blank\"`. This tells how missing data is stored in", 
        "contig files. Typically this is `\"\"` so `\"Blank\"` should be",
        "specified, however older versions of Cell Ranger use `\"None\"`",
        "instead. If this is the case, please provide `\"None\"` here"
    )
)

argsTable <- data.frame("Argument" = args,
                        "Description" = descriptions)
kable(argsTable, caption = "Additional arguments for the ECLIPSE function")

## ----makeColsTable, echo = FALSE----------------------------------------------
cols <- c("`highConfChains`",
            paste("`scR_CTgene`, `scR_CTnt`, `scR_CTaa`, `scR_CTstrict`,",
                "`scR_conalProportion`, `scR_clonalFrequency`,",
                "`scR_cloneSize`"),
            "`cloneCallSource`",
            "`CTaa`, `clonalProportion`, `clonalFrequency`, `cloneSize`",
            "`cell_unconventional_subset`, `clone_unconventional_subset`",
           "`EM_max_prop`, `EM_2ndmax_prop`, `EM_max_2ndmax_ratio`")

descriptions <- c(
    paste("all TCR chains that were sequenced in the cell and passed QC",
        "filtering by `ECLIPSE`. Helpful to compare to final clone (`CTaa`)",
        "used for analysis"),
    paste("columns added by `scRepertoire::combineExpression`, see",
        BiocStyle::Biocpkg("scRepertoire"),
        "documentation for details. These",
        "provide information about the cell if it was called with",
        BiocStyle::Biocpkg("scRepertoire"),
        "and can be useful in comparing to the final clone",
        "(`CTaa`) used for analysis. Please note the \"scR_\" prefix is added",
        "so ECLIPSE can add other columns with the same name that can",
        "interact with scRepertoire"),
    paste("whether the final clonotype list (in `CTaa`) is from",
        "the prediction of ",
        BiocStyle::Biocpkg("VDJdive"),
        "or from traditional analysis from",
        BiocStyle::Biocpkg("scRepertoire")),
    paste("columns in the style of what would be added by",
        "`scRepertoire:::combineExpression`. However, `CTaa` here stores",
        "the final clonotype of the cell as predicted by `ECLIPSE`"),
    paste("`cell_unconventional_subset` tells if the chains detected suggest",
        "the cell is a iNKT or MAIT cell. `clone_unconventional_subset` gives",
        "similar information, but uses the final clonotype of the cell",
        "instead of what chains were detected in that particular cell (and",
        "therefore will capture more cells as being a iNKT or MAIT cell). For",
        "both of these columns, `ECLIPSE` searches for 3 subsets: 1) iNKT",
        "cells (must have TRAV10 + TRAJ18 + TRBV25-1), 2) conventional MAIT",
        "cells (must have TRAV1-2 + TRAJ33), and 3) unconventional MAIT cells",
        "(must have TRAV1-2 + TRAJ12 or TRAV1-2 + TRAJ20. Please note that",
        "these are for human samples only, murine T cells use different gene",
        "segments that are not searched for by `ECLIPSE`"),
    paste("the proportion of the cell assigned by the EM algorithm to the",
          "most and 2nd most likely clone. The ratio of these two proportions",
          "(biggest/2nd biggest) is also provided. These columns are only",
          "included if `detailedEclipseStats == TRUE`")
)

colsTable <- data.frame("Column" = cols,
                        "Description" = descriptions)

kable(colsTable, caption = "Columns made by the ECLIPSE function")

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

