### Install SeuratDisk from GitHub Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/index.html This R code snippet demonstrates how to install the SeuratDisk package directly from GitHub using the 'remotes' package. It first checks if 'remotes' is installed and installs it if necessary. Ensure you have the 'remotes' package available before running this code. ```r if (!requireNamespace("remotes", quietly = TRUE)) { install.packages("remotes") } remotes::install_github("mojaveazure/seurat-disk") ``` -------------------------------- ### Create Progress Bar using PB function in R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/PB.html Demonstrates how to create and utilize a progress bar using the PB function. This example shows initializing the progress bar, updating its status in a loop, and closing it upon completion. It relies on the SeuratDisk package and base R utility functions. ```r # \donttest{ pb <- SeuratDisk:::PB() for (i in 1:10) { utils::setTxtProgressBar(pb, i / 10) } close(pb) # } ``` -------------------------------- ### Convert AnnData to Seurat via h5Seurat (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/convert-anndata.html This R code demonstrates how to convert an AnnData file (originally from Seurat) back into a Seurat object. It involves downloading an example h5ad file and then using SeuratDisk's `Convert` function to transform it into an h5Seurat file, which can then be loaded as a Seurat object. ```r library(SeuratDisk) library(curl) # Download an example AnnData file url <- "https://seurat.nygenome.org/pbmc3k_final.h5ad" curl_download(url, basename(url)) # Convert AnnData (h5ad) to h5Seurat format Convert("pbmc3k_final.h5ad", dest = "h5seurat") # Load the converted h5Seurat file as a Seurat object (example) # seurat_obj <- LoadH5Seurat("pbmc3k_final.h5seurat") ``` -------------------------------- ### Load Seurat Object with Advanced Customization Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Loads a Seurat object with fine-tuned control over assays, slots, reductions, graphs, and images. This example specifies slots for 'SCT' and 'Spatial' assays, loads only global reductions (NA), excludes all graphs (FALSE), and loads all spatial images (NULL). ```r brain2 <- LoadH5Seurat("anterior1.h5Seurat", assays = list(SCT = c("data", "scale.data"), Spatial = "counts"), reductions = NA, graphs = FALSE, images = NULL) brain2 #> An object of class Seurat #> 48721 features across 2696 samples within 2 assays #> Active assay: SCT (17668 features, 3000 variable features) #> 1 other assay present: Spatial #> 1 dimensional reduction calculated: umap ``` -------------------------------- ### Get and Print File Size in R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Calculates the size of an h5Seurat file and prints it in megabytes. This is useful for understanding storage requirements and comparing with other file formats. ```R size <- file.size("anterior1.h5Seurat") print(structure(size, class = "object_size"), units = "Mb") ``` -------------------------------- ### HDF5 Dense Matrix Representation (R Example) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-spec.html Illustrates the representation of a dense matrix stored in HDF5 using R. It shows the dataset's dimensions, datatype (64-bit little-endian float), and chunking strategy, adhering to column-major ordering. ```R #> [,1] [,2] [,3] [,4] #> [1,] 0 0 0 1 #> [2,] 0 1 1 1 #> [3,] 1 1 0 0 #> Class: H5D #> Dataset: /densemat #> Filename: /tmp/RtmpGhTXje/file2fc262fdf9e.h5 #> Access type: H5F_ACC_RDWR #> Datatype: H5T_IEEE_F64LE #> Space: Type=Simple Dims=3 x 4 Maxdims=Inf x Inf #> Chunk: 32 x 32 #> [,1] [,2] [,3] [,4] #> [1,] 0 0 0 1 #> [2,] 0 1 1 1 #> [3,] 1 1 0 0 ``` -------------------------------- ### Accessing and Setting Project Names in h5Seurat Objects (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/h5Seurat-bindings.html These S3 methods allow you to get and set the project name associated with an h5Seurat object. This can be helpful for organizing and identifying different datasets. ```r # S3 method for h5Seurat Project(object, ...) # S3 method for h5Seurat Project(object, ...) <- value ``` -------------------------------- ### Generate Chunk Points in R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/ChunkPoints.html The ChunkPoints function in SeuratDisk calculates start and end indices for data chunking. It takes the total data size (dsize) and desired chunk size (csize) as input. If csize is NA, it assumes a single chunk covering the entire dataset. The function returns a matrix where each row represents a chunk with its start and end points. ```r SeuratDisk:::ChunkPoints(100, 3) #> start end #> \[1,\ 1 3 #> \[2,\ 4 6 #> \[3,\ 7 9 #> \[4,\ 10 12 #> \[5,\ 13 15 #> \[6,\ 16 18 #> \[7,\ 19 21 #> \[8,\ 22 24 #> \[9,\ 25 27 #> [10,\ 28 30 #> [11,\ 31 33 #> [12,\ 34 36 #> [13,\ 37 39 #> [14,\ 40 42 #> [15,\ 43 45 #> [16,\ 46 48 #> [17,\ 49 51 #> [18,\ 52 54 #> [19,\ 55 57 #> [20,\ 58 60 #> [21,\ 61 63 #> [22,\ 64 66 #> [23,\ 67 69 #> [24,\ 70 72 #> [25,\ 73 75 #> [26,\ 76 78 #> [27,\ 79 81 #> [28,\ 82 84 #> [29,\ 85 87 #> [30,\ 88 90 #> [31,\ 91 93 #> [32,\ 94 96 #> [33,\ 97 99 #> [34,\ 100 100 SeuratDisk:::ChunkPoints(100, NA) #> start end #> [1,] 1 100 ``` -------------------------------- ### Managing Default Assay in h5Seurat Objects (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/h5Seurat-bindings.html These S3 methods allow you to get and set the default assay for an h5Seurat object. This is crucial for many Seurat operations that rely on a specified assay. ```r # S3 method for h5Seurat DefaultAssay(object, ...) # S3 method for h5Seurat DefaultAssay(object, ...) <- value ``` -------------------------------- ### Save Seurat Object to h5Seurat File Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Saves a Seurat object to an h5Seurat file using the SeuratDisk R package. This process automatically includes all assays, dimensional reductions, spatial images, and metadata. Ensure both Seurat and SeuratDisk packages are installed and loaded. ```r library(Seurat) library(SeuratDisk) library(SeuratData) # Load an example Seurat object InstallData(ds = "stxBrain") brain <- LoadData(ds = "stxBrain", type = "anterior1") # Process the Seurat object (example steps) brain <- UpdateSeuratObject(brain) brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE) brain <- RunPCA(brain) brain <- FindNeighbors(brain, dims = 1:30) brain <- FindClusters(brain, verbose = FALSE) brain <- RunUMAP(brain, dims = 1:30) # Save the Seurat object to an h5Seurat file SaveH5Seurat(brain, overwrite = TRUE) ``` -------------------------------- ### Generate HDF5 ASCII7 String Type with SeuratDisk Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/StringType.html This example shows how to generate an HDF5 string data type with ASCII7 encoding using the StringType function in SeuratDisk. It creates a fixed-width (7 bits) string with null termination and ASCII character set. ```r SeuratDisk:::StringType('ascii7') #> Class: H5T_STRING #> Datatype: H5T_STRING { #> STRSIZE 7; #> STRPAD H5T_STR_NULLTERM; #> CSET H5T_CSET_ASCII; #> CTYPE H5T_C_S1; #> } ``` -------------------------------- ### Get Class String with Package Info - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/GetClass.html The GetClass function in SeuratDisk generates a character vector representing an S4 class name, including its defining package. This is essential for preserving class information in HDF5 files. It handles exceptions for classes from specified packages, such as 'Seurat', by omitting the package prefix. The function takes the class name and an optional vector of package names to exclude. ```r SeuratDisk:::GetClass('Seurat') #> [1] "Seurat" SeuratDisk:::GetClass('Matrix') ``` -------------------------------- ### Create and Manipulate Loom Files Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Provides an R6 class interface for creating and manipulating loom files, supporting layers, attributes (global, row, column), and graph data. Enables adding expression matrices, metadata, and closing the file. ```r library(SeuratDisk) library(Matrix) # Create new loom file lfile <- loom$new(filename = "data.loom", mode = "w") # Add main matrix (required, features × cells) lfile$add_layer( x = expression_matrix, name = "matrix", transpose = TRUE, verbose = TRUE ) # Add additional layers lfile$add_layer( x = normalized_data, name = "normalized", transpose = TRUE ) # Add global attributes lfile$add_attribute( x = "Sample1", name = "sample_id", type = "global" ) # Add row (feature) attributes lfile$add_attribute( x = gene_names, name = "Gene", type = "row" ) # Add column (cell) attributes lfile$add_attribute( x = cell_types, name = "CellType", type = "col" ) # Add graph (sparse matrix) lfile$add_graph( x = knn_graph, name = "knn", type = "col" ) # Get version version <- lfile$version() # Close file lfile$close_all() ``` -------------------------------- ### Create h5Seurat File Connection Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Creates an h5Seurat file connection from a Seurat object, allowing programmatic access to the HDF5 file structure. This function requires the Seurat and SeuratDisk packages. It takes a Seurat object, a filename, and overwrite/verbose options as input, returning an object that allows inspection of assays, reductions, and metadata. ```r library(Seurat) library(SeuratDisk) pbmc <- LoadSeuratObject("pbmc.rds") # Convert and get file handle h5obj <- as.h5Seurat( x = pbmc, filename = "pbmc.h5seurat", overwrite = TRUE, verbose = TRUE ) # Access file structure h5obj[["assays"]] h5obj[["reductions"]] h5obj[["meta.data"]] # Check available datasets names(h5obj[["assays"]][["RNA"]]) # Close connection when done h5obj$close_all() ``` -------------------------------- ### Connect to HDF5 Files (h5Seurat, h5ad, loom) Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Establishes a connection to HDF5-based single-cell files (h5Seurat, h5ad, loom) with automatic format detection. Allows forcing a specific format and provides methods to access file structure, read data, and close the connection. ```r library(SeuratDisk) # Connect with automatic format detection h5file <- Connect("data.h5seurat") # Force connection to specific format h5ad_file <- Connect("data.h5ad", force = TRUE) # Access file structure names(h5file) # Read data expr_matrix <- h5file[["assays/RNA/data"]][] # Close when done h5file$close_all() ``` -------------------------------- ### HDF5 File Opening and Validation (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Includes functions for opening HDF5 files by path or index, and for validating file paths. These methods are fundamental for establishing a connection to an HDF5 file and ensuring its integrity before performing operations. ```r hdf5r::H5File$open() hdf5r::H5File$open_by_idx() hdf5r::H5File$path_valid() ``` -------------------------------- ### Assemble Seurat Command from h5Seurat File - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/AssembleObject.html Assembles a Seurat command object from a specified command within an h5Seurat file. Requires the SeuratDisk package and a connected h5Seurat file. ```r AssembleSeuratCommand(cmd, file, verbose = TRUE) ``` -------------------------------- ### Generate HDF5 UTF-8 String Type with SeuratDisk Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/StringType.html This example demonstrates how to generate an HDF5 string data type with UTF-8 encoding using the StringType function from the SeuratDisk package. It produces a variable-width string with null termination and UTF-8 character set. ```r SeuratDisk:::StringType() #> Class: H5T_STRING #> Datatype: H5T_STRING { #> STRSIZE H5T_VARIABLE; #> STRPAD H5T_STR_NULLTERM; #> CSET H5T_CSET_UTF8; #> CTYPE H5T_C_S1; #> } ``` -------------------------------- ### Assemble Graph from h5Seurat File - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/AssembleObject.html Assembles a graph object from a specified graph within an h5Seurat file. Requires the SeuratDisk package and a connected h5Seurat file. ```r AssembleGraph(graph, file, verbose = TRUE) ``` -------------------------------- ### Create a New Scdisk Object (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Initializes a new 'scdisk' object, which represents a connection to an on-disk HDF5 file. It allows specifying the filename and the mode of operation (read, write, append, etc.). The 'validate' argument controls file integrity checks upon connection. ```r scdisk$new(filename = NULL, mode = c("a", "r", "r+", "w", "w-", "x"), validate = TRUE, ...) ``` -------------------------------- ### Get and Register scdisk Subclasses in R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/RegisterSCDisk.html These functions allow retrieval and registration of scdisk subclass generators. GetSCDisk retrieves registered subclasses, either all of them or a specific one by name. RegisterSCDisk adds a new subclass generator to the internal registry. This is useful for functions that require class definitions or generators, not just object instances. ```R GetSCDisk() #> [1] "h5Seurat" GetSCDisk("h5Seurat") #> object generator #> Inherits from: #> Public: #> index: function () #> set.version: function (version) #> version: function () #> Private: #> index.internal: list #> versions: 3.1.2 3.1.5.9900 #> build.index: function (version) #> create: function (version, verbose = TRUE) #> validate: function (verbose = TRUE, ...) #> v3.1.2: function () #> v3.2.0: function () #> Parent env: #> Locked objects: TRUE #> Locked class: TRUE #> Portable: TRUE if (FALSE) { RegisterSCDisk(h5Seurat) } ``` -------------------------------- ### Assemble Image from h5Seurat File - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/AssembleObject.html Assembles an image object from a specified image within an h5Seurat file. Requires the SeuratDisk package and a connected h5Seurat file. ```r AssembleImage(image, file, verbose = TRUE) ``` -------------------------------- ### HDF5 File Listing and Information (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Offers methods to list directory contents, retrieve object information, and access object details by index or name within an HDF5 file. These functions are crucial for exploring and understanding the structure and contents of HDF5 datasets. ```r hdf5r::H5File$ls() hdf5r::H5File$obj_info() hdf5r::H5File$obj_info_by_idx() hdf5r::H5File$obj_info_by_name() ``` -------------------------------- ### Explore h5Seurat File Structure with Double Brackets (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Demonstrates using the double bracket operator `[[ ]]` to navigate and inspect the hierarchical structure of an h5Seurat file. This method allows viewing available assays, reductions, and their associated data without loading the entire object. ```r hfile[["assays"]] hfile[["assays/SCT"]] hfile[["reductions"]] hfile[["reductions/umap"]] ``` -------------------------------- ### Load Entire h5Seurat Object (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Shows how to load an entire h5Seurat object into memory using the LoadH5Seurat function. This is the default behavior and loads all assays and associated data. ```r brain2 <- LoadH5Seurat("anterior1.h5Seurat") brain2 ``` -------------------------------- ### Load Seurat Object from h5Seurat File Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Loads a Seurat object from an h5Seurat file. This function supports selective loading of specific components such as assays, reductions, graphs, and metadata, allowing for memory-efficient data retrieval. It requires the Seurat and SeuratDisk packages and takes the filename as a primary input. ```r library(Seurat) library(SeuratDisk) # Load entire object pbmc <- LoadH5Seurat("pbmc.h5Seurat") # Selective loading - only RNA assay with data slot pbmc_subset <- LoadH5Seurat( file = "pbmc.h5Seurat", assays = list(RNA = "data"), # Only load data slot reductions = c("pca", "umap"), # Only specific reductions graphs = NULL, # Load all graphs meta.data = TRUE, commands = FALSE, verbose = TRUE ) # Load only specific assay slots across all assays pbmc_data_only <- LoadH5Seurat( file = "pbmc.h5Seurat", assays = c("data", "counts"), # Only data and counts for all assays reductions = FALSE, # Skip reductions graphs = FALSE, # Skip graphs meta.data = TRUE ) # Returns: Seurat object with requested components ``` -------------------------------- ### Convert AnnData to h5Seurat and Load Seurat Object Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/convert-anndata.html This process involves two main steps: first, converting an AnnData file to an h5Seurat file using the `Convert` function, and second, loading the generated h5Seurat file into a Seurat object using the `LoadH5Seurat` function. The `Convert` function requires the input AnnData file path and the destination format ('h5seurat'), with an option to overwrite existing files. The `LoadH5Seurat` function takes the path to the h5Seurat file as input. ```r Convert("pbmc3k_final.h5ad", dest = "h5seurat", overwrite = TRUE) pbmc3k <- LoadH5Seurat("pbmc3k_final.h5seurat") pbmc3k ``` -------------------------------- ### Load Specific Assay from h5Seurat File (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Demonstrates loading only a specific assay (e.g., 'SCT') from an h5Seurat file using the `assays` parameter in LoadH5Seurat. This is useful for managing memory when only parts of the dataset are needed. ```r brain2 <- LoadH5Seurat("anterior1.h5Seurat", assays = "SCT") brain2 ``` -------------------------------- ### HDF5 File Printing (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Allows printing an HDF5 file object, which typically outputs a summary of the file's structure and contents. This is a helpful utility for quick inspection of HDF5 file metadata. ```r hdf5r::H5File$print() ``` -------------------------------- ### Assemble Assay from h5Seurat File - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/AssembleObject.html Assembles an Assay object from a specified assay within an h5Seurat file. Requires the SeuratDisk package and a connected h5Seurat file. Optionally accepts specific slots to load. ```r AssembleAssay(assay, file, slots = NULL, verbose = TRUE) ``` -------------------------------- ### GetObject API Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/GetObject.html Functions to determine and retrieve specific objects (assays, reductions, graphs, images) from an h5Seurat file. ```APIDOC ## GetAssays ### Description Determines which assays and their corresponding slots to load from an h5Seurat file. ### Method `GetAssays(assays, index)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **assays** (character vector or named list or NULL) - Specifies which assays and slots to load. Can be assay names, slot names ('counts', 'data', 'scale.data'), a list mapping assays to slots, or NULL for all assays. - **index** (h5SI object) - An index object for the h5Seurat file. ### Request Example ```json { "assays": ["RNA", "ADT"], "index": "" } ``` ### Response #### Success Response (200) - **assays** (named list) - A list where keys are assay names and values are vectors of slots to load from that assay. #### Response Example ```json { "assays": { "RNA": ["counts", "data"], "ADT": ["data"] } } ``` --- ## GetCommands ### Description Retrieves command log names associated with a specific assay. ### Method `GetCommands(index, assays = NULL)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **index** (h5SI object) - An index object for the h5Seurat file. - **assays** (character vector or NULL) - The name(s) of the assay(s) to get commands for. If NULL, considers all assays. ### Request Example ```json { "index": "", "assays": "RNA" } ``` ### Response #### Success Response (200) - **commands** (character vector) - A vector of command log names derived from the specified assay. #### Response Example ```json { "commands": ["command1", "command2"] } ``` --- ## GetDimReducs ### Description Identifies dimensional reduction objects to load from an h5Seaturat file, considering assay-specific and global reductions. ### Method `GetDimReducs(reductions, index, assays = NULL)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reductions** (character vector, NULL, NA, or FALSE) - Specifies which reductions to load. Can be reduction names, NULL for all, NA for global, or FALSE for none. Only reductions associated with loaded assays or marked as global will be loaded. - **index** (h5SI object) - An index object for the h5Seurat file. - **assays** (character vector or NULL) - The name(s) of the assay(s) to consider for associated reductions. If NULL, considers all assays. ### Request Example ```json { "reductions": ["UMAP", "tSNE"], "index": "", "assays": ["RNA"] } ``` ### Response #### Success Response (200) - **reductions** (character vector) - A vector of reduction names that are derived from the specified assays or are global. #### Response Example ```json { "reductions": ["UMAP", "tSNE", "pca"] } ``` --- ## GetGraphs ### Description Determines which graph objects to load from an h5Seurat file, specifically those associated with loaded assays. ### Method `GetGraphs(graphs, index, assays = NULL)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **graphs** (character vector, NULL, or FALSE) - Specifies which graphs to load. Can be graph names, NULL for all, or FALSE for none. Only graphs associated with loaded assays will be loaded. - **index** (h5SI object) - An index object for the h5Seurat file. - **assays** (character vector or NULL) - The name(s) of the assay(s) to consider for associated graphs. If NULL, considers all assays. ### Request Example ```json { "graphs": ["SNN", "KNN"], "index": "", "assays": ["RNA"] } ``` ### Response #### Success Response (200) - **graphs** (character vector) - A vector of graph names that are derived from the specified assays. #### Response Example ```json { "graphs": ["SNN", "KNN", "graph1"] } ``` --- ## GetImages ### Description Identifies image objects to load from an h5Seurat file, including assay-specific and global images. ### Method `GetImages(images, index, assays = NULL)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **images** (character vector, NULL, NA, or FALSE) - Specifies which images to load. Can be image names, NULL for all, NA for global, or FALSE for none. - **index** (h5SI object) - An index object for the h5Seurat file. - **assays** (character vector or NULL) - The name(s) of the assay(s) to consider for associated images. If NULL, considers all assays. Only images associated with loaded assays or marked as global will be loaded. ### Request Example ```json { "images": ["Visium", "ST"], "index": "", "assays": ["RNA"] } ``` ### Response #### Success Response (200) - **images** (character vector) - A vector of image names that are derived from the specified assays or are global. #### Response Example ```json { "images": ["Visium", "ST", "image1"] } ``` ``` -------------------------------- ### Convert Seurat Object to h5ad for Scanpy Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Demonstrates the process of saving a fully analyzed Seurat object to the h5Seurat format and then converting it to the h5ad format, which is compatible with Scanpy in Python. This preserves all computed reductions, graphs, and metadata. It's designed for large datasets with minimal memory overhead during conversion. ```r library(Seurat) library(SeuratDisk) # Complete Seurat analysis workflow pbmc <- CreateSeuratObject(counts = pbmc_counts, project = "PBMC") pbmc <- NormalizeData(pbmc) pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000) pbmc <- ScaleData(pbmc) pbmc <- RunPCA(pbmc, features = VariableFeatures(pbmc)) pbmc <- FindNeighbors(pbmc, dims = 1:10) pbmc <- FindClusters(pbmc, resolution = 0.5) pbmc <- RunUMAP(pbmc, dims = 1:10) # Add custom metadata pbmc$sample <- "PBMC_sample1" pbmc$batch <- factor(rep(c("batch1", "batch2"), length.out = ncol(pbmc))) # Save to h5Seurat SaveH5Seurat(pbmc, filename = "pbmc_analyzed.h5Seurat", overwrite = TRUE) # Convert to h5ad for Scanpy Convert("pbmc_analyzed.h5Seurat", dest = "h5ad", overwrite = TRUE) # In Python/Scanpy: # import scanpy as sc # adata = sc.read_h5ad("pbmc_analyzed.h5ad") # sc.pl.umap(adata, color=['louvain', 'batch']) ``` -------------------------------- ### HDF5 File Mounting and Unmounting (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Provides functionality to mount and unmount HDF5 file systems. Mounting allows treating an HDF5 file as a directory structure, while unmounting detaches it. This is useful for advanced file system integration. ```r hdf5r::H5File$mount() hdf5r::H5File$unmount() ``` -------------------------------- ### Convert Scanpy h5ad to h5Seurat for Seurat Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Illustrates how to import an AnnData object (h5ad format) created in Scanpy into Seurat (h5Seurat format). This workflow preserves expression matrices, dimensional reductions, and metadata from the Scanpy analysis. The converted object can then be used with Seurat's extensive analysis and visualization capabilities. ```r library(Seurat) library(SeuratDisk) # Convert h5ad from Scanpy to h5Seurat Convert( source = "scanpy_processed.h5ad", dest = "h5seurat", assay = "RNA", overwrite = TRUE ) # Load into Seurat pbmc <- LoadH5Seurat("scanpy_processed.h5seurat") # Verify loaded components print(pbmc) Assays(pbmc) Reductions(pbmc) head(pbmc[[]]) # Continue analysis in Seurat pbmc <- FindClusters(pbmc, resolution = 0.8) DimPlot(pbmc, reduction = "umap", group.by = "leiden") FeaturePlot(pbmc, features = c("CD3D", "CD79A", "MS4A1")) # Find markers markers <- FindAllMarkers(pbmc, only.pos = TRUE, min.pct = 0.25) ``` -------------------------------- ### Convert h5Seurat to H5AD (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/H5SeuratToH5AD.html The H5SeuratToH5AD function converts an h5Seurat file to an H5AD file. It takes the source h5Seurat file path and the destination H5AD file path as primary arguments. Optional arguments include specifying the assay to convert, whether to overwrite an existing file, and whether to display progress updates. The function returns a handle to the destination H5AD file. ```r H5SeuratToH5AD( source, dest, assay = H5SeuratBindings::DefaultAssay(object = source), overwrite = FALSE, verbose = TRUE ) ``` -------------------------------- ### R: Convert Sparse Matrix Pointers to Indices and Vice Versa Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/SparsePointers.html This R code demonstrates how to convert sparse matrix pointers to indices using PointerToIndex and indices to pointers using IndexToPointer from the SeuratDisk package. It also shows how to reconstruct sparse matrices using the converted indices and pointers with the Matrix package. ```R # \donttest { dat <- dat <- c(0, 0, 1, 4, 0, 2, 0, 9, 0) smat <- Matrix::Matrix(data = dat, nrow = 3, sparse = TRUE) j <- SeuratDisk:::PointerToIndex(p = smat@p) Matrix::sparseMatrix(i = smat@i + 1, j = j, x = smat@x) #> 3 x 3 sparse Matrix of class "dgCMatrix" #> #> [1,] . 4 . #> [2,] . . 9 #> [3,] 1 2 . p <- SeuratDisk:::IndexToPointer(j = j) Matrix::sparseMatrix(i = smat@i + 1, p = p, x= smat@x) #> 3 x 3 sparse Matrix of class "dgCMatrix" #> #> [1,] . 4 . #> [2,] . . 9 #> [3,] 1 2 . # } ``` -------------------------------- ### Convert h5Seurat to Seurat Object - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/LoadH5Seurat.html Converts an h5Seurat object to a Seurat object, allowing selective loading of components. This method provides fine-grained control over which assays, reductions, graphs, images, metadata, commands, and other data are included in the resulting Seurat object. It is useful for migrating data stored in the h5Seurat format to the standard Seurat object structure. ```R as.Seurat( x, assays = NULL, reductions = NULL, graphs = NULL, images = NULL, meta.data = TRUE, commands = TRUE, misc = TRUE, tools = TRUE, verbose = TRUE, ... ) ``` -------------------------------- ### Connect to h5Seurat File in R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Establishes a connection to an h5Seurat file, creating an h5Seurat object that serves as an interface to the HDF5 data. This allows for querying without loading the entire dataset into memory. ```R hfile <- Connect("anterior1.h5Seurat") hfile ``` -------------------------------- ### H5ADToH5Seurat Function Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/H5ADToH5Seurat.html Converts AnnData/H5AD files to h5Seurat files. This function handles the complexities of mapping data from the AnnData structure to the h5Seurat format, including expression matrices and metadata. ```APIDOC ## H5ADToH5Seurat ### Description Converts AnnData/H5AD files to h5Seurat files. ### Method R function ### Endpoint N/A (R function) ### Parameters #### Arguments - **source** (character) - Source dataset (path to AnnData/H5AD file). - **dest** (character) - Name of destination dataset (path for the h5Seurat file). - **assay** (character) - Default: "RNA". Name of assay to write out (when converting to h5Seurat) or store assay data as (when converting from h5Seurat). - **overwrite** (logical) - Default: FALSE. Overwrite existing destination file. - **verbose** (logical) - Default: TRUE. Show progress updates. ### Request Example ```R H5ADToH5Seurat(source = "path/to/your_file.h5ad", dest = "path/to/output.h5seurat") ``` ### Response #### Success Response Returns a handle to `dest` as an `h5Seurat` object. #### Response Example ```R # Example of a returned h5Seurat object handle (actual object is a file path) 'path/to/output.h5seurat' ``` ### AnnData/H5AD to h5Seurat Conversion Details #### Expression data The conversion automatically fills expression matrices (`counts`, `data`, `scale.data`) based on the presence of `/X` and `/raw/X` in the AnnData file: - `counts` will be filled with `/raw/X` if present; otherwise, it will be filled with `/X`. - `data` will be filled with `/raw/X` if `/raw/X` is present and `/X` is dense; otherwise, it will be filled with `/X`. - `scale.data` will be filled with `/X` if it is dense; otherwise, it will be empty. Feature names are taken from the feature-level metadata. #### Feature-level metadata Feature-level metadata is added to the `meta.features` datasets in each assay. Feature names are determined by the "_index" attribute, the "_index" dataset, or the "index" dataset, in that order. Metadata is populated with `/raw/var` if present, otherwise with `/var`. If both are present, `/raw/var` is used first, and then `/var` is added. For columns common to both, the values from `/var` take precedence. If `/var` has fewer features than `/raw/var`, only the features present in `/var` will be overwritten. #### Cell-level metadata Cell-level metadata is added to `meta.data`. Row names are determined by the "_index" attribute, the "_index" dataset, or the "index" dataset, in that order, and added to the "cell.names" dataset. If the "__categories" dataset is present, each dataset within it will be stored as a factor group. Cell-level metadata is added as an HDF5 group unless factors are not present and `SeuratDisk.dtype.dataframe_as_group` is set to `FALSE`. ``` -------------------------------- ### Assemble Dimensionality Reduction from h5Seurat File - R Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/AssembleObject.html Assembles a dimensionality reduction object from a specified reduction within an h5Seurat file. Requires the SeuratDisk package and a connected h5Seurat file. ```r AssembleDimReduc(reduction, file, verbose = TRUE) ``` -------------------------------- ### Convert Between h5Seurat and h5ad Formats Source: https://context7.com/mojaveazure/seurat-disk/llms.txt Converts HDF5-based single-cell files between h5Seurat and AnnData/h5ad formats on disk with minimal memory usage. This facilitates interoperability between Seurat (R) and Scanpy (Python) workflows. The function requires the SeuratDisk package and takes source and destination file paths, along with specified assay and overwrite options. ```r library(SeuratDisk) # Convert h5Seurat to h5ad for use in Scanpy Convert( source = "pbmc.h5Seurat", dest = "h5ad", assay = "RNA", overwrite = FALSE, verbose = TRUE ) # Creates: pbmc.h5ad # Convert h5ad to h5Seurat for use in Seurat Convert( source = "scanpy_processed.h5ad", dest = "h5seurat", assay = "RNA", overwrite = FALSE, verbose = TRUE ) # Creates: scanpy_processed.h5seurat # Then load into Seurat pbmc <- LoadH5Seurat("scanpy_processed.h5seurat") # Conversion preserves: # - Expression matrices (counts, data, scale.data) # - Feature and cell metadata # - Dimensional reductions (PCA, UMAP, tSNE) # - Nearest-neighbor graphs # - Layers (for multi-assay data) ``` -------------------------------- ### Full Append of Seurat Object with AppendData Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Demonstrates performing a 'full append' operation using AppendData, which loads all remaining data from the h5Seurat file into the Seurat object. This is achieved by setting the 'assays', 'reductions', 'graphs', and 'images' parameters to their default 'NULL' values. ```r brain2 <- AppendData("anterior1.h5Seurat", brain2) ``` -------------------------------- ### Accessing and Setting Keys for H5Group Objects (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/h5Seurat-bindings.html The Key() S3 method retrieves the key associated with an H5Group object. Keys can be used to identify and access specific groups or datasets within the h5Seurat file. ```r # S3 method for H5Group Key(object, ...) ``` -------------------------------- ### Access h5Seurat File Structure Programmatically Source: https://context7.com/mojaveazure/seurat-disk/llms.txt The h5Seurat R6 class provides direct programmatic access to the structure of an h5Seurat file. It allows reading, writing, and indexing of Seurat data stored in HDF5 format. Key functionalities include retrieving the file index, version information, component names, and specific datasets like cell embeddings or metadata. Requires the SeuratDisk package. ```r library(SeuratDisk) # Open existing h5Seurat file h5file <- h5Seurat$new(filename = "pbmc.h5seurat", mode = "r") # Get file index showing structure index <- h5file$index() print(index) # Access version information version <- h5file$version() # Access file components assays <- names(h5file[["assays"]]) reductions <- names(h5file[["reductions"]]) # Read specific datasets cell_names <- h5file[["cell.names"]][] pca_embeddings <- h5file[["reductions/pca/cell.embeddings"]][] # Get metadata metadata <- as.data.frame(h5file[["meta.data"]]) # Check default assay default_assay <- h5attr(h5file, "active.assay") # Close connection h5file$close_all() ``` -------------------------------- ### Convert Seurat to AnnData via h5Seurat (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/convert-anndata.html This R code snippet demonstrates the process of converting a Seurat object to an AnnData file. It first saves the Seurat object to an h5Seurat file using `SaveH5Seurat` and then converts this h5Seurat file to an h5ad (AnnData) file using the `Convert` function. This enables data analysis in Python using Scanpy. ```r library(Seurat) library(SeuratData) library(SeuratDisk) InstallData("pbmc3k") data("pbmc3k.final") # Convert Seurat object to h5Seurat format SaveH5Seurat(pbmc3k.final, filename = "pbmc3k.h5Seurat") # Convert h5Seurat to AnnData (h5ad) format Convert("pbmc3k.h5Seurat", dest = "h5ad") ``` -------------------------------- ### Load Seurat Object with Specific Reductions Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Loads a Seurat object from an h5Seurat file, specifying which dimensional reductions to load. The 'reductions' parameter controls this. Special values include NULL (all reductions), NA (global reductions only), and FALSE (no reductions). Note that reductions are tied to assays. ```r brain2 <- LoadH5Seurat("anterior1.h5Seurat", assays = "Spatial", reductions = "pca") brain2 #> An object of class Seurat #> 31053 features across 2696 samples within 1 assay #> Active assay: Spatial (31053 features, 0 variable features) ``` -------------------------------- ### Generate Chunk Points for HDF5 Dataset (R) Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/reference/scdisk-class.html Calculates chunk points for a specified dataset within an HDF5 file. This function is useful for optimizing data access by dividing large datasets into manageable chunks. It allows specifying the chunking margin and size. ```r scdisk$chunk.points(dataset, MARGIN = getOption("SeuratDisk.chunking.MARGIN", default = "largest"), csize = NULL) ``` -------------------------------- ### Append Specific Assay with AppendData Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Illustrates appending data for a specific assay ('SCT') from an h5Seurat file to an existing Seurat object, while explicitly excluding other data types like reductions, graphs, and images by setting them to FALSE. ```r brain2 <- AppendData("anterior1.h5Seurat", brain2, assays = "SCT", reductions = FALSE, graphs = FALSE, images = FALSE) ``` -------------------------------- ### Append Global Reductions with AppendData Source: https://github.com/mojaveazure/seurat-disk/blob/master/docs/articles/h5Seurat-load.html Shows how to use the AppendData function to add global dimensional reductions to an existing Seurat object without loading additional assay data. This is achieved by setting 'assays' to FALSE and 'reductions' to NA. ```r brain2 <- AppendData("anterior1.h5Seurat", brain2, assays = FALSE, reductions = NA, graphs = FALSE, images = NULL) ```