### Install CellBench R Package Source: https://github.com/shians/cellbench/blob/devel/README.md This snippet shows how to install the CellBench R package from GitHub using the `remotes` package. It includes options to control the build process. ```r if (!require(remotes)) install.packages("remotes") remotes::install_github("shians/CellBench", ref = "R-3.5", build_opts = c("--no-resave-data", "--no-manual")) ``` -------------------------------- ### Chain Method Applications in R Source: https://github.com/shians/cellbench/blob/devel/README.md Illustrates how to chain multiple `apply_methods` calls to expand the `benchmark_tbl` combinatorially. This allows for computing combinations of different methods, such as applying both correlation and covariance, followed by mean and median calculations. ```r library(CellBench) sample1 <- data.frame( x = matrix(runif(25), nrow = 5, ncol = 5) ) sample2 <- data.frame( x = matrix(runif(25), nrow = 5, ncol = 5) ) datasets <- list( sample1 = sample1, sample2 = sample2 ) transform <- list( correlation = cor, covariance = cov ) metric <- list( mean = mean, median = median ) datasets %>% apply_methods(transform) %>% apply_methods(metric) ``` -------------------------------- ### Apply Single Method to Datasets in R Source: https://github.com/shians/cellbench/blob/devel/README.md Demonstrates the basic usage of the `apply_methods` function in CellBench. It takes a list of datasets and a list of transformation functions (e.g., correlation, covariance) and applies them, returning a `benchmark_tbl`. ```r library(CellBench) sample1 <- data.frame( x = matrix(runif(25), nrow = 5, ncol = 5) ) sample2 <- data.frame( x = matrix(runif(25), nrow = 5, ncol = 5) ) datasets <- list( sample1 = sample1, sample2 = sample2 ) transform <- list( correlation = cor, covariance = cov ) datasets %>% apply_methods(transform) ``` -------------------------------- ### POST /collapse_pipeline Source: https://context7.com/shians/cellbench/llms.txt Collapses a benchmark table into a summary format, creating pipeline strings that represent the full analysis path for reporting and visualization. ```APIDOC ## POST /collapse_pipeline ### Description Collapses a benchmark table into a summary with pipeline strings and results. Useful for visualization and reporting where a single string describes the full analysis path. ### Method POST ### Endpoint /collapse_pipeline ### Parameters #### Query Parameters - **sep** (string) - Optional - Custom separator for the pipeline string (default: " >> ") - **data.name** (boolean) - Optional - Whether to include the data name in the pipeline string (default: TRUE) ### Request Example { "res": "benchmark_tbl_object", "sep": " -> ", "data.name": false } ### Response #### Success Response (200) - **pipeline** (factor) - The collapsed pipeline path string - **result** (numeric) - The computed result value ``` -------------------------------- ### POST /cache_method Source: https://context7.com/shians/cellbench/llms.txt Wraps a function to enable disk-based caching, preventing recomputation of expensive methods when called with identical arguments. ```APIDOC ## POST /cache_method ### Description Enables disk-based caching of method results. Cached methods return stored results when called with identical arguments. ### Method POST ### Endpoint /cache_method ### Parameters #### Request Body - **method** (function) - Required - The expensive function to wrap ### Request Example { "method": "expensive_computation_function" } ### Response #### Success Response (200) - **cached_method** (function) - The wrapped function with caching enabled ``` -------------------------------- ### Preview Matrices with mhead Source: https://context7.com/shians/cellbench/llms.txt Displays a square n-by-n block from the top-left corner of a 2D object. This utility prevents console flooding when inspecting large matrices. ```r library(CellBench) x <- matrix(runif(100), nrow = 10, ncol = 10) # Default 6x6 block mhead(x) # Custom size mhead(x, n = 3) ``` -------------------------------- ### Compare Multithreading Performance in CellBench Source: https://github.com/shians/cellbench/wiki/Quirky-Behaviours This snippet demonstrates the performance discrepancy between single-threaded and multi-threaded execution in CellBench. It uses the apply_methods function with an identity function to isolate the overhead caused by thread management. ```R library(CellBench) do_nothing <- list( nothing = identity ) data <- load_sc_data() # the following runs slowly set_cellbench_threads(4) res <- data %>% apply_methods(do_nothing) # the following runs instantly set_cellbench_threads(1) res <- data %>% apply_methods(do_nothing) ``` -------------------------------- ### Apply Methods to Datasets and Benchmark Tables using CellBench Source: https://context7.com/shians/cellbench/llms.txt The `apply_methods` function is the core of CellBench, enabling the application of a list of functions (methods) to a list of datasets or an existing benchmark table. It generates a `benchmark_tbl` that systematically records which methods were applied to which data and stores the results. This function supports combinatorial designs by allowing chaining of multiple `apply_methods` calls, testing all combinations of methods across pipeline steps. Parallel execution is supported when threading is enabled. ```r library(CellBench) # Create a list of datasets datasets <- list( sample1 = data.frame(x = matrix(runif(25), nrow = 5, ncol = 5)), sample2 = data.frame(x = matrix(runif(25), nrow = 5, ncol = 5)) ) # Define transformation methods transform <- list( correlation = cor, covariance = cov ) # Apply methods to datasets res <- datasets %>% apply_methods(transform) # Result: ## # A tibble: 4 x 3 ## data transform result ## ## 1 sample1 correlation ## 2 sample1 covariance ## 3 sample2 correlation ## 4 sample2 covariance # Chain multiple method applications for combinatorial design metric <- list( mean = mean, median = median ) full_results <- datasets %>% apply_methods(transform) %>% apply_methods(metric) # Result: 8 rows (2 datasets x 2 transforms x 2 metrics) ## # A tibble: 8 x 4 ## data transform metric result ## ## 1 sample1 correlation mean 0.0602 ## 2 sample1 correlation median -0.0520 ## ... ``` -------------------------------- ### Time Method Execution with CellBench Source: https://context7.com/shians/cellbench/llms.txt The `time_methods` function in CellBench is similar to `apply_methods` but specifically designed to record the execution time of each applied method. It ensures fair timing comparisons by running methods in a single-threaded manner. The function returns a `benchmark_timing_tbl` which includes both the results of the methods and their associated timing data (user, system, and elapsed time). The timing information can be extracted using `unpack_timing()` or removed to obtain a standard `benchmark_tbl` using `strip_timing()`. ```r library(CellBench) # Create large dataset for timing datasets <- list( set1 = 1:1e7 ) # Define transformation methods transform <- list( sqrt = sqrt, log = log ) # Time the methods timing_results <- time_methods(datasets, transform) # Extract timing information timing_results %>% unpack_timing() # Result: ## # A tibble: 2 x 5 ## data transform user system elapsed ## ## 1 set1 sqrt 0.045s 0.012s 0.057s ## 2 set1 log 0.038s 0.009s 0.047s # Strip timing to get regular benchmark_tbl benchmark_tbl <- timing_results %>% strip_timing() ``` -------------------------------- ### Generate Function Combinations with fn_arg_seq Source: https://context7.com/shians/cellbench/llms.txt Creates a list of functions by iterating over parameter combinations. This is useful for testing multiple configurations of a single algorithm, such as varying parameters for kmeans clustering. ```r f <- function(x, y, z) { x + y + z } f_list <- fn_arg_seq(f, y = 1:2, z = 3:4) clustering <- fn_arg_seq(kmeans, centers = 2:5) datasets <- list(data1 = iris[, 1:4]) cluster_results <- datasets %>% apply_methods(clustering) ``` -------------------------------- ### Access Packaged Sample Data with cellbench_file Source: https://context7.com/shians/cellbench/llms.txt Retrieves file paths for sample datasets included in the CellBench package. This function is essential for loading standard test data like 10x or CelSeq samples for benchmarking. ```r library(CellBench) # List available files cellbench_file() # Get path to specific file path <- cellbench_file("10x_sce_sample.rds") # Load sample data sample_10x <- readRDS(cellbench_file("10x_sce_sample.rds")) ``` -------------------------------- ### Load CellBench Benchmark Datasets in R Source: https://context7.com/shians/cellbench/llms.txt Loads CellBench benchmark datasets. Data is downloaded on the first call and cached locally for subsequent use. Various subsets of data can be loaded, including single-cell and mixed RNA/cell datasets. ```r library(CellBench) # Load all datasets all_data <- load_all_data() ## Contains: sc_10x, sc_celseq, sc_dropseq, cell_mix1-5, mrna_mix_celseq, mrna_mix_sortseq # Load specific subsets sc_data <- load_sc_data() ## Contains: sc_10x, sc_celseq, sc_dropseq mrna_data <- load_mrna_mix_data() ## Contains: mrna_mix_celseq, mrna_mix_sortseq cell_data <- load_cell_mix_data() ## Contains: cell_mix1, cell_mix2, cell_mix3, cell_mix4, cell_mix5 # Use directly in benchmark datasets <- load_sc_data() norm_methods <- list( raw = SingleCellExperiment::counts, cpm = function(x) { counts <- SingleCellExperiment::counts(x) t(t(1e6 * counts) / colSums(counts)) } ) results <- datasets %>% apply_methods(norm_methods) ``` -------------------------------- ### Convert Benchmark Tables to Lists with as_pipeline_list Source: https://context7.com/shians/cellbench/llms.txt Converts a benchmark table into a named list where keys represent the full pipeline path. This structure is ideal for integration with base R apply functions. ```r result_list <- as_pipeline_list(res) lapply(result_list, mean) ``` -------------------------------- ### Summarize Benchmark Pipelines with collapse_pipeline Source: https://context7.com/shians/cellbench/llms.txt Collapses a benchmark table into a summary format where each row represents a unique pipeline path and its result. This facilitates easier visualization and reporting of complex benchmark results. ```r res <- datasets %>% apply_methods(add_noise) %>% apply_methods(metric) collapsed <- collapse_pipeline(res) collapse_pipeline(res, sep = " -> ") collapse_pipeline(res, data.name = FALSE) ``` -------------------------------- ### Generate Pipeline Separators with arrow_sep Source: https://context7.com/shians/cellbench/llms.txt Creates arrow separator strings for pipeline descriptions. Supports both standard and Unicode arrow formats for use in pipeline visualization. ```r library(CellBench) # Right arrow (default) arrow_sep("right") # Unicode arrows arrow_sep("right", unicode = TRUE) # Use with collapse_pipeline collapse_pipeline(results, sep = arrow_sep("right")) ``` -------------------------------- ### Advanced Parallelism with set_cellbench_bpparam Source: https://context7.com/shians/cellbench/llms.txt Allows for fine-grained control over parallel execution by passing a custom BiocParallel parameter object, such as MulticoreParam or SnowParam. ```r param <- MulticoreParam(workers = 4, stop.on.error = FALSE, progressbar = TRUE) set_cellbench_bpparam(param) ``` -------------------------------- ### Configure Parallel Execution with set_cellbench_threads Source: https://context7.com/shians/cellbench/llms.txt Sets the number of threads for parallel execution using BiocParallel. It supports both Unix and Windows environments, though users should be cautious of memory usage when scaling threads. ```r set_cellbench_threads(4) results <- datasets %>% apply_methods(methods) set_cellbench_threads(1) ``` -------------------------------- ### Cache Method Results with cache_method Source: https://context7.com/shians/cellbench/llms.txt Enables disk-based caching for expensive functions to avoid redundant computations. Methods wrapped in cache_method will return stored results if called with identical arguments. ```r set_cellbench_cache_path(".CellBenchCache") methods <- list(mean = cache_method(expensive_method1), sd = cache_method(expensive_method2)) results <- datasets %>% apply_methods(methods) clear_cellbench_cache() ``` -------------------------------- ### Generate Function Variants with fn_arg_seq in CellBench Source: https://context7.com/shians/cellbench/llms.txt The `fn_arg_seq` function in CellBench is used to generate a list of function variants by pre-applying sequences of values to specific arguments. This is particularly useful for performing parameter sweeps or hyperparameter tuning within a benchmarking context. By creating these function variants, users can systematically test how different parameter settings affect method performance across datasets. ```r library(CellBench) ``` -------------------------------- ### Create Validated Function Lists with CellBench's fn_list Source: https://context7.com/shians/cellbench/llms.txt The `fn_list` function is a utility in CellBench for creating validated lists of functions. It ensures that all elements within the list are named functions, providing more informative error messages during list construction compared to standard R lists. This validated list can then be seamlessly used with functions like `apply_methods` to ensure that the methods being applied are correctly defined and named. ```r library(CellBench) # Create a validated function list methods <- fn_list( mean = mean, median = median, sd = sd ) # Error handling example - this will fail with informative message # fn_list(mean, median) # Error: all fn_list members must have names # Use with apply_methods datasets <- list( set1 = rnorm(500, mean = 2, sd = 1), set2 = rnorm(500, mean = 1, sd = 2) ) results <- datasets %>% apply_methods(methods) ``` -------------------------------- ### Split Pipeline Steps with split_step Source: https://context7.com/shians/cellbench/llms.txt Transforms a single pipeline step column into multiple distinct columns. This is useful for decomposing combined method steps into individual logical components for analysis. ```r library(CellBench) # Split into separate logical steps res_split <- res %>% split_step("combined", c("normalization", "transformation")) ``` -------------------------------- ### Create Validated Data Lists with CellBench's data_list Source: https://context7.com/shians/cellbench/llms.txt The `data_list` function in CellBench provides a way to create validated lists of datasets. It enforces that all elements in the list are named and share the same class, which is crucial for maintaining consistency within benchmark datasets. This validation helps prevent errors that might arise from inconsistent data structures when applying methods. The validated data list can then be used with `apply_methods` for benchmarking. ```r library(CellBench) # Create a validated data list data(iris) datasets <- data_list( data1 = iris[1:20, ], data2 = iris[21:40, ], data3 = iris[41:60, ] ) # Error handling - fails if elements have different classes # data_list( # data1 = iris, # data2 = matrix(1:10) # Error: all data_list members must have same class # ) # Use with apply_methods metric <- fn_list( nrow = nrow, ncol = ncol ) results <- datasets %>% apply_methods(metric) ``` -------------------------------- ### POST /set_cellbench_threads Source: https://context7.com/shians/cellbench/llms.txt Configures the number of threads used for parallel method application within the CellBench framework. ```APIDOC ## POST /set_cellbench_threads ### Description Sets the number of threads CellBench uses for parallel method application. Uses BiocParallel internally. ### Method POST ### Endpoint /set_cellbench_threads ### Parameters #### Request Body - **threads** (integer) - Required - Number of threads to utilize ### Request Example { "threads": 4 } ### Response #### Success Response (200) - **status** (string) - Confirmation of thread count update ``` -------------------------------- ### Randomly Sample Cells or Genes in R Source: https://context7.com/shians/cellbench/llms.txt Randomly samples cells (columns) or genes (rows) from SingleCellExperiment objects. This function is useful for creating subsamples for testing or for generating multiple random subsets for comparative analysis. ```r library(CellBench) sample_sce <- readRDS(cellbench_file("celseq_sce_sample.rds")) # Sample 10 cells subsampled_cells <- sample_cells(sample_sce, 10) # Sample 50 genes subsampled_genes <- sample_genes(sample_sce, 50) # Use for creating multiple subsamples datasets <- list( subsample1 = sample_genes(sample_sce, 1000), subsample2 = sample_genes(sample_sce, 1000), subsample3 = sample_genes(sample_sce, 1000) ) methods <- list( mean_expr = function(x) mean(SingleCellExperiment::counts(x)) ) results <- datasets %>% apply_methods(methods) ``` -------------------------------- ### Check Benchmark Table for Errors in R Source: https://context7.com/shians/cellbench/llms.txt Checks if any tasks in a benchmark_tbl produced errors. This function can optionally report which rows contain errors, providing a verbose output to identify specific error locations within the benchmark results. ```r library(CellBench) methods <- list( sqrt_safe = function(x) sqrt(abs(x)), sqrt_unsafe = function(x) sqrt(x), # fails on negative log_safe = function(x) log(abs(x) + 1) ) datasets <- list( positive = 1:100, mixed = -50:50 ) results <- datasets %>% apply_methods(methods) # Quick check for any errors if (any_task_errors(results)) { message("Some tasks failed!") } # Verbose mode to identify error locations any_task_errors(results, verbose = TRUE) ## task_error in row 4 ## task_error in row 5 ## [1] TRUE ``` -------------------------------- ### Check for Task Errors in R Source: https://context7.com/shians/cellbench/llms.txt Checks if elements in a result list are task_error objects, useful for filtering benchmark results. It can be used to identify failed computations and filter datasets to include only successful or failed results for debugging. ```r library(CellBench) # Create methods including one that fails methods <- list( good = function(x) mean(x), bad = function(x) stop("intentional error") ) datasets <- list(data1 = rnorm(100)) # Errors are captured, not thrown results <- datasets %>% apply_methods(methods) # Check which results are errors error_mask <- is.task_error(results$result) # [1] FALSE TRUE # Filter to successful results library(dplyr) successful <- results %>% filter(!is.task_error(result)) # Filter to failed results for debugging failed <- results %>% filter(is.task_error(result)) ``` -------------------------------- ### Filter Genes by Variance in R Source: https://context7.com/shians/cellbench/llms.txt Filters to keep the most variable genes, with variability scaled by total counts. This function is useful for identifying genes that show the most significant changes across samples, often used in differential expression analysis. ```r library(CellBench) data(sample_sce_data) # Keep 50 most variable genes high_var <- keep_high_var_genes(sample_sce_data, 50) # Use in benchmark comparing filter strategies filters <- list( high_count = function(x) keep_high_count_genes(x, 100), high_var = function(x) keep_high_var_genes(x, 100) ) datasets <- list(sce = sample_sce_data) results <- datasets %>% apply_methods(filters) ``` -------------------------------- ### Filter Genes/Cells by Count in R Source: https://context7.com/shians/cellbench/llms.txt Filters SingleCellExperiment or matrix to keep genes/cells with the highest total counts. This function is useful for reducing dimensionality and focusing on the most expressed genes or abundant cells. ```r library(CellBench) data(sample_sce_data) # Keep top 300 genes by count high_count_genes <- keep_high_count_genes(sample_sce_data, 300) # Keep top 10 cells by count high_count_cells <- keep_high_count_cells(sample_sce_data, 10) # Use in benchmark pipeline gene_filters <- fn_arg_seq(keep_high_count_genes, n = c(100, 200, 500)) datasets <- list(sce = sample_sce_data) results <- datasets %>% apply_methods(gene_filters) ``` -------------------------------- ### Remove Zero Count Genes in R Source: https://context7.com/shians/cellbench/llms.txt Removes genes (rows) with zero total counts from SingleCellExperiment objects or matrices. This function is useful for cleaning datasets before analysis, ensuring that genes with no expression are excluded. ```r library(CellBench) # Example with matrix x <- matrix(rep(0:5, times = 5), nrow = 6, ncol = 5) filtered <- filter_zero_genes(x) # Removes first row (all zeros) # Use in benchmark pipeline data(sample_sce_data) preprocess <- list( filter_zeros = filter_zero_genes, raw = identity ) datasets <- list(sce = sample_sce_data) results <- datasets %>% apply_methods(preprocess) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.