# -------------------------------------------------------------------------
# Create an example spatial dataset 4 scigenex ----------------------------
# -------------------------------------------------------------------------

# Loading libraries  ------------------------------------------------------

library(qlcMatrix)
library(Matrix)
library(tidyverse)
library(biomaRt)
library(Seurat)
library(SeuratObject)
library(patchwork)
library(ggstar)
library(enrichplot)
library(ggpubr)
library(stringr)
library(grid)
library(gridExtra)
library(xlsx)
library(devtools)
library(usethis)

# Install  ----------------------------------------------------------------
devtools::install_github("dputhier/scigenex@fd3eca3751ab9d774e179a4fc9e7f8d96b769716")
library(scigenex)
detach("package:scigenex", unload = T)
library(scigenex)
scigenex::set_verbosity(3)


# Downloading files  ------------------------------------------------------

DATA_PATH <- file.path(path.expand('~'), "Documents", "ST_data", "V1_Human_Lymph_Node")
dir.create(DATA_PATH, recursive = TRUE, showWarnings = F)
setwd(DATA_PATH)
           
h5_url <- "https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Human_Lymph_Node/V1_Human_Lymph_Node_filtered_feature_bc_matrix.h5"
download.file(h5_url, destfile = "V1_Human_Lymph_Node_filtered_feature_bc_matrix.h5")
spatial_img <- "https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Human_Lymph_Node/V1_Human_Lymph_Node_spatial.tar.gz"
download.file(spatial_img, destfile = "V1_Human_Lymph_Node_spatial.tar.gz")
untar("V1_Human_Lymph_Node_spatial.tar.gz")

# Creating a Seurat Obj  --------------------------------------------------

dir()
seurat_obj <- Seurat::Load10X_Spatial(filename = "V1_Human_Lymph_Node_filtered_feature_bc_matrix.h5", data.dir = DATA_PATH)
Seurat::SpatialFeaturePlot(seurat_obj, features = "nCount_Spatial")
seurat_obj <- NormalizeData(seurat_obj, normalization.method = "LogNormalize")
seurat_obj <- ScaleData(seurat_obj)
seurat_obj <- FindVariableFeatures(seurat_obj)
seurat_obj <- RunPCA(seurat_obj, assay = "Spatial", verbose = FALSE)
seurat_obj <- FindNeighbors(seurat_obj, reduction = "pca", dims = 1:20)
seurat_obj <- FindClusters(seurat_obj, resolution = 0.9)
seurat_obj <- RunUMAP(seurat_obj, reduction = "pca", dims = 1:20)
DimPlot(seurat_obj, reduction = "umap", label = TRUE)
SpatialDimPlot(seurat_obj, label = TRUE, label.size = 3, pt.size.factor = 1.4)

# Select Genes with scigenex ----------------------------------------------

res <- select_genes(data=seurat_obj,
                    distance_method="pearson",
                    row_sum = 20)

gc <- gene_clustering(res, keep_nn = F, inflation = 2.2, threads = 4)
gcs <- filter_cluster_size(gc, min_cluster_size = 7)
set.seed(123)

gn2keep <- unname(unlist(lapply(lapply(gcs@gene_clusters, sample, 100, replace=T), unique)))
gn2keep <- unique(union(gn2keep, sample(rownames(seurat_obj), 1000)))

# Subsetting the object and storing -------------------------------------
data(lymph_node_selected_spot_2)

seurat_obj <- subset(seurat_obj, cells=lymph_node_selected_spot_2) 
seurat_obj@assays$Spatial@data <- seurat_obj@assays$Spatial@data[rownames(seurat_obj) %in% gn2keep, ]
seurat_obj@assays$Spatial@counts <- seurat_obj@assays$Spatial@counts[rownames(seurat_obj) %in% gn2keep, ]
dim(seurat_obj)

lymph_node_tiny_2 <- seurat_obj
save(lymph_node_tiny_2, file="lymph_node_tiny_2.rda")

# Store a clusterSet object  ---------------------------------------------

res <- select_genes(data=lymph_node_tiny_2,
                    distance_method="pearson",
                    row_sum = 5)

gc <- gene_clustering(res, keep_nn = F, inflation = 2.2, threads = 4)
gcs <- filter_cluster_size(gc, min_cluster_size = 4)
lymph_node_tiny_clusters_2 <-  gcs
save(lymph_node_tiny_clusters_2, file="lymph_node_tiny_clusters_2.rda")

