## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)

## ----echo=FALSE, paged.print=FALSE, rownames.print=FALSE----------------------
MAFtable <- read.table(system.file("extdata", "HCC_LDC.maf", package = "MesKit"), header=TRUE)
extractLines <- rbind(MAFtable[1, ], MAFtable[6600, ])
extractLines <- rbind(extractLines, MAFtable[15000, ])
data.frame(extractLines, row.names = NULL)

## ----echo=FALSE, paged.print=FALSE, rownames.print=FALSE----------------------
ccfInfo <- read.table(system.file("extdata", "HCC_LDC.ccf.tsv", package = "MesKit"), header = TRUE)
ccfInfo[1:5, ]

## ----echo=FALSE, paged.print=FALSE, rownames.print=FALSE----------------------
segInfo <- read.table(system.file("extdata", "HCC_LDC.seg.txt", package = "MesKit"), header = TRUE)
segInfo[1:5, ]

## ----eval=FALSE---------------------------------------------------------------
#  install.packages("devtools")
#  devtools::install_github("Niinleslie/MesKit")

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

## ----message=FALSE------------------------------------------------------------
library(MesKit)

## -----------------------------------------------------------------------------
maf.File <- system.file("extdata/", "HCC_LDC.maf", package = "MesKit")
ccf.File <- system.file("extdata/", "HCC_LDC.ccf.tsv", package = "MesKit")
# Maf object generation
maf <- readMaf(mafFile = maf.File, refBuild = "hg19") 
# Maf object with CCF information
maf <- readMaf(mafFile = maf.File,
               ccfFile = ccf.File,
               refBuild = "hg19")  

## ----message=FALSE, fig.align='left', fig.width=11, fig.height=6.5------------
# Driver genes of CRC collected from [IntOGen](https://www.intogen.org/search) (v.2020.2）
driverGene.file <- system.file("extdata/", "IntOGen-DriverGenes_HC.tsv", package = "MesKit")
driverGene <- as.character(read.table(driverGene.file)$V1)
mut.class <- classifyMut(maf, class =  "SP", patient.id = 'HCC8257')
head(mut.class)

## ----message=FALSE, fig.align='left', fig.width=11, fig.height=4.5------------
# specify the order of patients and samples via "patient.id" and "sampleOrder" respectively

patientOrder <- c("HCC5647", "HCC6690", "HCC6046")
sampleOrder <- list("HCC5647" = c("T1", "T4", "T5", "T3"))

plotMutProfile(
  maf,
  patient.id = patientOrder,
  sampleOrder = sampleOrder,
  class =  "SP", geneList = driverGene)

## ----message=FALSE------------------------------------------------------------
# Read segment file
segCN <- system.file("extdata", "HCC_LDC.seg.txt", package = "MesKit")
# Reading gistic output files
all.lesions <- system.file("extdata", "LIHC_all_lesions.conf_99.txt", package = "MesKit")
amp.genes <- system.file("extdata", "LIHC_amp_genes.conf_99.txt", package = "MesKit")
del.genes <- system.file("extdata", "LIHC_del_genes.conf_99.txt", package = "MesKit")
seg <- readSegment(segFile = segCN, gisticAllLesionsFile = all.lesions,
                   gisticAmpGenesFile = amp.genes, gisticDelGenesFile = del.genes)
seg$HCC8257[1:5, ]

## ---- fig.width=10, fig.align='left', fig.height=5----------------------------
plotCNA(seg, patient.id = c("HCC5647", "HCC8257", "HCC6690"))

## ----warning=FALSE, fig.width=8, fig.height=5---------------------------------
# calculate MATH score of each sample
MATH.sample <- mathScore(maf)
MATH.sample

## ----fig.height=5, fig.width=6, message=FALSE---------------------------------
AUC <- ccfAUC(maf, patient.id = 'HCC8257')
names(AUC)

## ----fig.height=5, fig.width=6, message=FALSE---------------------------------
AUC$AUC.value

## ----fig.height=5, fig.width=5.5, message=FALSE, fig.align='left'-------------
# show cumulative density plot of CCF
AUC$CCF.density.plot

## ----message=FALSE, fig.height=5.5, fig.width=9.5-----------------------------
clusterVaf <- vafCluster(maf, patient.id = 'HCC8257')
head(clusterVaf$cluster.data[, -1])
clusterPlots <- clusterVaf$cluster.plot
cowplot::plot_grid(plotlist = clusterPlots)

## ----fig.align='left', fig.width=5.5, fig.height=5, fig.asp=1.0---------------
calFst(maf, patient.id = 'HCC8257', plot = TRUE, number.cex = 10)

## ----fig.align='left', fig.width=5.5, fig.height=5, fig.asp=1.0---------------
calNeiDist(maf, patient.id = 'HCC8257', number.cex = 10)

## ----fig.align='left', fig.width=5, fig.height=5, message=FALSE, warning=FALSE----
ccf.list <- compareCCF(maf)
ccf.pairwise <- ccf.list$HCC8257[["T3-T4"]]
# compare CCF using smoothScatter
graphics::smoothScatter(matrix(c(ccf.pairwise[,3], ccf.pairwise[,4]),ncol = 2),
              xlim = c(0,1), ylim = c(0,1),
              colramp = colorRampPalette(c("white", RColorBrewer::brewer.pal(9,"BuPu"))),
              xlab = "T3", ylab = "T4")
