### Install SpatialExperiment from Bioconductor Source: https://github.com/drighelli/spatialexperiment/blob/devel/README.md Install the release version of the SpatialExperiment package using BiocManager. This is the recommended installation method for most users. ```R install.packages("BiocManager") BiocManager::install("SpatialExperiment") ``` -------------------------------- ### Install SpatialExperiment from GitHub Source: https://github.com/drighelli/spatialexperiment/blob/devel/README.md Install the latest development version of the SpatialExperiment package directly from GitHub. This may require manual installation of some dependency packages. ```R remotes::install_github("drighelli/SpatialExperiment") ``` -------------------------------- ### Constructing a SpatialExperiment Object Source: https://context7.com/drighelli/spatialexperiment/llms.txt Demonstrates creating a SpatialExperiment object using spatial coordinates from colData, a separate matrix, or by integrating full image data from 10x Genomics Visium files. ```r library(SpatialExperiment) # Method 1: Provide spatial coordinates via colData column names n <- 26 y <- matrix(nrow = n, ncol = n) cd <- DataFrame(x = seq(n), y = seq(n), sample_id = "sample01") spe <- SpatialExperiment( assays = list(counts = y), colData = cd, spatialCoordsNames = c("x", "y") ) # Method 2: Provide spatial coordinates as a separate matrix xy <- as.matrix(cd[, c("x", "y")]) spe <- SpatialExperiment( assays = list(counts = y), colData = cd["sample_id"], spatialCoords = xy ) # Full constructor with image data dir <- system.file( file.path("extdata", "10xVisium", "section1", "outs"), package = "SpatialExperiment") # Read count data using DropletUtils fnm <- file.path(dir, "raw_feature_bc_matrix") sce <- DropletUtils::read10xCounts(fnm) # Read image data img <- readImgData( path = file.path(dir, "spatial"), sample_id = "foo") # Read spatial coordinates from tissue positions file fnm <- file.path(dir, "spatial", "tissue_positions_list.csv") xyz <- read.csv(fnm, header = FALSE, col.names = c("barcode", "in_tissue", "array_row", "array_col", "pxl_row_in_fullres", "pxl_col_in_fullres")) # Construct SpatialExperiment with images spe <- SpatialExperiment( assays = list(counts = assay(sce)), rowData = DataFrame(symbol = rowData(sce)$Symbol), colData = DataFrame(xyz), spatialCoordsNames = c("pxl_col_in_fullres", "pxl_row_in_fullres"), imgData = img, sample_id = "foo") spe ``` -------------------------------- ### colData Access with $ Source: https://context7.com/drighelli/spatialexperiment/llms.txt Demonstrates convenient column access from colData using the $ operator with auto-completion. ```APIDOC ## colData Access with $ ### Description The `SpatialExperiment` class supports convenient column access from `colData` using the `$` operator with auto-completion in RStudio. ### Method Not specified (operator usage in R) ### Endpoint Not applicable (R object manipulation) ### Parameters No explicit parameters for the `$` operator itself, but it accesses columns within the `spe` object's `colData`. ### Request Example ```r # Access sample_id column unique(spe$sample_id) # Access in_tissue column table(spe$in_tissue) # Access array coordinates head(spe$array_row) head(spe$array_col) # Replace sample_id (must map uniquely to existing values) new_ids <- spe$sample_id new_ids[new_ids == "section1"] <- "sample_A" spe$sample_id <- new_ids # Note: sample_id is protected and cannot be removed spe$sample_id <- NULL # Has no effect ``` ### Response #### Success Response (200) Access to columns within the `colData` of the `SpatialExperiment` object (`spe`). Modifications to columns are reflected in the object. #### Response Example ```r # Output of unique(spe$sample_id) # [1] "section1" "section2" # Output of table(spe$in_tissue) # FALSE TRUE # 99 99 # Output of head(spe$array_row) # [1] 0 1 0 1 2 0 ``` ``` -------------------------------- ### Importing Visium Data via VisiumIO Source: https://context7.com/drighelli/spatialexperiment/llms.txt Recommended approach for importing 10x Genomics Visium data using the VisiumIO package. ```r library(VisiumIO) # Get sample directories dir <- list.dirs(system.file( file.path("extdata", "10xVisium"), package = "SpatialExperiment"), recursive = FALSE, full.names = TRUE) sample_ids <- basename(dir) # Create TENxVisiumList and import vl <- TENxVisiumList( sampleFolders = dir, sample_ids = sample_ids, processing = "raw", # "raw" or "filtered" images = "lowres" # image resolution ) spe <- import(vl) spe ``` -------------------------------- ### Access Image Content and Sources Source: https://context7.com/drighelli/spatialexperiment/llms.txt Retrieve raster objects for visualization or file paths/URLs for image sources. ```r # Get raster object for plotting img <- imgRaster(spe, sample_id = "section1", image_id = "lowres") plot(img) # Get raster for first available image img <- imgRaster(spe) class(img) # [1] "raster" # Get image source path/URL imgSource(spe, sample_id = "section1", image_id = "lowres") # [1] "/path/to/tissue_lowres_image.png" # For remote images, get cached file path imgSource(spe, sample_id = "section1", image_id = "lowres", path = TRUE) ``` -------------------------------- ### Loading 10x Genomics Visium Data (Deprecated) Source: https://context7.com/drighelli/spatialexperiment/llms.txt Loads Visium data using the deprecated read10xVisium function. This method is maintained for backward compatibility. ```r # Define sample directories dir <- system.file( file.path("extdata", "10xVisium"), package = "SpatialExperiment") sample_ids <- c("section1", "section2") samples <- file.path(dir, sample_ids, "outs") # Load multiple Visium samples spe <- read10xVisium( samples = samples, sample_id = sample_ids, type = "sparse", # "sparse" or "HDF5" data = "raw", # "raw" or "filtered" images = "lowres", # "lowres", "hires", "detected", "aligned" load = FALSE # FALSE stores path, TRUE loads into memory ) spe # Tabulate spots mapped to tissue per sample table( in_tissue = colData(spe)$in_tissue, sample_id = colData(spe)$sample_id) ``` -------------------------------- ### Combine SpatialExperiment Samples Source: https://context7.com/drighelli/spatialexperiment/llms.txt Merge multiple SpatialExperiment objects column-wise, ensuring sample identifiers and image data are synchronized. ```r # Create two separate SPE objects spe1 <- spe2 <- spe # Method 1: Let cbind handle duplicate sample_ids (appends indices) spe_combined <- cbind(spe1, spe2) unique(spe_combined$sample_id) # [1] "section1.1" "section2.1" "section1.2" "section2.2" # Method 2: Pre-assign unique sample identifiers (preferred) spe1 <- spe2 <- spe spe1$sample_id <- paste(spe1$sample_id, "A", sep = ".") spe2$sample_id <- paste(spe2$sample_id, "B", sep = ".") spe_combined <- cbind(spe1, spe2) unique(spe_combined$sample_id) # [1] "section1.A" "section2.A" "section1.B" "section2.B" # Image data is also combined imgData(spe_combined) # sample_id image_id data scaleFactor # 1 section1.A lowres LoadedSpatialImage 0.03462326 # 2 section2.A lowres LoadedSpatialImage 0.03462326 # 3 section1.B lowres LoadedSpatialImage 0.03462326 # 4 section2.B lowres LoadedSpatialImage 0.03462326 # Tabulate combined data cd <- colData(spe_combined) table(in_tissue = cd$in_tissue, sample_id = cd$sample_id) ``` -------------------------------- ### Access colData with $ Operator Source: https://context7.com/drighelli/spatialexperiment/llms.txt Demonstrates accessing columns within the `colData` of a `SpatialExperiment` object using the `$` operator for convenient data retrieval and modification. Note that `sample_id` is a protected column and cannot be removed. ```r # Access sample_id column unique(spe$sample_id) # [1] "section1" "section2" # Access in_tissue column table(spe$in_tissue) # FALSE TRUE # 99 99 # Access array coordinates head(spe$array_row) # [1] 0 1 0 1 2 0 head(spe$array_col) # [1] 16 11 18 19 14 20 # Replace sample_id (must map uniquely to existing values) new_ids <- spe$sample_id new_ids[new_ids == "section1"] <- "sample_A" spe$sample_id <- new_ids # Note: sample_id is protected and cannot be removed spe$sample_id <- NULL # Has no effect ``` -------------------------------- ### Mirror and Rotate Images Source: https://context7.com/drighelli/spatialexperiment/llms.txt Functions to mirror and rotate images within a SpatialExperiment object. ```APIDOC ## Mirror Image Vertically ```r spe_mirrored <- mirrorImg(spe, sample_id = "section1", image_id = "lowres", axis = "v") ``` ## Visual Comparison of Transformations ```r par(mfrow = c(1, 3)) plot(imgRaster(spe)) plot(imgRaster(rotateImg(spe, degrees = 90))) plot(imgRaster(mirrorImg(spe, axis = "h"))) ``` ``` -------------------------------- ### Image Transformations Source: https://context7.com/drighelli/spatialexperiment/llms.txt Apply rotation and mirroring transformations to images stored in the SpatialExperiment. ```APIDOC ## rotateImg, mirrorImg - Image Transformations Apply rotation and mirroring transformations to images stored in the `SpatialExperiment`. ### Rotate image 90 degrees clockwise (positive) or counter-clockwise (negative) ```r spe_rotated <- rotateImg(spe, sample_id = "section1", image_id = "lowres", degrees = 90) ``` ### Rotate all images ```r spe_rotated <- rotateImg(spe, sample_id = TRUE, image_id = TRUE, degrees = -90) # Counter-clockwise ``` ### Mirror image horizontally ```r spe_mirrored <- mirrorImg(spe, sample_id = "section1", image_id = "lowres", axis = "h") ``` ``` -------------------------------- ### Combining Multiple Samples Source: https://context7.com/drighelli/spatialexperiment/llms.txt Function to combine multiple SpatialExperiment objects column-wise, synchronizing all data fields. ```APIDOC ## cbind - Combining Multiple Samples Combine multiple `SpatialExperiment` objects column-wise, merging samples while synchronizing all data fields including `imgData`. ### Method 1: Let cbind handle duplicate sample_ids (appends indices) ```r # Create two separate SPE objects spe1 <- spe2 <- spe spe_combined <- cbind(spe1, spe2) unique(spe_combined$sample_id) # [1] "section1.1" "section2.1" "section1.2" "section2.2" ``` ### Method 2: Pre-assign unique sample identifiers (preferred) ```r spe1 <- spe2 <- spe spe1$sample_id <- paste(spe1$sample_id, "A", sep = ".") spe2$sample_id <- paste(spe2$sample_id, "B", sep = ".") spe_combined <- cbind(spe1, spe2) unique(spe_combined$sample_id) # [1] "section1.A" "section2.A" "section1.B" "section2.B" # Image data is also combined imgData(spe_combined) # sample_id image_id data scaleFactor # 1 section1.A lowres LoadedSpatialImage 0.03462326 # 2 section2.A lowres LoadedSpatialImage 0.03462326 # 3 section1.B lowres LoadedSpatialImage 0.03462326 # 4 section2.B lowres LoadedSpatialImage 0.03462326 # Tabulate combined data cd <- colData(spe_combined) table(in_tissue = cd$in_tissue, sample_id = cd$sample_id) ``` ``` -------------------------------- ### Read Image Data for Visium Source: https://context7.com/drighelli/spatialexperiment/llms.txt Reads images and scale factors from 10x Genomics Visium spatial directories into a valid imgData DataFrame. ```APIDOC ## readImgData - Read Image Data for Visium ### Description Read images and scale factors from 10x Genomics Visium spatial directories into a valid `imgData` `DataFrame`. ### Method Not specified (function call in R) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters - **path** (string) - Required - Path to the Visium spatial directory. - **sample_id** (string) - Required - Identifier for the sample. - **load** (boolean) - Optional - Whether to load image data into memory (default is TRUE). ### Request Example ```r # Read from Visium spatial directory dir <- system.file(file.path("extdata", "10xVisium", "section1", "outs", "spatial"), package = "SpatialExperiment") # Read image data img_data <- readImgData(path = dir, sample_id = "sample1", load = TRUE) ``` ### Response #### Success Response (200) - **img_data** (DataFrame) - A DataFrame containing image data, including sample ID, image ID, data (image or path), and scale factor. #### Response Example ```r # When load = TRUE # sample_id image_id data scaleFactor # 1 sample1 lowres LoadedSpatialImage 0.03462326 # When load = FALSE # class(img_data$data[[1]]) # [1] "StoredSpatialImage" ``` ``` -------------------------------- ### Subsetting SpatialExperiment Objects Source: https://context7.com/drighelli/spatialexperiment/llms.txt Methods for subsetting SpatialExperiment objects while maintaining attribute synchronization. ```APIDOC ## Subsetting Subset `SpatialExperiment` objects while automatically synchronizing all attributes including `spatialCoords` and `imgData`. ### Subset by sample_id ```r spe_section1 <- spe[, spe$sample_id == "section1"] ncol(spe_section1) # [1] 99 ``` ### Subset to spots mapped to tissue ```r spe_tissue <- spe[, colData(spe)$in_tissue] ncol(spe_tissue) # Number of in-tissue spots ``` ### Subset by genes ```r genes_of_interest <- c("gene1", "gene2", "gene3") spe_subset <- spe[genes_of_interest, ] ``` ### Combined subsetting ```r spe_filtered <- spe[ rownames(spe)[1:100], spe$sample_id == "section1" & spe$in_tissue] ``` ``` -------------------------------- ### Image Retrieval, Addition, and Removal Source: https://context7.com/drighelli/spatialexperiment/llms.txt Functions to retrieve, add, and remove images from the SpatialExperiment object's imgData. ```APIDOC ## getImg, addImg, rmvImg - Image Management Functions to retrieve, add, and remove images from the `SpatialExperiment` object's `imgData`. ### Get a SpatialImage object ```r spi <- getImg(spe) ``` ### Get specific image by sample and image ID ```r spi <- getImg(spe, sample_id = "section1", image_id = "lowres") ``` ### Add an image from URL ```r url <- "https://i.redd.it/3pw5uah7xo041.jpg" spe <- addImg(spe, imageSource = url, scaleFactor = NA_real_, sample_id = "section1", image_id = "new_image", load = TRUE) ``` ### Remove an image ```r spe <- rmvImg(spe, sample_id = "section1", image_id = "new_image") ``` ### Remove all images for a sample ```r spe <- rmvImg(spe, sample_id = "section1", image_id = TRUE) ``` ``` -------------------------------- ### Apply Image Transformations Source: https://context7.com/drighelli/spatialexperiment/llms.txt Rotate or mirror images stored within the SpatialExperiment object. ```r # Rotate image 90 degrees clockwise (positive) or counter-clockwise (negative) spe_rotated <- rotateImg(spe, sample_id = "section1", image_id = "lowres", degrees = 90) # Rotate all images spe_rotated <- rotateImg(spe, sample_id = TRUE, image_id = TRUE, degrees = -90) # Counter-clockwise # Mirror image horizontally spe_mirrored <- mirrorImg(spe, sample_id = "section1", image_id = "lowres", axis = "h") ``` -------------------------------- ### Retrieve, Add, and Remove Images Source: https://context7.com/drighelli/spatialexperiment/llms.txt Functions for managing the collection of images stored within the imgData slot. ```r # Get a SpatialImage object spi <- getImg(spe) spi # LoadedSpatialImage object # Get specific image by sample and image ID spi <- getImg(spe, sample_id = "section1", image_id = "lowres") # Add an image from URL url <- "https://i.redd.it/3pw5uah7xo041.jpg" spe <- addImg(spe, imageSource = url, scaleFactor = NA_real_, sample_id = "section1", image_id = "new_image", load = TRUE) imgData(spe) # sample_id image_id data scaleFactor # 1 section1 lowres LoadedSpatialImage 0.03462326 # 2 section2 lowres LoadedSpatialImage 0.03462326 # 3 section1 new_image LoadedSpatialImage NA # Remove an image spe <- rmvImg(spe, sample_id = "section1", image_id = "new_image") # Remove all images for a sample spe <- rmvImg(spe, sample_id = "section1", image_id = TRUE) ``` -------------------------------- ### SpatialImage Class Operations Source: https://context7.com/drighelli/spatialexperiment/llms.txt Create and manipulate SpatialImage objects from files or URLs, including dimension retrieval and coercion. ```r # Create SpatialImage from file path path <- system.file( "extdata", "10xVisium", "section1", "outs", "spatial", "tissue_lowres_image.png", package = "SpatialExperiment") spi <- SpatialImage(path) class(spi) # [1] "StoredSpatialImage" # Get image dimensions dim(spi) # [1] 600 600 nrow(spi) # [1] 600 ncol(spi) # [1] 600 # Convert to raster and plot plot(imgRaster(spi)) # Or use as.raster method plot(as.raster(spi)) # Coerce to LoadedSpatialImage (in-memory) spi_loaded <- as(spi, "LoadedSpatialImage") class(spi_loaded) # [1] "LoadedSpatialImage" # Create from URL (creates RemoteSpatialImage) url <- "https://example.com/image.png" spi_remote <- SpatialImage(url) class(spi_remote) # [1] "RemoteSpatialImage" ``` -------------------------------- ### Image Content Access Source: https://context7.com/drighelli/spatialexperiment/llms.txt Retrieve the raster representation or source path/URL of images stored in the SpatialExperiment. ```APIDOC ## imgRaster, imgSource - Access Image Content Retrieve the raster representation or source path/URL of images stored in the `SpatialExperiment`. ### Get raster object for plotting ```r img <- imgRaster(spe, sample_id = "section1", image_id = "lowres") plot(img) ``` ### Get raster for first available image ```r img <- imgRaster(spe) class(img) ``` ### Get image source path/URL ```r imgSource(spe, sample_id = "section1", image_id = "lowres") ``` ### For remote images, get cached file path ```r imgSource(spe, sample_id = "section1", image_id = "lowres", path = TRUE) ``` ``` -------------------------------- ### Read Visium Image Data Source: https://context7.com/drighelli/spatialexperiment/llms.txt Reads image and scale factor data from a 10x Genomics Visium spatial directory. Set `load = TRUE` to load images into memory, or `load = FALSE` to store only file paths. ```r # Read from Visium spatial directory dir <- system.file( file.path("extdata", "10xVisium", "section1", "outs", "spatial"), package = "SpatialExperiment") # List directory contents list.files(dir) # [1] "scalefactors_json.json" "tissue_lowres_image.png" # [3] "tissue_positions_list.csv" # Read image data img_data <- readImgData( path = dir, sample_id = "sample1", load = TRUE) # Load into memory img_data # sample_id image_id data scaleFactor # 1 sample1 lowres LoadedSpatialImage 0.03462326 # Read without loading (store path only) img_data <- readImgData( path = dir, sample_id = "sample1", load = FALSE) class(img_data$data[[1]]) # [1] "StoredSpatialImage" ``` -------------------------------- ### Transform Images and Coordinates Source: https://context7.com/drighelli/spatialexperiment/llms.txt Perform vertical or horizontal mirroring and rotation on images and spatial coordinates. ```r # Mirror image vertically spe_mirrored <- mirrorImg(spe, sample_id = "section1", image_id = "lowres", axis = "v") # Visual comparison par(mfrow = c(1, 3)) plot(imgRaster(spe)) plot(imgRaster(rotateImg(spe, degrees = 90))) plot(imgRaster(mirrorImg(spe, axis = "h"))) ``` ```r # Rotate coordinates 90 degrees clockwise # Subsets to specified sample spe_rotated <- rotateCoords(spe, sample_id = "section1", degrees = 90, warn = TRUE) # Warns about potential image mismatch # Mirror coordinates across vertical axis spe_mirrored <- mirrorCoords(spe, sample_id = "section1", axis = "v", warn = TRUE) # Check transformed coordinates head(spatialCoords(spe_rotated)) ``` ```r # Rotate both coordinates and image by 90 degrees spe_rotated <- rotateObject(spe, sample_id = "section1", image_id = "lowres", degrees = 90) # Rotate 180 degrees spe_rotated <- rotateObject(spe, sample_id = "section1", degrees = 180) # Mirror both horizontally spe_mirrored <- mirrorObject(spe, sample_id = "section1", image_id = "lowres", axis = "h") # Apply multiple transformations spe_transformed <- rotateObject(spe, sample_id = "section2", degrees = 180) spe_transformed <- mirrorObject(spe_transformed, axis = "v") # Visual verification par(mfrow = c(1, 2)) plot(imgRaster(spe, sample_id = "section2", image_id = "lowres")) plot(imgRaster(spe_transformed, sample_id = "section2", image_id = "lowres")) ``` -------------------------------- ### Combined Transformations (Object Level) Source: https://context7.com/drighelli/spatialexperiment/llms.txt Wrapper functions to transform both spatial coordinates and images together, ensuring consistency. ```APIDOC ## rotateObject, mirrorObject - Combined Transformations Transform both spatial coordinates and images together to maintain consistency. These are wrapper functions around the individual transformation methods. ### Rotate both coordinates and image by 90 degrees ```r spe_rotated <- rotateObject(spe, sample_id = "section1", image_id = "lowres", degrees = 90) ``` ### Rotate 180 degrees ```r spe_rotated <- rotateObject(spe, sample_id = "section1", degrees = 180) ``` ### Mirror both horizontally ```r spe_mirrored <- mirrorObject(spe, sample_id = "section1", image_id = "lowres", axis = "h") ``` ### Apply multiple transformations ```r spe_transformed <- rotateObject(spe, sample_id = "section2", degrees = 180) spe_transformed <- mirrorObject(spe_transformed, axis = "v") ``` ### Visual verification ```r par(mfrow = c(1, 2)) plot(imgRaster(spe, sample_id = "section2", image_id = "lowres")), plot(imgRaster(spe_transformed, sample_id = "section2", image_id = "lowres")) ``` ``` -------------------------------- ### Subset SpatialExperiment Objects Source: https://context7.com/drighelli/spatialexperiment/llms.txt Filter SpatialExperiment objects by sample, tissue status, or genes while maintaining attribute synchronization. ```r # Subset by sample_id spe_section1 <- spe[, spe$sample_id == "section1"] ncol(spe_section1) # [1] 99 # Subset to spots mapped to tissue spe_tissue <- spe[, colData(spe)$in_tissue] ncol(spe_tissue) # Number of in-tissue spots # Subset by genes genes_of_interest <- c("gene1", "gene2", "gene3") spe_subset <- spe[genes_of_interest, ] # Combined subsetting spe_filtered <- spe[ rownames(spe)[1:100], spe$sample_id == "section1" & spe$in_tissue] ``` -------------------------------- ### Manage Molecule-Based Spatial Data Source: https://context7.com/drighelli/spatialexperiment/llms.txt Store and access molecule-level spatial data using the BumpyMatrix assay within a SpatialExperiment object. ```r library(BumpyMatrix) # Create simulated molecule-based data n <- 1000 # number of molecules ng <- 50 # number of genes nc <- 20 # number of cells # Sample xy-coordinates x <- runif(n) y <- runif(n) # Assign molecules to gene-cell pairs gs <- paste0("gene", seq(ng)) cs <- paste0("cell", seq(nc)) gene <- factor(sample(gs, n, TRUE), gs) cell <- factor(sample(cs, n, TRUE), cs) # Create data frame of molecule coordinates df <- data.frame(gene, cell, x, y) # Convert to BumpyMatrix mol <- splitAsBumpyMatrix( df[, c("x", "y")], row = df$gene, col = df$cell) # Create count matrix y <- with(df, table(gene, cell)) y <- as.matrix(unclass(y)) # Construct SpatialExperiment with molecules assay spe_mol <- SpatialExperiment( assays = list( counts = y, molecules = mol)) # Access molecules assay molecules(spe_mol) # 50 x 20 BumpyDataFrameMatrix # ... # Access molecule positions for specific gene-cell molecules(spe_mol)["gene1", "cell1"] # DataFrame with x and y columns ``` -------------------------------- ### Manage Image Data Metadata Source: https://context7.com/drighelli/spatialexperiment/llms.txt Access the DataFrame containing image identifiers and scale factors for samples. ```r # View image data structure imgData(spe) # sample_id image_id data scaleFactor # 1 section1 lowres LoadedSpatialImage 0.03462326 # 2 section2 lowres LoadedSpatialImage 0.03462326 # Get scale factors for images scaleFactors(spe) # [1] 0.03462326 0.03462326 # Get scale factors for specific sample/image scaleFactors(spe, sample_id = "section1", image_id = "lowres") # [1] 0.03462326 ``` -------------------------------- ### Image Data Management Source: https://context7.com/drighelli/spatialexperiment/llms.txt Access and manipulate the DataFrame storing image information including sample identifiers, image identifiers, image data, and scale factors. ```APIDOC ## imgData - Manage Image Data Access and manipulate the `DataFrame` storing image information including sample identifiers, image identifiers, image data (as `SpatialImage` objects), and scale factors. ### View image data structure ```r imgData(spe) ``` ### Get scale factors for images ```r scaleFactors(spe) ``` ### Get scale factors for specific sample/image ```r scaleFactors(spe, sample_id = "section1", image_id = "lowres") ``` ``` -------------------------------- ### SpatialImage Class Source: https://context7.com/drighelli/spatialexperiment/llms.txt The SpatialImage class hierarchy provides representations for images from various sources. ```APIDOC ## SpatialImage Class - Image Storage The `SpatialImage` class hierarchy provides representations for images from various sources: `LoadedSpatialImage` (in-memory raster), `StoredSpatialImage` (local file), and `RemoteSpatialImage` (URL). ### Create SpatialImage from file path ```r path <- system.file( "extdata", "10xVisium", "section1", "outs", "spatial", "tissue_lowres_image.png", package = "SpatialExperiment") spi <- SpatialImage(path) class(spi) ``` ### Get image dimensions ```r dim(spi) nrow(spi) col(spi) ``` ### Convert to raster and plot ```r plot(imgRaster(spi)) plot(as.raster(spi)) ``` ### Coerce to LoadedSpatialImage (in-memory) ```r spi_loaded <- as(spi, "LoadedSpatialImage") class(spi_loaded) ``` ### Create from URL (creates RemoteSpatialImage) ```r url <- "https://example.com/image.png" spi_remote <- SpatialImage(url) class(spi_remote) ``` ``` -------------------------------- ### Spatial Coordinate Transformations Source: https://context7.com/drighelli/spatialexperiment/llms.txt Functions to transform spatial coordinates independently of images, with options for rotation and mirroring. ```APIDOC ## rotateCoords, mirrorCoords - Spatial Coordinate Transformations Transform spatial coordinates independently from images. Use with caution as this may cause mismatches with images. ### Rotate coordinates 90 degrees clockwise ```r # Subsets to specified sample spe_rotated <- rotateCoords(spe, sample_id = "section1", degrees = 90, warn = TRUE) # Warns about potential image mismatch ``` ### Mirror coordinates across vertical axis ```r spe_mirrored <- mirrorCoords(spe, sample_id = "section1", axis = "v", warn = TRUE) ``` ### Check transformed coordinates ```r head(spatialCoords(spe_rotated)) ``` ``` -------------------------------- ### Spatial Coordinates Management Source: https://context7.com/drighelli/spatialexperiment/llms.txt Access and modify the numeric matrix of spatial coordinates (typically x and y positions) for each spot or cell. ```APIDOC ## spatialCoords - Access and Set Spatial Coordinates Access or modify the numeric matrix of spatial coordinates (typically x and y positions) for each spot or cell. ### Get spatial coordinates ```r head(spatialCoords(spe)) ``` ### Get coordinate column names ```r spatialCoordsNames(spe) ``` ### Rename coordinate columns ```r spatialCoordsNames(spe) <- c("x", "y") head(spatialCoords(spe)) ``` ### Replace spatial coordinates ```r new_coords <- spatialCoords(spe) new_coords[, 1] <- new_coords[, 1] * 2 # Scale x coordinates spatialCoords(spe) <- new_coords ``` ``` -------------------------------- ### Molecule-Based ST Data Access Source: https://context7.com/drighelli/spatialexperiment/llms.txt Accessing and creating molecule-based spatial transcriptomics data stored as a BumpyMatrix. ```APIDOC ## molecules - Molecule-Based ST Data Access the `molecules` assay for molecule-based spatial transcriptomics data stored as a `BumpyMatrix`, where each entry contains coordinates of individual molecules. ### Create simulated molecule-based data ```r library(BumpyMatrix) # Create simulated molecule-based data n <- 1000 # number of molecules ng <- 50 # number of genes nc <- 20 # number of cells # Sample xy-coordinates x <- runif(n) y <- runif(n) # Assign molecules to gene-cell pairs gs <- paste0("gene", seq(ng)) cs <- paste0("cell", seq(nc)) gene <- factor(sample(gs, n, TRUE), gs) cell <- factor(sample(cs, n, TRUE), cs) # Create data frame of molecule coordinates df <- data.frame(gene, cell, x, y) # Convert to BumpyMatrix mol <- splitAsBumpyMatrix( df[, c("x", "y")], row = df$gene, col = df$cell) # Create count matrix y <- with(df, table(gene, cell)) y <- as.matrix(unclass(y)) # Construct SpatialExperiment with molecules assay spe_mol <- SpatialExperiment( assays = list( counts = y, molecules = mol)) ``` ### Access molecules assay ```r molecules(spe_mol) # 50 x 20 BumpyDataFrameMatrix # ... # Access molecule positions for specific gene-cell molecules(spe_mol)["gene1", "cell1"] # DataFrame with x and y columns ``` ``` -------------------------------- ### Access and Modify Spatial Coordinates Source: https://context7.com/drighelli/spatialexperiment/llms.txt Use these functions to retrieve, rename, or update the spatial coordinate matrix associated with spots or cells. ```r # Get spatial coordinates head(spatialCoords(spe)) # pxl_col_in_fullres pxl_row_in_fullres # AAACAACGAATAGTTC-1 2312 1252 # AAACAAGTATCTCCCA-1 5765 2107 # AAACAATCTACTAGCA-1 2744 1577 # Get coordinate column names spatialCoordsNames(spe) # [1] "pxl_col_in_fullres" "pxl_row_in_fullres" # Rename coordinate columns spatialCoordsNames(spe) <- c("x", "y") head(spatialCoords(spe)) # x y # AAACAACGAATAGTTC-1 2312 1252 # AAACAAGTATCTCCCA-1 5765 2107 # AAACAATCTACTAGCA-1 2744 1577 # Replace spatial coordinates new_coords <- spatialCoords(spe) new_coords[, 1] <- new_coords[, 1] * 2 # Scale x coordinates spatialCoords(spe) <- new_coords ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.