Skip to contents

Given 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, or MarchR::MarchRProject) Input to apply LSI to.

If Matrix-like, counts matrix with dimensions (features x cells).

If MarchRDataset or MarchRProject, objects with a matrix assay.

preset

(character) "archr" (default, addIterativeLSI parity) or "marchr" (unbounded pools). Sets defaults for total_features and sample_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 top num_feats features by total accessibility after removing filter_top_features of the most accessible features. Recommended for ATAC data (TileMatrix/PeakMatrix). "var" uses feature_selection_method for 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". Default 2500L.

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 are select_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_features most accessible features by feature_means before pseudobulking. Default NULL resolves from preset: Inf for "marchr" and 500000 for "archr".

pseudobulk_format

(character) Materialization used for the bounded inter-iteration pseudobulk. "iterable" (default) converts BPCells' pseudobulk_matrix() result to an IterableMatrix; "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:

  • 1 or "tf-logidf": Term frequency multiplied by log(inverse document frequency) - (Adapted from Cusanovich et al. 2018)

  • 2 or "log(tf-idf)": Log of (term frequency x inverse document frequency) - Default (Stuart et al. 2019)

  • 3 or "logtf-logidf": Log(term frequency) multiplied by log(inverse document frequency)

  • 4 or "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's clusterParams). 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's clusterParams$maxClusters. Set to NULL to disable.

depth

(numeric vector or NULL) Per-cell fragment counts used for depth-correlation filtering after transformation with log10(depth + 1). The MarchRProject method uses nFrags from fragment QC when available. If NULL, 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 to NULL to 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 of x after binarization (when binarize = TRUE), named like rownames(x). NULL computes them with a full pass over x. 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 with get_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 class c("IterativeLSI", "DimReduction") whose fitted_params include:

    • lsi_method: The method used for LSI

    • feature_selection_method: The method used for selecting features

    • cluster_method: The method used for clustering

    • feature_means: The means of the features used for tf-idf normalization

    • iterations: The number of LSI iterations ran

    • iter_info: A tibble of iteration info with rows as iterations. Columns include the following:

      • iteration: The iteration number

      • feature_names: The names of the features used for the iteration

      • feature_loadings: SVD component u with dimension (n_dimensions, n_variable_features)

      • pcs_to_keep: The PCs that were kept after filtering by correlation to sequencing depth

      • clusters: 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_selection strategy: "top" uses select_features_top (accessibility-based), "var" uses feature_selection_method

    • Perform LSI on the selected features

    • If n_iterations is 1, return the projected data from the first LSI fit

    • Else, 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_method

    • Perform 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_pre is finite, non-terminal iterations fit LSI on a subsample of that many cells (drawn per iteration) and the final iteration fits on all cells; when sample_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 the project() method with the iteration argument set to the desired iteration to get projected data. This can then be fed into uwot::umap().

  • ArchR filters out PCs with a correlation to sequencing depth greater than 0.75. corr_cutoff defaults to 0.75 in IterativeLSI().

  • MarchR excludes cells at the requested outlier_quantiles while 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 supplied depth, MarchR instead uses raw matrix column sums.

  • With first_selection = "top", both presets rank all eligible features. By default, filter_top_features = 2500L removes 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))
} # }