## ----setup, echo=FALSE--------------------------------------------------------
suppressWarnings(library(knitr))

opts_chunk$set(tidy = FALSE, message = FALSE, warning = FALSE)

## ----getPackage, eval=FALSE---------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE)) {
#   install.packages("BiocManager")
# }
# 
# BiocManager::install("iModMix")

## ----getPackageDevel, eval=FALSE----------------------------------------------
# devtools::install_github("biodatalab/iModMix")

## ----Load, message=FALSE------------------------------------------------------
library(iModMix)

## ----launchApp, eval=FALSE----------------------------------------------------
# iModMix::run_app()

## ----upload1------------------------------------------------------------------
# Load the package
library(iModMix)

# Get the path to the expression data file
pathMetabExp <- system.file("Example_data/ccRCC4_Data/Metab_exp.rds", package = "iModMix")

# Load the expression data
dataExp1 <- readRDS(pathMetabExp)

# Check the expression data
dataExp1[1:5, 1:5]

# Get the path to the Metadata file
pathMetadata <- system.file("Example_data/ccRCC4_Data/Metadata.rds", package = "iModMix")

# Load the Metadata
metadata <- readRDS(pathMetadata)

# Check the Metadata
head(metadata)

## ----Preprocess---------------------------------------------------------------
# Preprocess of data for iModMix upload
loadData1 <- fctLoadData(dataExp1)
loadData1[1:5, 1:5]

## ----partial_cors1------------------------------------------------------------
# Perform Partial correlation
parcorData1 <- fctPartialCors(loadData1, rho = 0.25)
parcorData1[1:5, 1:5]

## ----hierarchical_cluster1----------------------------------------------------
# Perform hierarchical clustering
hcData1 <- fctHierarchicalCluster(parcorMat = parcorData1, tom = TRUE, minModuleSize = 10)

hcClu <- hcData1$hclustTree
hcMod <- as.matrix(hcData1$dynamicMods_numeric)
WGCNA::plotDendroAndColors(
  dendro = hcClu,
  colors = hcMod,
  dendroLabels = FALSE,
  hang = 0.03,
  addGuide = TRUE,
  guideHang = 0.05,
  groupLabels = "Modules",
  main = "Feature dendrogram and module assignments"
)

## ----cluster_assignments1-----------------------------------------------------
# Perform cluster assignments
clusterAssigData1 <- fctClusterAssignments(as.data.frame(hcData1$cluster_assignments))
head(clusterAssigData1)

## ----Eigengenes11-------------------------------------------------------------
# Obtain Eigenfeatures
eigenData1 <- fctEigengenes(loadData1, hcData1$cluster_assignments[, 3])
eigengenesData1 <- eigenData1$module_eigenmetab_Me
eigengenesData1[1:5, 1:5]

## ----upload2------------------------------------------------------------------
# Get the path to the expression data file
pathRNAexp <- system.file("Example_data/ccRCC4_Data/RNA_exp.rds", package = "iModMix")

# Load the expression data
dataExp2 <- readRDS(pathRNAexp)
dataExp2 <- dataExp2[1:1000, ]

# Check the expression data
dataExp2[1:5, 1:5]

# Preprocessing of data for iModMix upload
loadData2 <- fctLoadData(dataExp2)

## ----partial_cors2------------------------------------------------------------
# Partial correlation
parcorData2 <- fctPartialCors(loadData2, rho = 0.25)
parcorData2[1:5, 1:5]

## ----hierarchical_cluster2----------------------------------------------------
# Perform hierarchical clustering
hcData2 <- fctHierarchicalCluster(parcorMat = parcorData2, tom = TRUE, minModuleSize = 10)

# Access the hierarchical clustering tree and module assignments
hcClu2 <- hcData2$hclustTree
hcMod2 <- as.matrix(hcData2$dynamicMods_numeric)

# Plot the dendrogram
WGCNA::plotDendroAndColors(
  dendro = hcClu2,
  colors = hcMod2,
  dendroLabels = FALSE,
  hang = 0.03,
  addGuide = TRUE,
  guideHang = 0.05,
  groupLabels = "Modules",
  main = "Feature dendrogram and module assignments"
)

## ----cluster_assignments2-----------------------------------------------------
# Perform cluster assignment
clusterAssigData2 <- fctClusterAssignments(as.data.frame(hcData2$cluster_assignments))
eigenData2 <- fctEigengenes(loadData2, hcData2$cluster_assignments[, 3])
eigengenesData2 <- eigenData2$module_eigenmetab_Me
eigengenesData2[1:5, 1:5]

## ----perform_classification2--------------------------------------------------
# Perform Classification
ClassificationData <- fctPerformClassification(
  eigengeneData = eigengenesData1,
  metadata = metadata,
  phenotypeVariable = "TN",
  significanceThreshold = 0.09
)

ClassificationData$result[1:10, ]

# Plot BoxPlot
selectedVariable <- "TN"
levels <- unique(metadata[[selectedVariable]])
classLabel <- paste(levels, collapse = " vs ")
plot <- ClassificationData$plots[[1]]
plot <- plot +
  ggplot2::labs(
    title = classLabel, fill = as.factor(levels),
    x = "Variables",
    y = "Class"
  ) +
  ggplot2::theme(
    axis.text.x = ggplot2::element_text(angle = 90, hjust = 1)
  )
plot

## ----Multiomics---------------------------------------------------------------
# Summarize into list the different eigenfeatures
eigengenesList <- list(eigengenesData1, eigengenesData2)
clusterList <- list(clusterAssigData1, clusterAssigData2)
IntegrationData1Data2 <- fctModulesCorrelation(eigengenesList, clusterList, threshold = 0.6)
TopCorrelations <- IntegrationData1Data2[["Top_cor_Prot_metab"]]
head(TopCorrelations)

# Plot correlation
CorrelationPlot <- IntegrationData1Data2$Correlation_Plot
hist(CorrelationPlot[[1]], main = "Correlation: Data 1 / Data 2 ")

# Plot Network
nodes <- as.data.frame(IntegrationData1Data2$nodes)
edges <- as.data.frame(IntegrationData1Data2$edges)
n <- IntegrationData1Data2$n

shapes <- c("diamond", "triangle", "dot")
colors <- c("orange", "darkgreen", "darkblue")

network <- visNetwork::visNetwork(nodes = nodes, edges = edges, width = "100%", height = "800px")
network <- visNetwork::visLegend(network,
  useGroups = FALSE,
  addNodes = data.frame(
    label = paste0("Data", 1:n, " Modules"),
    shape = shapes[1:n], color = colors[1:n]
  ),
  addEdges = data.frame(label = "Correlation", shape = "line", length = 200, color = "darkgreen")
)
network <- visNetwork::visInteraction(network, navigationButtons = TRUE)
network

## ----enrichmentAnalysisCode, eval = FALSE-------------------------------------
# # Perform enrichment analysis per module
# selectedDatabase <- "GO_Biological_Process_2023"
# clusterAssignmentsData2Enrich <- fctAssignmentGenesEnrichr(clusterAssignmentsProtGenes = clusterAssigData2, database = selectedDatabase)

## ----summarizedExperimentExample----------------------------------------------
# Load required library
library(SummarizedExperiment)

# Assuming:
# - 'dataExp1' has features in rows and samples in columns
# - 'Feature_ID' is the first column of dataExp1
# - 'metadata' has sample information with 'Sample' column matching column names of dataExp1 (except Feature_ID)

# Create SummarizedExperiment object
se <- fctiModMix2SE(dataExp1, metadata)

# Check structure
se

## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()

