## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.path = 'figures/'
)

## ----eval=TRUE, message=FALSE, warning=FALSE----------------------------------
library(Banksy)

library(SummarizedExperiment)
library(SpatialExperiment)
library(scuttle)

library(scater)
library(cowplot)
library(ggplot2)

## ----eval=TRUE----------------------------------------------------------------
data(hippocampus)
gcm <- hippocampus$expression
locs <- as.matrix(hippocampus$locations)

## ----eval=TRUE, message=FALSE-------------------------------------------------
se <- SpatialExperiment(assay = list(counts = gcm), spatialCoords = locs)

# QC based on total counts
qcstats <- perCellQCMetrics(se)
thres <- quantile(qcstats$total, c(0.05, 0.98))
keep <- (qcstats$total > thres[1]) & (qcstats$total < thres[2])
se <- se[, keep]

# Normalization to mean library size
se <- computeLibraryFactors(se)
aname <- "normcounts"
assay(se, aname) <- normalizeCounts(se, log = FALSE)

## ----eval=TRUE----------------------------------------------------------------
k_geom <- c(15, 30)
se <- computeBanksy(se, assay_name = aname, compute_agf = TRUE, k_geom = k_geom)

## ----eval=TRUE----------------------------------------------------------------
assayNames(se)

## ----eval=TRUE----------------------------------------------------------------
lambda <- c(0, 0.2)
set.seed(1000)
se <- runBanksyPCA(se, use_agf = TRUE, lambda = lambda, lazy = FALSE)
se <- runBanksyUMAP(se, use_agf = TRUE, lambda = lambda)
se <- clusterBanksy(se, use_agf = TRUE, lambda = lambda, resolution = 1.2)
se <- connectClusters(se)

## ----eval=TRUE, fig.height=5, fig.width=14------------------------------------
cnames <- colnames(colData(se))
cnames <- cnames[grep("^clust", cnames)]
colData(se) <- cbind(colData(se), spatialCoords(se))

plot_nsp <- plotColData(se,
    x = "sdimx", y = "sdimy",
    point_size = 0.6, colour_by = cnames[1]
)
plot_bank <- plotColData(se,
    x = "sdimx", y = "sdimy",
    point_size = 0.6, colour_by = cnames[2]
)

plot_grid(plot_nsp + coord_equal(), plot_bank + coord_equal(), ncol = 2)

## ----eval=TRUE----------------------------------------------------------------
banksy_matrix <- getBanksyMatrix(se, M = 1, lambda = 0.2,
                                  assay_name = aname, scale = TRUE)
dim(banksy_matrix)

## ----sess-------------------------------------------------------------------------------------------------------------
options(width = 120)
sessioninfo::session_info()

