Run Iterative LSI on a matrix.
IterativeLSI.RdGiven a (features x cells) counts matrix, perform IterativeLSI to create cell embeddings with shape (cells, retained dimensions).
This uses the method described in ArchR (Granja et al. 2021).
The returned fitted dim_reduction component can project matrices with the same features into the fitted latent space.
Usage
# Default S3 method
IterativeLSI(
x,
preset = c("archr", "marchr"),
n_iterations = 2,
first_selection = c("top", "var"),
filter_top_features = 2500L,
feature_selection_method = select_features_variance,
total_features = NULL,
pseudobulk_format = c("iterable", "dense"),
scale_factor = 10000,
lsi_method = 2,
binarize = TRUE,
n_dimensions = 30L,
corr_cutoff = 0.75,
scale_dims = TRUE,
cluster_method = cluster_cells_graph(knn_method = knn_hnsw(k = 20L),
knn_to_graph_method = knn_to_snn_graph, cluster_graph_method =
cluster_graph_leiden(resolution = 2)),
max_clusters = 6L,
depth = NULL,
outlier_quantiles = c(0.02, 0.98),
sample_cells_pre = NULL,
sample_group = NULL,
seed = 1,
drop_zero_cells = TRUE,
feature_means = NULL,
threads = NULL,
verbose = getOption("MarchR.verbose", FALSE)
)
# S3 method for class 'IterativeLSI'
project(x, mat, iteration = x$fitted_params$iterations, threads = NULL, ...)
# S3 method for class 'MarchRProject'
IterativeLSI(
x,
assay_name = character(0),
dataset_names = character(0),
output_assay_name = "IterativeLSI",
dim_reduction_name = "IterativeLSI",
preset = c("archr", "marchr"),
n_iterations = 2,
first_selection = c("top", "var"),
filter_top_features = 2500L,
feature_selection_method = select_features_variance,
total_features = NULL,
pseudobulk_format = c("iterable", "dense"),
scale_factor = 10000,
lsi_method = 2,
binarize = TRUE,
n_dimensions = 30L,
corr_cutoff = 0.75,
scale_dims = TRUE,
cluster_method = cluster_cells_graph(knn_method = knn_hnsw(k = 20L),
knn_to_graph_method = knn_to_snn_graph, cluster_graph_method =
cluster_graph_leiden(resolution = 2)),
max_clusters = 6L,
depth = NULL,
outlier_quantiles = c(0.02, 0.98),
sample_cells_pre = NULL,
sample_group = NULL,
seed = 1,
drop_zero_cells = TRUE,
overwrite = FALSE,
threads = NULL,
verbose = getOption("MarchR.verbose", FALSE)
)Arguments
- x
(IterableMatrix;
MarchR::MarchRDataset, orMarchR::MarchRProject) Input to apply LSI to.If Matrix-like, counts matrix with dimensions
(features x cells).If
MarchRDatasetorMarchRProject, objects with a matrix assay.- preset
(character) "archr" (default,
addIterativeLSIparity) or "marchr" (unbounded pools). Sets defaults fortotal_featuresandsample_cells_pre; explicit args override. Default "archr".- n_iterations
(int) The number of LSI iterations to perform.
- first_selection
(character) Feature selection strategy for the first iteration:
"top"(default) selects the topnum_featsfeatures by total accessibility after removingfilter_top_featuresof the most accessible features. Recommended for ATAC data (TileMatrix/PeakMatrix)."var"usesfeature_selection_methodfor iteration 1 as well, which may be preferable for RNA data.- filter_top_features
(integer) The number of the most accessible features excluded before the first LSI when
first_selection = "top". Default2500L.- feature_selection_method
(function) Method to use for selecting features in iterations 2+. In iteration 1, this is only used when
first_selection = "var". Current builtin options areselect_features_variance,select_features_dispersion,select_features_mean,select_features_binned_dispersion- total_features
(numeric or NULL) Cap on the feature pool used for iterations 2+ pseudobulk re-selection. Finite values retain the
total_featuresmost accessible features byfeature_meansbefore pseudobulking. DefaultNULLresolves frompreset:Inffor"marchr"and500000for"archr".- pseudobulk_format
(character) Materialization used for the bounded inter-iteration pseudobulk.
"iterable"(default) converts BPCells'pseudobulk_matrix()result to anIterableMatrix;"dense"uses the dense result directly before normalization and variance selection. This is primarily an implementation/benchmark switch; both formats are expected to select the same features.- scale_factor
(numeric) Scaling factor to multiply matrix by during tf-idf normalization.
- lsi_method
(integer or character) TF-IDF normalization method:
1or"tf-logidf": Term frequency multiplied by log(inverse document frequency) - (Adapted from Cusanovich et al. 2018)2or"log(tf-idf)": Log of (term frequency x inverse document frequency) - Default (Stuart et al. 2019)3or"logtf-logidf": Log(term frequency) multiplied by log(inverse document frequency)4or"logtf-idf": Log(term frequency) multiplied by inverse document frequency
- binarize
(logical) If
TRUE(the default), binarize the input accessibility matrix before running each LSI iteration.- n_dimensions
(integer) Number of SVD dimensions to compute per iteration. Default 30.
- corr_cutoff
(numeric) Numeric filter for the correlation of a PC to the sequencing depth. If the PC has a correlation that is greater or equal to the corr_cutoff, it will be excluded from the final PCA matrix.
- scale_dims
(logical) Whether to apply row-wise z-score scaling to the LSI embedding. When
TRUE(default, matching ArchR), each cell's coordinates are z-scored across dimensions so no single PC dominates distance-based operations. Applied both during intermediate clustering (affecting feature selection) and to the final stored embeddings.- cluster_method
(function) Method to use for clustering the post-SVD matrix. Default uses
cluster_cells_graph(knn_method = knn_hnsw(k = 20L), knn_to_graph_method = knn_to_snn_graph, cluster_graph_method = cluster_graph_leiden(resolution = 2)), matching ArchR's internal clustering (SNN graph, k=20 from Seurat's FindNeighbors default, resolution=2 from ArchR'sclusterParams). Users can override with partial application, e.g.cluster_cells_graph(cluster_graph_method = cluster_graph_louvain(resolution = 0.5)).- max_clusters
(integer) Maximum clusters per iteration. If exceeded, clusters are merged via hierarchical clustering on centroids. Default is
6L, matching ArchR'sclusterParams$maxClusters. Set toNULLto disable.- depth
(numeric vector or NULL) Per-cell fragment counts used for depth-correlation filtering after transformation with
log10(depth + 1). The MarchRProject method usesnFragsfrom fragment QC when available. IfNULL, matrix column sums are used.- outlier_quantiles
(numeric vector or NULL) Lower and upper column-sum quantiles used to exclude extreme cells while fitting each SVD. Excluded cells are projected back into the fitted space. Default
c(0.02, 0.98); set toNULLto disable.- sample_cells_pre
(numeric) Pre-iteration subsample size; Inf disables (full cells). NULL resolves from the preset ("archr" is 10000, "marchr" is Inf). Default NULL.
- sample_group
(vector or NULL) Optional per-cell grouping for subsampling, in matrix-column order; the project method fills it from per-cell dataset membership. NULL uses uniform sampling. Default NULL.
- seed
(numeric) Seed for the subsample draw (only for this subsample). Default 1.
- drop_zero_cells
(logical) Passed to
LSI(); drop 0-count cells before LSI. Default TRUE.- feature_means
(numeric or NULL) For
IterativeLSI.default(): per-feature means ofxafter binarization (whenbinarize = TRUE), named likerownames(x). NULL computes them with a full pass overx. the MarchRProject method supplies them from stored per-feature totals. Default NULL.- threads
(integer) Per-call override of
set_threads(). Default NULL threads each SVD withget_threads()and clusters single-threaded. Note that an explicit value also threads the clustering KNN, which makes results non-deterministic.- verbose
(logical) Print progress messages. Default
getOption("MarchR.verbose", FALSE).- mat
(IterableMatrix) Counts matrix of shape
(features x cells).- iteration
(integer) Which iteration of
IterativeLSI's features and loadings to use for projection.- ...
Additional arguments passed to methods.
- assay_name
(character) Name of the assay to apply the function to. If not provided, defaults to the first assay in the dataset.
- dataset_names
(character) Names of the datasets to apply the function to. If not provided, defaults to all datasets in the project.
- output_assay_name
(character) Name to store the embeddings as a new assay. Defaults to "IterativeLSI".
- dim_reduction_name
(character) Name to store the DimReduction result. Defaults to "IterativeLSI".
- overwrite
(logical) If
TRUE, overwrites existing DimReduction with the same name.
Value
For a matrix input, IterativeLSI() returns a named list with two elements:
cell_embeddings: Matrix(cells, retained dimensions)containing the final iteration embeddings.dim_reduction: DimReduction object of classc("IterativeLSI", "DimReduction")whosefitted_paramsinclude:lsi_method: The method used for LSIfeature_selection_method: The method used for selecting featurescluster_method: The method used for clusteringfeature_means: The means of the features used for tf-idf normalizationiterations: The number of LSI iterations raniter_info: A tibble of iteration info with rows as iterations. Columns include the following:iteration: The iteration numberfeature_names: The names of the features used for the iterationfeature_loadings: SVD componentuwith dimension(n_dimensions, n_variable_features)pcs_to_keep: The PCs that were kept after filtering by correlation to sequencing depthclusters: The clusters for the iteration. This is blank for the first iteration
For a MarchRProject input, the modified project is returned with the fitted
reduction in dim_reductions and cell embeddings stored as assays.
project() Matrix of the projected data of shape (cells, n_dimensions).
Details
The Iterative LSI method is as follows:
First iteration:
Select features using
first_selectionstrategy:"top"usesselect_features_top(accessibility-based),"var"usesfeature_selection_methodPerform LSI on the selected features
If
n_iterationsis 1, return the projected data from the first LSI fitElse, cluster the LSI results using
cluster_method
For each subsequent iteration:
Pseudobulk the clusters from the previous iteration, log-normalize the pseudo-bulk matrix, then select features using
feature_selection_methodPerform LSI on the selected features
If this is the final iteration, return the projected data from this LSI fit
Else, cluster the LSI results using
cluster_method
Remaining differences compared to the ArchR implementation:
ArchR calculates LSI during non-terminal iterations using a default subset of 10000 cells to prevent a memory bottleneck, which BPCells does not encounter even with a non-subsetted matrix. When
sample_cells_preis finite, non-terminal iterations fit LSI on a subsample of that many cells (drawn per iteration) and the final iteration fits on all cells; whensample_cells_pre = Inf(the MarchR default) every iteration uses all cells.ArchR defaults to using Seurat clustering, which utilizes the Louvain algorithm (See
Seurat::FindClusters()). In contrast,IterativeLSI()utilizes Leiden, which should provide similar clustering results while being faster.ArchR also plots and calculates a UMAP of every iteration's dimensionality reduction. While this is not implemented in
IterativeLSI(), one can use theproject()method with theiterationargument set to the desired iteration to get projected data. This can then be fed intouwot::umap().ArchR filters out PCs with a correlation to sequencing depth greater than 0.75.
corr_cutoffdefaults to 0.75 inIterativeLSI().MarchR excludes cells at the requested
outlier_quantileswhile fitting each SVD, then projects those cells back into the fitted latent space.For MarchRProject inputs with fragment QC, depth correlation uses
log10(nFrags + 1), matching ArchR. For direct matrix inputs without a supplieddepth, MarchR instead uses raw matrix column sums.With
first_selection = "top", both presets rank all eligible features. By default,filter_top_features = 2500Lremoves the 2,500 most accessible and selects the next 25,000, independently of the inter-iteration pseudobulk pool.preset = "archr"(the default) caps the inter-iteration pseudobulk pool at 500,000 features. On a genome-wide 500bp tile matrix that cap corresponds to roughly "open in at least 10 cells", which keeps the inter-iteration variance statistic – estimated from one value per cluster – away from counts too low to rank reliably.preset = "marchr"retains an unbounded inter-iteration pseudobulk pool (total_features = Inf) and full-cell LSI fits.
Examples
if (FALSE) { # \dontrun{
## Prep data
nrows <- 500
ncols <- 10000
mat <- matrix(1:(nrows*ncols), nrow = nrows) %>% as("IterableMatrix")
rownames(mat) <- paste0("feat", seq(nrows))
colnames(mat) <- paste0("cell", seq(ncols))
########################################################################
## IterativeLSI() example
########################################################################
lsi_result <- IterativeLSI(mat, n_dimensions = 5)
lsi_result$cell_embeddings
lsi_result$dim_reduction
## Can customize parameters using partialization
lsi_result <- IterativeLSI(
mat,
n_dimensions = 10,
feature_selection_method = select_features_variance(
num_feats = 0.5,
normalize_method = normalize_tfidf(scale_factor = 5000)
),
cluster_method = cluster_cells_graph(
cluster_graph_method = cluster_graph_louvain(resolution = 0.5),
knn_to_graph_method = knn_to_snn_graph
)
)
} # }
if (FALSE) { # \dontrun{
#######################################################################
## project(<IterativeLSI>) example
#######################################################################
dim(project(dim_reduction, mat))
} # }