## show driver genes
gene.idx <- which(ccf.pairwise$Hugo_Symbol %in% driverGene) 
points(ccf.pairwise[gene.idx, 3:4], cex=0.6, col=2, pch=2)
text(ccf.pairwise[gene.idx, 3:4], cex=0.7, pos=1, ccf.pairwise$Hugo_Symbol[gene.idx])
title('HCC8257', cex.main = 1.2)

## ----fig.align='left', fig.width=7, fig.height=7, fig.asp=1.0-----------------
JSI.res <- compareJSI(maf, plot = FALSE, patient.id = 'HCC8257') 
names(JSI.res)

## ----fig.align='left', fig.width=7, fig.height=7, fig.asp=1.0-----------------
# show the JSI result
JSI.res$JSI.multi
JSI.res$JSI.pair

## ----message=FALSE, warning=FALSE, fig.height=4.5, fig.width=4.5--------------
neutralResult <- testNeutral(maf, min.mut.count = 10, patient.id = 'HCC8257')
neutralResult$neutrality.metrics
neutralResult$model.fitting.plot$T3

## -----------------------------------------------------------------------------
phyloTree <- getPhyloTree(maf, patient.id = "HCC8257", method = "NJ", min.vaf = 0.06)

## ---- message=FALSE, warning=FALSE, fig.height=4, fig.width=6-----------------
tree.NJ <- getPhyloTree(maf, patient.id = 'HCC8257', method = "NJ")
tree.MP <- getPhyloTree(maf, patient.id = 'HCC8257', method = "MP")
# compare phylogenetic trees constructed by two approaches
compareTree(tree.NJ, tree.MP, plot = TRUE)

## ---- message=FALSE, warning=FALSE, fig.width=5, fig.height=5-----------------
library(org.Hs.eg.db)
library(clusterProfiler)

# Pathway enrichment analysis
HCC8257.branches <- getMutBranches(phyloTree)
# pathway enrichment for public mutated genes in patient HCC8257
HCC8257_Public <- HCC8257.branches[HCC8257.branches$Mutation_Type == "Public", ]
geneIDs = suppressMessages(bitr(HCC8257_Public$Hugo_Symbol, fromType="SYMBOL", 
                              toType=c("ENTREZID"), OrgDb="org.Hs.eg.db"))
KEGG_HCC8257_Public  = enrichKEGG(
  gene = geneIDs$ENTREZID,
  organism = 'hsa',
  keyType = 'kegg',
  pvalueCutoff = 0.05,
)
dotplot(KEGG_HCC8257_Public)

## ----message=FALSE------------------------------------------------------------
# load the genome reference
library(BSgenome.Hsapiens.UCSC.hg19)

## ---- warning = FALSE, message=FALSE------------------------------------------
mutClass <- mutTrunkBranch(phyloTree, CT = TRUE, plot = TRUE)
names(mutClass)

## ---- warning = FALSE, message=FALSE, fig.height=5, fig.width=5---------------
mutClass$mutTrunkBranch.res
mutClass$mutTrunkBranch.plot

## ---- warning = FALSE, message=FALSE, fig.height=7, fig.width=10--------------
trimatrix_HCC8257 <- triMatrix(phyloTree, withinTumor = TRUE)
fit_HCC8257 <- fitSignatures(trimatrix_HCC8257)

## ---- warning = FALSE, message=FALSE, fig.height=3, fig.width=10--------------
# Visualize the 96 trinucleodide mutational profile
plotMutSigProfile(trimatrix_HCC8257)[[1]]

## ---- fig.height=6, fig.width=10----------------------------------------------
# Compare the reconstructed mutational profile with the original mutational profile
plotMutSigProfile(fit_HCC8257)[[1]]

## ---- warning = FALSE, message=FALSE, fig.height=5, fig.width=8---------------
# Below plot shows cosine similarities between the mutational profile of each group and COSMIC signatures
library(ComplexHeatmap)
ComplexHeatmap::Heatmap(fit_HCC8257$HCC8257$cosine.similarity, name = "Cosine similarity")

## ---- fig.align='left', fig.width=12, fig.height=5, message=FALSE, warning=FALSE----
# A phylogenetic tree along with binary and CCF heatmap of mutations 
phylotree_HCC8257 <- plotPhyloTree(phyloTree)
heatmapbinary_HCC8257 <- mutHeatmap(maf, use.ccf = FALSE, 
                                    patient.id = "HCC8257", min.vaf = 0.06)
heatmapCCF_HCC8257 <- mutHeatmap(maf, use.ccf = TRUE, 
                                 patient.id = "HCC8257", min.vaf = 0.06)
cowplot::plot_grid(phylotree_HCC8257, heatmapbinary_HCC8257, 
                   heatmapCCF_HCC8257, nrow = 1, rel_widths = c(1.3, 1, 1))

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

