## ----setup, include=FALSE-----------------------------------------------------
# Set chunk options: suppress echo, messages, and warnings in code output
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)

## ----install, eval=FALSE------------------------------------------------------
# # Install BiocManager if not already installed, then install SpaceTrooper
# if (!requireNamespace("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# BiocManager::install("SpaceTrooper")

## ----load-data----------------------------------------------------------------
library(SpatialExperiment)
# Load the SpaceTrooper library
library(SpaceTrooper)

# Load Xenium data into a Spatial Experiment object (SPE)
xeniumFolder <- system.file( "extdata", "Xenium_small", package="SpaceTrooper")
(xen <- readXeniumSPE(xeniumFolder, computeMissingMetrics=TRUE,
                        keepPolygons=TRUE))
colData(xen)
# Load Merfish data into an SPE with parquet boundaries
merscopeFolder <- system.file("extdata", "Merfish_Tiny", package="SpaceTrooper")
(mer <- readMerfishSPE(merscopeFolder, boundariesType="parquet",
                        computeMissingMetrics=TRUE, keepPolygons=TRUE))
colData(mer)

## ----cosmx-analysis-----------------------------------------------------------
# Reload CosMx data with sample name and without polygons
cosmxFolder <- system.file(file.path("extdata", "CosMx_DBKero_Tiny"), 
                        package="SpaceTrooper")
spe <- readCosmxSPE(cosmxFolder, sampleName="DBKero_CosMx")
## a custom function for the labels of this dataset
source(system.file(file.path("scripts", "labelsfunct.R"), 
                    package="SpaceTrooper"))
spe <- addLabelsDBKero(spe)

spe

## ----plot-fovs----------------------------------------------------------------
# Plot the cells within their respective Field of Views (FOVs)
plotCellsFovs(spe)

## ----plot-centroids-labels----------------------------------------------------
# Plot the centroids of the cells in the SPE
plotCentroids(spe, colourBy="labels")
# Plot the centroids of the cells in the SPE with personalized labels
plotCentroids(spe, colourBy="labels", palette="labels_colors")

## ----cosmx-analysis-qc--------------------------------------------------------
# Perform per-cell quality control checks
spe <- spatialPerCellQC(spe, rmZeros=TRUE,
        negProbList=c("NegPrb", "Negative", "SystemControl"))
names(colData(spe))

## ----plot-metrics-------------------------------------------------------------
# Plot a histogram of counts (sum)
plotMetricHist(spe, metric="sum")
# Plot a histogram of cell areas (Area_um)
plotMetricHist(spe, metric="Area_um")
# Plot a histogram of proportion of counts respect to the cell area in micron 
plotMetricHist(spe, metric="log2CountArea")

## ----cosmx-analysis-outlier, warning=FALSE------------------------------------
# Identify spatial outliers based on cell area (Area_um)
spe <- computeSpatialOutlier(spe, computeBy="Area_um", method="both")

# Identify spatial outliers based on mean DAPI intensity
spe <- computeSpatialOutlier(spe, computeBy="Mean.DAPI", method="both")
names(colData(spe))

## ----plot-metrics-2-----------------------------------------------------------
# Plot a histogram with fences to identify outliers using the medcouple
plotMetricHist(spe, metric="Area_um", useFences="Area_um_outlier_mc")

# Plot a histogram with fences to identify outliers using scuttle
plotMetricHist(spe, metric="Area_um", useFences="Area_um_outlier_sc")

# Plot a histogram with fences to identify outliers using the medcouple
plotMetricHist(spe, metric="Mean.DAPI", useFences="Mean.DAPI_outlier_mc")

# Plot a histogram with fences to identify outliers using scuttle
plotMetricHist(spe, metric="Mean.DAPI", useFences="Mean.DAPI_outlier_sc")

## ----cosmx-analysis-score-----------------------------------------------------
# Calculate quality scores for each cell
spe <- computeQCScore(spe)
names(colData(spe))

## ----cosmx-analysis-score2----------------------------------------------------
# Compute flags to identify cells for filtering
spe <- computeQCScoreFlags(spe, qsThreshold=0.5)
names(colData(spe))
table(spe$low_qcscore)

## ----threshold-outlier--------------------------------------------------------
spe <- computeThresholdFlags(spe, totalThreshold=0, 
                                ctrlTotRatioThreshold=0.1)
table(spe$threshold_flags)

## ----plot-polygons------------------------------------------------------------
# Read polygon data associated with cells in the SPE
# the polygon file path is stored in the spe metadata
pols <- readPolygonsCosmx(metadata(spe)$polygons)

# Add the polygon data to the SPE object
spe <- addPolygonsToSPE(spe, pols)

## ----plot-polygons-fov-1------------------------------------------------------
# Plot the polygons of the selected cells
plotPolygons(spe, bgColor="white")

## ----plot-polygons-fov-2------------------------------------------------------
# Plot polygons colored by cell area
plotPolygons(spe, colourBy="log2AspectRatio")
plotPolygons(spe, colourBy="Area_um")

## ----plot-polygons-fov-3------------------------------------------------------
plotPolygons(spe, colourBy="QC_score")
plotPolygons(spe, colourBy="low_qcscore")

## ----plot-zoom-fov------------------------------------------------------------
plotZoomFovsMap(spe, fovs=16, colourBy="QC_score")
plotZoomFovsMap(spe, fovs=16, colourBy="low_qcscore")

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

