| Title: | Streamlined scRNA-Seq Analysis Pipeline |
|---|---|
| Description: | Streamlined scRNA-Seq analysis pipeline. |
| Authors: | Igor Dolgalev [cre, aut], Anna Yeaton [aut] |
| Maintainer: | Igor Dolgalev <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.0.9005 |
| Built: | 2026-10-23 13:48:35 UTC |
| Source: | https://github.com/igordot/scooter |
Detected by gene symbol prefix, case-insensitively so the same patterns
match both human (MT-, RPS/RPL, HBA/HBB) and mouse (mt-,
Rps/Rpl, Hba-a1/Hbb-bs) naming. RPS6K* (ribosomal protein S6
kinase) is excluded from pct_ribo - it matches the RPS prefix but is a
signaling kinase, not a ribosomal protein.
add_gene_class_percent(x)add_gene_class_percent(x)
x |
A Seurat object. |
High expression levels of mitochondrial genes could be an indicator of poor sample quality, leading to a high fraction of apoptotic or lysing cells (see reference below).
pct_ribo is normally 15-45%; the exact fraction varies by cell type and
overall cell health. "Although both ribosomal proteins and ribosomal RNA
(rRNA) make up the ribosome complex, ribosomal protein transcripts are not
equivalent to ribosomal RNA (rRNA). Ribosomal protein transcript detection
will not necessarily correlate with either rRNA or mitochondrial
transcripts." (see reference below)
High pct_hb is a contamination signal in PBMC and most solid tissue:
per-sample pct_hb flags incomplete red blood cell lysis in PBMC preps, or
inadequate perfusion in solid tissue.
Seurat object with pct_mito, pct_ribo, and pct_hb metadata
columns added.
pct_ribo:
https://kb.10xgenomics.com/s/article/218169723-What-fraction-of-reads-map-to-ribosomal-proteins
Add assay to Seurat object.
add_seurat_assay(x, assay, counts_matrix, log_file = NULL)add_seurat_assay(x, assay, counts_matrix, log_file = NULL)
x |
Seurat object. |
assay |
Seurat assay to add the matrix to. |
counts_matrix |
Raw counts matrix. |
log_file |
Filename for the log file. |
Seurat object of cells found in both the existing object and new data.
Annotates query with Pan-human Azimuth, a neural network trained on
23 human tissues. Install the AzimuthAPI package from GitHub
(satijalab/AzimuthAPI).
annotate_pan_human_azimuth(query, query_assay = "RNA", verbose = TRUE)annotate_pan_human_azimuth(query, query_assay = "RNA", verbose = TRUE)
query |
Query Seurat object. |
query_assay |
Assay in |
verbose |
Print progress messages. |
Unlike transfer_labels(), the function needs no reference object.
query with these columns added to its metadata:
pan_human_azimuth_label (the most specific label),
pan_human_azimuth_final_level_confidence (its confidence),
pan_human_azimuth_broad, pan_human_azimuth_medium,
pan_human_azimuth_fine, pan_human_azimuth_final_level_labels,
pan_human_azimuth_full_consistent_hierarchy and
pan_human_azimuth_full_hierarchical_labels. The function writes the
columns of AzimuthAPI, under their own names and after a cell column,
to annotation/annotation-pan-human-azimuth.csv.gz. It also writes
dr-umap-<column>.png for each metadata column, except those with too
many groups to color.
Pan-human Azimuth website: https://satijalab.org/pan_human_azimuth
Sarkar S, Li Z, Molla G, Shenoy A, Zhang B, Collins D, et al. Organism-scale annotation with Pan-human Azimuth. bioRxiv. 2026 Jul 21. doi:10.64898/2026.07.16.738997
Function to extract data from Seurat object.
as_data_frame_seurat( x, assay = NULL, slot = NULL, features = NULL, reduction = NULL, metadata = TRUE )as_data_frame_seurat( x, assay = NULL, slot = NULL, features = NULL, reduction = NULL, metadata = TRUE )
x |
A Seurat object. |
assay |
Assay such as RNA. |
slot |
Slot such as counts. Default is scale.data. |
features |
Features from assay. |
reduction |
Character vector of reduction types. |
metadata |
Boolean. To grab metadata or not |
A metadata file merged on cell identifiers.
Writes expression-mean-<label>.csv, and additionally
expression-mean-<label>-per-sample.csv when x has more than one sample.
calculate_cluster_expression(x, label)calculate_cluster_expression(x, label)
x |
Seurat object with an identity set, such as via |
label |
Suffix for the output filenames. |
x, invisibly. Called for its file output.
test, forwarded to Seurat::FindAllMarkers()/Seurat::FindMarkers():
"wilcox" (Wilcoxon rank sum, the default), "roc" (classification power
from 0 = random to 1 = perfect), "bimod" (McDavid et al. 2013), "tobit"
(Trapnell et al. 2014), or "MAST" (Finak et al. 2015).
calculate_cluster_markers(x, label, test, pairwise = FALSE)calculate_cluster_markers(x, label, test, pairwise = FALSE)
x |
Seurat object with an identity set. |
label |
Suffix for the output filenames. |
test |
Statistical test - see above. |
pairwise |
Compare clusters pairwise instead of each cluster against all others - see above. |
pairwise = TRUE compares each cluster against each other cluster
individually (rather than each cluster against all others combined), keeping
only genes significant in every comparison - local and global markers both,
at the cost of being much slower for many clusters.
x, invisibly. Called for its file and plot output.
Writes metadata-<label>.csv.gz (cell metadata joined with the tSNE/UMAP
embeddings, skipped if neither reduction is present) and
summary-<label>.csv (cell counts and percentages per cluster, split
further by sample into summary-<label>-per-sample.csv when that differs).
calculate_cluster_stats(x, label)calculate_cluster_stats(x, label)
x |
Seurat object with an identity set, such as via |
label |
Suffix for the output filenames. |
x, invisibly. Called for its file output.
Builds a shared nearest neighbor (SNN) graph from reduced dimensions and identifies clusters over a range of resolutions.
calculate_clusters(x, ...) ## S3 method for class 'Seurat' calculate_clusters( x, assay, reduction, num_dim, num_neighbors = 20, res = NULL, algorithm = 4, log_file = NULL, max_clusters = length(get_color_scheme("clusters")), ... )calculate_clusters(x, ...) ## S3 method for class 'Seurat' calculate_clusters( x, assay, reduction, num_dim, num_neighbors = 20, res = NULL, algorithm = 4, log_file = NULL, max_clusters = length(get_color_scheme("clusters")), ... )
x |
A matrix of cell embeddings (cells as rows) or a Seurat object. |
... |
Arguments passed to the individual methods. |
assay |
Assay logged as the one this clustering run is over (Seurat
method). Purely for the log message - clustering itself runs on
|
reduction |
Reduction to take the cell embeddings from (Seurat method). No default - always state it explicitly. |
num_dim |
Number of dimensions to use. |
num_neighbors |
Number of neighbors ( |
res |
Clustering resolution(s). If |
algorithm |
Clustering algorithm: 1 = Louvain, 2 = Louvain with
multilevel refinement, 3 = SLM, 4 = Leiden (the default). See
|
log_file |
Filename for the log file. |
max_clusters |
Drop resolutions yielding this many clusters or more. Defaults to the length of the cluster color scheme, since resolutions that exceed it cannot be plotted (Seurat method). |
For a Seurat object, the cluster assignments are added to the object
metadata as res.<resolution> columns, the labels are converted to the
C01, C02, ... convention (1-based, zero-padded, and C-prefixed to
block downstream numeric coercion), and resolutions that do not yield any
new clusters are dropped.
Cluster assignments as a data frame (default method) or the Seurat object with the cluster assignments added to its metadata (Seurat method).
Check identity of the Seurat object.
check_identity_column(x, identity_column)check_identity_column(x, identity_column)
x |
A Seurat object. |
identity_column |
The name of the identity column to pull from object metadata. |
The name of the identity column, potentially corrected if resolution.
The clustering step of the pipeline in one call: run tSNE and UMAP on an
existing "pca" reduction (run_tsne(), run_umap()), build the SNN graph
and cluster over a range of resolutions (calculate_clusters()), and plot
each reduction by cluster.
cluster_seurat_object( x, assay = "RNA", reduction, num_dim, num_neighbors = 30, metadata_file = NULL, log_file = NULL )cluster_seurat_object( x, assay = "RNA", reduction, num_dim, num_neighbors = 30, metadata_file = NULL, log_file = NULL )
x |
Seurat object with |
assay |
Assay to attribute the tSNE/UMAP reductions to.
|
reduction |
Reduction to compute tSNE/UMAP from and to cluster on -
"pca" after |
num_dim |
Principal components to use, bounded to 5-50. |
num_neighbors |
Neighbors for UMAP and for the SNN graph. |
metadata_file |
Path to write the cell metadata and embeddings to, via
|
log_file |
Filename for the log file. |
This function computes both reductions before clustering, since the
cluster plots draw on them. run_tsne() and run_umap() already write
their own sample-colored scatter to the working directory, so this
function skips plotting "by sample" again.
The per-resolution cluster plots also write unconditionally, into a
clusters-resolutions/ subdirectory. This matches every other verb's
standard-output convention.
A Seurat object with "tsne" and "umap" reductions and one res.<x>
column per retained clustering resolution.
Function to create a color vector.
create_color_vect(seurat_obj, group = "orig.ident")create_color_vect(seurat_obj, group = "orig.ident")
seurat_obj |
A Seurat object. |
group |
Assay such as RNA. |
A vector of colors.
Everything needed to take a sample from a counts file to an object ready for clustering, in one call.
create_seurat_object( path, sample_name, num_mads = 3, min_genes = 500, max_genes = NULL, min_counts = NULL, max_counts = NULL, max_mt = 10, min_cells = 100, normalization_method = "log", num_variable_genes = 3000, num_pcs = 50, num_dim = 30, log_file = NULL )create_seurat_object( path, sample_name, num_mads = 3, min_genes = 500, max_genes = NULL, min_counts = NULL, max_counts = NULL, max_mt = 10, min_cells = 100, normalization_method = "log", num_variable_genes = 3000, num_pcs = 50, num_dim = 30, log_file = NULL )
path |
Path to a 10x directory or a flat counts file. |
sample_name |
Sample/library name, used as the cell ID prefix. |
num_mads, min_genes, max_genes, min_counts, max_counts, max_mt
|
Quality
cutoffs, passed to |
min_cells |
Minimum number of cells that must survive filtering. |
normalization_method |
Normalization method, passed to
|
num_variable_genes |
Number of variable features. |
num_pcs |
Principal components to compute. Reduced automatically when the object is too small to support that many. |
num_dim |
Number of dimensions for the first-pass tSNE/UMAP, capped at
|
log_file |
Filename for the log file. |
The function runs these steps:
Read the counts (read_counts_file()).
Build the object (initialize_seurat_object()).
Attach any antibody capture data as an "ADT" assay
(add_seurat_assay()).
Apply the quality cutoffs (filter_cells()).
Normalize, select variable features, and scale
(normalize_counts(), which does all three for either method).
Run PCA (run_pca()).
Compute a first-pass tSNE/UMAP (run_tsne(), run_umap()).
This function attaches the ADT assay before filtering, on purpose.
add_seurat_assay() restricts the object to the barcodes both matrices
share. Attaching ADT after filtering would apply the cutoffs to a
different set of cells.
PCA, and the tSNE/UMAP computed from it, runs on whichever assay
normalization left active. SCTransform() creates and activates "SCT".
The log path leaves "RNA" active. So dr_assay is decided directly from
normalization_method, not read back off the object. Reading it back off
DefaultAssay() would reintroduce the implicit dependency an explicit
assay argument exists to avoid.
The tSNE/UMAP computed here are a first-pass look, capped at num_dim
dimensions. cluster_seurat_object() recomputes both once a clustering
resolution's own num_dim is chosen. So this pair is not the final one
used for the actual clustering plots.
A Seurat object with normalized data, variable features, scaled
data, and "pca", "tsne", and "umap" reductions — ready for
cluster_seurat_object(). Also writes the variable-feature, PCA, tSNE,
and UMAP diagnostic plots (via normalize_counts(), run_pca(),
run_tsne(), and run_umap()) and the metadata+embeddings table (via
save_metadata(), as metadata.csv.gz) to the working directory.
Calculate differentially expressed genes within each subpopulation/cluster
differential_expression_per_cluster( x, cluster_column, group_column, test = "wilcox", out_path = ".", write = TRUE, log_file = NULL )differential_expression_per_cluster( x, cluster_column, group_column, test = "wilcox", out_path = ".", write = TRUE, log_file = NULL )
x |
A Seurat object. |
cluster_column |
Metadata column specifying the groups to split by. |
group_column |
Metadata column specifying the groups for differential expressin within each split. |
test |
Statistical method to use. |
out_path |
Output path. |
write |
Boolean to save results to disk. |
log_file |
log file. |
.
A label-count estimate made without building the plot. plot_dr_group()
now sizes itself from the actual rendered legend instead (see
save_dr_plot()), so this has no callers left in the package - kept as a
cheap standalone estimate for callers that don't have a plot object yet.
dr_plot_width(x, group_by = "orig.ident")dr_plot_width(x, group_by = "orig.ident")
x |
Seurat object, or the number of legend labels. |
group_by |
Metadata column whose distinct values become the plot's
legend. Ignored if |
Numeric width in inches.
Filtering runs in two stages, and the log records how many cells each one removed.
filter_cells( x, num_mads = 3, min_genes = 500, max_genes = NULL, min_counts = NULL, max_counts = NULL, max_mt = 10, min_cells = 50, log_file = NULL )filter_cells( x, num_mads = 3, min_genes = 500, max_genes = NULL, min_counts = NULL, max_counts = NULL, max_mt = 10, min_cells = 50, log_file = NULL )
x |
A tibble with metadata (default method) or a Seurat object (Seurat
method). Must have |
num_mads |
Median absolute deviations for the outlier stage. |
min_genes |
Minimum number of genes per cell. |
max_genes |
Maximum number of genes per cell. |
min_counts |
Minimum number of counts per cell. |
max_counts |
Maximum number of counts per cell. |
max_mt |
Maximum percentage of mitochondrial reads per cell. |
min_cells |
Minimum number of cells that must survive filtering. Below
this, filtering |
log_file |
Log file. |
Outlier removal. Cells further than num_mads median absolute
deviations from the median number of genes or counts are dropped. The
median and MAD are computed on the log scale and the bounds
back-transformed, which suits these right-skewed counts. num_mads = NULL skips it.
Fixed cutoffs. min_genes / max_genes / min_counts /
max_counts are applied to whatever survived stage 1, then max_mt.
Each is skipped when NULL, so out of the box only min_genes (500) and
max_mt (10) do anything.
Applying the fixed cutoffs second makes them a quality floor the data-driven bounds cannot undercut: a wide or contaminated distribution can put the MAD bound below 500 genes, and those cells are still removed. All cutoffs are inclusive.
Genes that are no longer detected in any of the retained cells are dropped, since filtering cells leaves them as all-zero rows.
Filtered data. The Seurat method also writes a pre-filtering QC
violin plot (via plot_metrics_distribution()) and the unfiltered
metadata (via save_metadata(), as metadata-unfiltered.csv.gz), plus
the post-filtering QC plots (via plot_metrics_distribution() and
plot_metrics_correlations()) to the working directory.
Get geneset scores.
geneset_score(module_tbl, counts_raw, min_cpm = 0, limit_pct = 1)geneset_score(module_tbl, counts_raw, min_cpm = 0, limit_pct = 1)
module_tbl |
geneset table. |
counts_raw |
Raw counts |
min_cpm |
. |
limit_pct |
. |
.
Determine the color scheme. Can be specified for samples or clusters to avoid confusion.
get_color_scheme(type = "clusters")get_color_scheme(type = "clusters")
type |
Type of scheme ("samples" or "clusters"). |
A vector of colors.
Determine the point size for reduced dimensions scatter plots (smaller for larger datasets).
get_dr_point_size(x)get_dr_point_size(x)
x |
Number of cells (points on the plot), a Seurat object, or a data frame with one row per cell. |
Numeric point size.
Get a small matrix of raw counts from the PBMC dataset.
get_test_counts_matrix()get_test_counts_matrix()
A matrix of raw counts.
pbmc_mat <- get_test_counts_matrix()pbmc_mat <- get_test_counts_matrix()
Read in 10x Genomics Cell Ranger Matrix Market format data.
import_mtx(data_path, gene_column = 2, prefix = "", log_file = NULL)import_mtx(data_path, gene_column = 2, prefix = "", log_file = NULL)
data_path |
Path to directory that holds the files output from 10x. |
gene_column |
The column with the gene names. |
prefix |
File name prefix of the matrix, features, and barcodes files. |
log_file |
Filename for the log file. |
Named list of matrices. One matrix for each data type as specified
in the third column of the features.tsv file. As of Oct 3rd 2019, the two
options are Gene Expression and Antibody Capture
For an RNA assay the per-cell QC metrics are added at the same time:
pct_mito/pct_ribo/ pct_hb (via add_gene_class_percent()), plus
detected_genes and total_counts as clearer aliases of
nFeature_RNA/nCount_RNA, and sample_name as a clearer alias of
orig.ident. All six are metadata columns as soon as the object exists,
so plot_metrics_distribution() (which takes its metrics explicitly, no
default) and plot_metrics_correlations() can use any of them without
further preparation.
initialize_seurat_object( counts_matrix, assay = "RNA", min_cells = 1, min_genes = 1, project = "proj", log_file = NULL )initialize_seurat_object( counts_matrix, assay = "RNA", min_cells = 1, min_genes = 1, project = "proj", log_file = NULL )
counts_matrix |
A matrix of raw counts. |
assay |
Seurat assay to add the data to. |
min_cells |
Include genes/features detected in at least this many cells. |
min_genes |
Include cells where at least this many genes/features are detected. |
project |
Project name for Seurat object. |
log_file |
Filename for the logfile. |
Seurat object.
Runs the Seurat 5 IntegrateLayers() workflow. It adds what calling
IntegrateLayers() directly leaves for the caller to handle:
integrate_layers( x, assay = "RNA", int_reduction = "cca", num_dim, k_anchor = 10, k_weight = 100, log_file = NULL, ... )integrate_layers( x, assay = "RNA", int_reduction = "cca", num_dim, k_anchor = 10, k_weight = 100, log_file = NULL, ... )
x |
Seurat object with split layers and a "pca" reduction. |
assay |
Assay to integrate. |
int_reduction |
Integration method: "cca", "rpca", or "harmony". |
num_dim |
Number of dimensions to use (5-50). For "cca"/"rpca", this
value is passed as |
k_anchor |
Neighbors to use when picking anchors. Ignored by "harmony". A value larger than Seurat's default of 5 strengthens the alignment. |
k_weight |
Neighbors to use when weighting the corrections. Must be smaller than the number of cells in the smallest batch. Reduced to 25 when the smallest batch has fewer than 100 cells. Batches smaller than 25 cells are an error. |
log_file |
Filename for the log file. |
... |
Extra arguments for whichever method |
Clamps k_weight to fit the smallest batch. Seurat's own default of 100
errors outright below that size. See k_weight below.
Excludes dims/k.anchor for "harmony". HarmonyIntegration()
silently ignores both instead of erroring, so passing them would rely
on that silent drop. See num_dim/k_anchor below.
Forces future::plan(future::sequential). Benchmarks show multisession
gives no gain here, and is a documented liability at this scale
elsewhere in this package.
Rejoins the split layers with JoinLayers() afterward.
IntegrateLayers() itself leaves this undone.
Unlike the older anchor workflow, this function creates no "integrated"
assay. Clustering and visualization use the corrected embedding directly,
instead of re-running PCA. This function expects
split_layers_by_batch() to have run first. It is the one step of
integrate_seurat_object() that calls IntegrateLayers() directly.
A Seurat object with rejoined layers and an int_reduction-named
reduction ("cca", "rpca", or "harmony").
The integrate step of the pipeline in one call. It plays the same role for
a merged object that create_seurat_object() plays for a single sample.
integrate_seurat_object( x, assay = "RNA", int_reduction = "cca", num_dim, batch_var = "orig.ident", num_variable_genes = 3000, num_neighbors = 30, k_anchor = 10, k_weight = 100, log_file = NULL, ... )integrate_seurat_object( x, assay = "RNA", int_reduction = "cca", num_dim, batch_var = "orig.ident", num_variable_genes = 3000, num_neighbors = 30, k_anchor = 10, k_weight = 100, log_file = NULL, ... )
x |
Merged Seurat object, such as the output of
|
assay |
Assay to integrate. Passed straight through to
|
int_reduction |
Integration method: "cca", "rpca", or "harmony". |
num_dim |
Number of dimensions to use (5-50). |
batch_var |
Metadata column identifying the batch. |
num_variable_genes |
Number of variable features per batch. |
num_neighbors |
Neighbors for UMAP. |
k_anchor |
Neighbors to use when picking anchors. Passed straight
through to |
k_weight |
Neighbors to use when weighting the corrections. Passed
straight through to |
log_file |
Filename for the log file. |
... |
Passed straight through to |
The function runs these steps:
Split the assay layers by batch and prepare them
(split_layers_by_batch()).
Report how much the per-batch variable genes overlap
(plot_var_genes_euler(), plot_var_genes_upset()).
Correct the batch effect (integrate_layers()).
Compute a first-pass tSNE/UMAP on the corrected embedding.
The tSNE/UMAP from step 4 is a preview, capped at num_dim. It differs
from the real one cluster_seurat_object() computes later over its own
num_dim. cluster_seurat_object() has no default reduction. Pass it
this function's int_reduction name explicitly. Otherwise it may use the
uncorrected "pca" reduction that split_layers_by_batch() also leaves on
the object.
A Seurat object with rejoined layers, an int_reduction-named
reduction ("cca", "rpca", or "harmony"), and "tsne"/"umap"
reductions computed from it. Also writes the variable-gene overlap, QC
distribution, integrated-embedding, and tSNE/UMAP plots to the working
directory.
x and y must not share column names other than cell - stop()s if
they do, rather than letting left_join() silently rename the collision to
<col>.x/<col>.y.
merge_metadata(x, y, log_file = NULL)merge_metadata(x, y, log_file = NULL)
x |
A Seurat object or tibble with cell IDs (a |
y |
A tibble with cell IDs (a |
log_file |
A log filename. |
A metadata file merged on cell identifiers.
Merges a list of Seurat objects, rejoins the split layers that Seurat 5 leaves behind, and removes genes that are detected in too few cells. Features of the non-RNA assays (such as ADT and HTO) are always kept.
merge_seurat_objects(seurat_object_list, min_cells = NULL, log_file = NULL)merge_seurat_objects(seurat_object_list, min_cells = NULL, log_file = NULL)
seurat_object_list |
List of Seurat objects and/or analysis directory paths (mixing both is fine). |
min_cells |
Keep genes detected in at least this many cells. If |
log_file |
Filename for the log file. |
Elements of seurat_object_list may be Seurat objects, or paths to an
analysis directory containing a seurat_obj.qs2 (as written by the
CLI). Which one it is does not matter to the caller: this function
resolves each element to an object first.
Once every input is an object, this function strips each one's own
reductions, scaled data, and clustering columns before merging. A
per-sample PCA, tSNE/UMAP, or clustering — written by
create_seurat_object()/cluster_seurat_object() — is meaningless once
merged. normalize_counts()/run_pca() recompute all of it downstream
anyway.
Writes metrics-distribution.png, a per-sample QC violin plot, to the
working directory.
A merged Seurat object.
A thin wrapper that picks the right Seurat function for method and fixes
the parameters this pipeline uses, so either path hands back a fully
processed object — no separate variance step needed. method = "sct"
already worked this way natively: SCTransform() produces the counts,
variable features and scaled data in one pass. method = "log" now mirrors
that explicitly: NormalizeData() followed by FindVariableFeatures() and
ScaleData().
normalize_counts( x, method = "log", num_variable_genes = 3000, assay = "RNA", log_file = NULL )normalize_counts( x, method = "log", num_variable_genes = 3000, assay = "RNA", log_file = NULL )
x |
A Seurat object. |
method |
"log" for |
num_variable_genes |
Number of variable features. |
assay |
Assay to normalize. |
log_file |
Log file. |
No covariates are regressed out (vars.to.regress = NULL) for either path.
Germain et al. (2020) found that the "common practice of regressing out cell
covariates, such as the detection rate or proportion of mitochondrial
reads[,] nearly always had a negative impact."
On the log path, this function drops any vf_* columns already on
assay's feature meta data before recomputing them. An earlier call can
leave these columns behind: each sample's own pre-merge run, or a merge
step's preview run. Left alone, they would just accumulate call after
call. See variable_features_by_batch() for what reading an accumulated
column list, instead of a current one, leads to.
SCTransform() never writes this kind of per-gene bookkeeping column. So
the sct path has nothing to clean up. The check runs the same way for
both paths; it is a no-op for sct, not something conditioned on method.
The processed Seurat object. Also writes the variable-feature plot
(variance-features.png) to the working directory.
Heatmap of the top cluster markers, at several top-N cutoffs.
plot_cluster_markers_heatmap(x, markers_tbl, num_genes, filename_base)plot_cluster_markers_heatmap(x, markers_tbl, num_genes, filename_base)
x |
Seurat object with an identity set. |
markers_tbl |
Marker table, such as from |
num_genes |
Top-N genes per cluster to include, one heatmap per value. |
filename_base |
Path prefix for the output files. |
Nothing; called for its file output.
Plot a gene list in multiple ways: UMAP, dot plot, violin, and per-cluster bar plot.
plot_cluster_markers_top( x, genes, filename_base, color_scheme = get_color_scheme("clusters") )plot_cluster_markers_top( x, genes, filename_base, color_scheme = get_color_scheme("clusters") )
x |
Seurat object with an identity set. |
genes |
Genes to plot. |
filename_base |
Path prefix for the output files. |
color_scheme |
(optional) Named vector of cluster colors, used by the
violin and bar plots. Defaults to |
Nothing; called for its file output.
A single cluster says nothing, and past the color scheme's length the colors
start repeating, so nothing is plotted outside 2:length(color_scheme)
clusters.
plot_clusters( x, resolution, filename_base, color_scheme = get_color_scheme("clusters") )plot_clusters( x, resolution, filename_base, color_scheme = get_color_scheme("clusters") )
x |
Seurat object. |
resolution |
Metadata column (or bare resolution value, resolved via
|
filename_base |
Path prefix for the two plots ( |
color_scheme |
(optional) Named vector of cluster colors. Defaults to
|
x with resolution set as its identity.
Plot the distribution of specified features/variables.
plot_distribution(x, features, grouping, color_scheme = NULL)plot_distribution(x, features, grouping, color_scheme = NULL)
x |
Seurat object or metadata. |
features |
Vector of features to plot (such as "nGene", "nUMI", "percent.mito"). |
grouping |
X. |
color_scheme |
(optional) Vector of colors. |
A vector of colors.
One point per cell, colored by expression/abundance of feature (a gene,
antibody, or any other value FeaturePlot() can fetch). Unlike passing a
multi-color ramp straight to FeaturePlot(cols = ), the ramp is applied
afterward with scale_color_gradientn() so the color scale stays
continuous - see the "cols" note below.
plot_dr_feature( x, feature, assay = NULL, reduction = "umap", cells = NULL, color_scheme = NULL, pt_size = NULL, file_prefix = NULL, file_format = c("png", "pdf") )plot_dr_feature( x, feature, assay = NULL, reduction = "umap", cells = NULL, color_scheme = NULL, pt_size = NULL, file_prefix = NULL, file_format = c("png", "pdf") )
x |
Seurat object. |
feature |
Feature name (gene, antibody, or metadata column) to plot. |
assay |
(optional) Assay to fetch |
reduction |
Dimensionality reduction to plot on (e.g. "umap", "tsne", "pca"). |
cells |
(optional) Cells to plot, in the given order (controls z-order of overlapping points). Defaults to a random shuffle of all cells so no single cell/group dominates due to plot order. |
color_scheme |
(optional) Vector of colors for the low-to-high expression gradient. |
pt_size |
(optional) Point size. Defaults to |
file_prefix |
(optional) Path to save to. |
file_format |
File formats to write when |
A ggplot object.
FeaturePlot(cols = ) quirkAs of Seurat 5, passing a cols vector of anything other than exactly 2
colors makes FeaturePlot() bin the continuous values into 2 groups before
coloring (cut(x, breaks = 2)), which turns a smooth expression gradient
into a flat low/high split. Seurat 4 only did this when cols had exactly 2
colors, so a long custom ramp used to pass through untouched. This function
sidesteps the quirk (and the version difference) entirely by never passing a
multi-color cols to FeaturePlot() - the ramp is layered on afterward
instead.
The categorical counterpart of plot_dr_feature(): cells are colored by a
metadata column (or by the current identities) rather than by a continuous
feature. Cells are shuffled so no one group is drawn on top of the others.
plot_dr_group( x, reduction = "umap", group_by = NULL, color_scheme = NULL, pt_size = NULL, na_value = "grey50", file_prefix = NULL, file_format = c("png", "pdf"), width = NULL, height = 6 )plot_dr_group( x, reduction = "umap", group_by = NULL, color_scheme = NULL, pt_size = NULL, na_value = "grey50", file_prefix = NULL, file_format = c("png", "pdf"), width = NULL, height = 6 )
x |
Seurat object. |
reduction |
Dimensionality reduction to plot on (e.g. "umap", "tsne", "pca"). |
group_by |
(optional) Metadata column to color by. |
color_scheme |
(optional) Vector of colors. Defaults to the "clusters" scheme. |
pt_size |
(optional) Point size. Defaults to |
na_value |
Color for cells with no value in |
file_prefix |
(optional) Path to save to. |
file_format |
File formats to write when |
width |
(optional) Saved width in inches. |
height |
Saved height in inches. |
A ggplot object.
Plot a UMAP colored by one or more cluster/grouping variables.
plot_dr_umap_clusters( x, cluster_var, color_scheme = get_color_scheme("clusters") )plot_dr_umap_clusters( x, cluster_var, color_scheme = get_color_scheme("clusters") )
x |
Seurat object with a "umap" reduction. |
cluster_var |
Metadata column(s) to color by, as a single string (comma-separated for more than one). |
color_scheme |
(optional) Named vector of colors. Defaults to
|
Nothing; called for its file output, one dr-umap-<cluster_var>.png
per variable.
One panel per pair in pairs, colored by sample. No legend, since this only
ever runs on a single sample - see filter_cells(). Pairs are a curated
list rather than every combination of a metric vector, since that would make
the panel count quadratic in the number of metrics (5 metrics -> 10 panels
via combn()) and most pairs are not biologically meaningful together.
plot_metrics_correlations( x, pairs = list(c("total_counts", "detected_genes"), c("pct_mito", "detected_genes"), c("pct_mito", "pct_ribo")), group_by = "orig.ident", color_scheme = NULL, file = NULL, width = 16, height = 5 )plot_metrics_correlations( x, pairs = list(c("total_counts", "detected_genes"), c("pct_mito", "detected_genes"), c("pct_mito", "pct_ribo")), group_by = "orig.ident", color_scheme = NULL, file = NULL, width = 16, height = 5 )
x |
Seurat object. |
pairs |
A list of length-2 character vectors, |
group_by |
Metadata column to color the points by. |
color_scheme |
(optional) Named vector of colors. Defaults to the
"samples" scheme, named by the sorted levels of |
file |
Path to save the plot to. |
width, height
|
Saved size in inches. The default is wide and short: one square panel per pair of metrics, side by side. |
A combined plot, one panel per pair.
One violin panel per metric, grouped by sample. The metrics are metadata
columns, so layer is set explicitly: VlnPlot() otherwise searches for
the "data" layer, which does not exist before NormalizeData() has been
run.
plot_metrics_distribution( x, metrics, group_by = "orig.ident", color_scheme = NULL, file = NULL, width = 12, height = 6 )plot_metrics_distribution( x, metrics, group_by = "orig.ident", color_scheme = NULL, file = NULL, width = 12, height = 6 )
x |
Seurat object. |
metrics |
Metadata columns to plot, one panel each. No default - the
caller decides, since the right set depends on context (e.g. a single
sample can afford |
group_by |
Metadata column to group the violins by. |
color_scheme |
(optional) Named vector of colors. Defaults to the
"samples" scheme, named by the sorted levels of |
file |
Path to save the plot to. |
width, height
|
Saved size in inches. Widen it when there are many samples. |
A combined plot, one panel per plotted metric.
Becomes unreadable and can take a very long time to fit for many sets, so
returns NULL when there are too many batches.
plot_var_genes_euler(var_genes_list, color_scheme = NULL, max_sets = 8)plot_var_genes_euler(var_genes_list, color_scheme = NULL, max_sets = 8)
var_genes_list |
Named list of variable gene vectors, one element per batch. |
color_scheme |
(optional) Vector of colors. |
max_sets |
Return |
A plot, or NULL if there are too many sets to draw.
UpSet plot of the variable genes shared between batches.
plot_var_genes_upset(var_genes_list, nsets = 50, nintersects = 15)plot_var_genes_upset(var_genes_list, nsets = 50, nintersects = 15)
var_genes_list |
Named list of variable gene vectors, one element per batch. |
nsets |
Maximum number of sets to include. |
nintersects |
Maximum number of intersections to show. |
An UpSet plot.
Works on any S4 object or list, not just Seurat objects. It descends into
S4 slots and list elements, bounded by max_depth. So a Seurat object,
an assay pulled from one (x[["RNA"]]), a DimReduc, or a plain nested
list all get the same recursive breakdown.
profile_object_size(x, max_depth = 3)profile_object_size(x, max_depth = 3)
x |
Any object - a Seurat object, a piece pulled from one (an assay via
|
max_depth |
How many levels to descend before reporting a subtree's total size instead of continuing to break it down. |
An Assay5's layers slot is itself a list. So
layers > counts/layers > data/layers > scale.data are sized
separately, not lumped into one layers total.
A matrix, data frame, or atomic vector is neither S4 nor a list. Passing
one of these just reports its own size, the same as calling
object.size() directly. There is nothing to descend into.
A tibble with one row per slot/element, largest first: path (its
position, " > "-separated) and size (human-readable, e.g. "1.2 Mb").
Read in Gene Expression and Antibody Capture data from a 10x Genomics Cell Ranger sparse matrix or from a text file.
read_counts_file(path, sample_name, log_file = NULL)read_counts_file(path, sample_name, log_file = NULL)
path |
Path to a matrix directory, or to a matrix.mtx.gz, text, h5, or h5ad file. Next to a matrix.mtx.gz file, the features and barcodes files must have the same prefix. |
sample_name |
A character that will be used as a prefix for all cell names. |
log_file |
Filename for the log file. |
Named list of matrices. One matrix for each data type. Currently the only two data types are 'Gene Expression' and 'Antibody Capture'
Meant for parameters that accept either an in-memory Seurat object or a serialized one - resolving here means callers do not need to check which they got themselves.
resolve_seurat_object(x)resolve_seurat_object(x)
x |
A Seurat object, a path to one saved as |
A Seurat object.
Run dimensionality reduction: pca, tsne, or umap
run_dr(x, dr_method, suffix = "", assay = "RNA", ...)run_dr(x, dr_method, suffix = "", assay = "RNA", ...)
x |
A matrix or a Seurat object. |
dr_method |
Dimensionality reduction method ("pca", "tsne", or "umap"). |
suffix |
Tag inserted into the reduction name and key. |
assay |
Assay to use (Seurat methods). Always passed explicitly here
rather than left |
... |
Passed to the chosen reduction function. |
run_dr() is a thin dispatcher: it routes to run_pca(), run_tsne(), or
run_umap() based on dr_method, forwarding suffix and anything in
.... It only carries the parameters common to every method;
method-specific ones (num_pcs, num_neighbors, reduction, ...) are
passed through ... to the chosen function. Each of those functions is
itself generic: a plain matrix takes the .default method
(irlba/Rtsne/uwot), a Seurat object takes the .Seurat method (native
RunPCA()/RunTSNE()/RunUMAP(), storing a "<method><suffix>"
reduction).
The reduced data (matrix input) or a Seurat object with the reduction added. For a Seurat object, also writes the diagnostic plot(s) for the chosen method to the working directory: PCA gets a sample-colored scatter and an elbow plot (plus a heatmap past 15 components); tSNE/UMAP get a sample-colored scatter.
run_pca(), run_tsne(), run_umap()
The default method runs irlba::prcomp_irlba() on a matrix; the Seurat
method runs Seurat::RunPCA() on the object and stores a "pca<suffix>"
reduction.
run_pca(x, ...) ## Default S3 method: run_pca(x, num_pcs = 50, suffix = "", ...) ## S3 method for class 'Seurat' run_pca( x, num_pcs = 50, suffix = "", assay = "RNA", features = NULL, var_features = FALSE, ... )run_pca(x, ...) ## Default S3 method: run_pca(x, num_pcs = 50, suffix = "", ...) ## S3 method for class 'Seurat' run_pca( x, num_pcs = 50, suffix = "", assay = "RNA", features = NULL, var_features = FALSE, ... )
x |
A matrix (default) or a Seurat object. |
... |
Passed to the underlying function. |
num_pcs |
Number of principal components. |
suffix |
Tag inserted into the reduction/column names. |
assay |
Assay to use (Seurat method). Always set explicitly. |
features |
Explicit features to use (Seurat method). |
var_features |
Use the assay's variable features (Seurat method). |
A named list (default) or a Seurat object with the reduction added (Seurat method). The Seurat method also writes the diagnostic plots to the working directory: a sample-colored scatter and an elbow plot, plus a heatmap past 15 components.
The default method runs Rtsne::Rtsne() on a matrix; the Seurat method runs
Seurat::RunTSNE() on the object and stores a "tsne<suffix>" reduction.
run_tsne(x, ...) ## Default S3 method: run_tsne(x, seed.use = 1, dim.embed = 2, suffix = "", ...) ## S3 method for class 'Seurat' run_tsne( x, seed.use = 1, dim.embed = 2, suffix = "", assay = "RNA", reduction = NULL, num_dim = NULL, features = NULL, var_features = FALSE, file_format = c("png", "pdf"), ... )run_tsne(x, ...) ## Default S3 method: run_tsne(x, seed.use = 1, dim.embed = 2, suffix = "", ...) ## S3 method for class 'Seurat' run_tsne( x, seed.use = 1, dim.embed = 2, suffix = "", assay = "RNA", reduction = NULL, num_dim = NULL, features = NULL, var_features = FALSE, file_format = c("png", "pdf"), ... )
x |
A matrix (default) or a Seurat object. |
... |
Passed to the underlying function. |
seed.use |
Seed to use. |
dim.embed |
Number of tSNE embeddings to return. |
suffix |
Tag inserted into the reduction/column names. |
assay |
Assay to use (Seurat method). Always set explicitly. |
reduction |
Existing reduction to take dimensions from (Seurat method). |
num_dim |
Number of dimensions to take from |
features |
Explicit features to use (Seurat method). |
var_features |
Use the assay's variable features (Seurat method). |
file_format |
File formats to write the scatter plot in (Seurat method). |
A tSNE embedding matrix (default) or a Seurat object with the
reduction added. The Seurat method also writes a sample-colored scatter of
the result to the working directory, as dr.<reduction>.png/.pdf (or
just .png if file_format = "png").
The default method runs uwot::umap2() on a matrix; the Seurat method runs
Seurat::RunUMAP() with umap.method = "uwot2" (also uwot::umap2()) and
stores a "umap<suffix>" reduction. Defaults match Seurat::RunUMAP() (30
neighbors, minimum distance 0.3) rather than the lower uwot defaults.
run_umap(x, ...) ## Default S3 method: run_umap(x, num_neighbors = 30, min_dist = 0.3, suffix = "", ...) ## S3 method for class 'Seurat' run_umap( x, num_neighbors = 30, min_dist = 0.3, suffix = "", assay = "RNA", reduction = NULL, num_dim = NULL, features = NULL, var_features = FALSE, graph = NULL, file_format = c("png", "pdf"), ... )run_umap(x, ...) ## Default S3 method: run_umap(x, num_neighbors = 30, min_dist = 0.3, suffix = "", ...) ## S3 method for class 'Seurat' run_umap( x, num_neighbors = 30, min_dist = 0.3, suffix = "", assay = "RNA", reduction = NULL, num_dim = NULL, features = NULL, var_features = FALSE, graph = NULL, file_format = c("png", "pdf"), ... )
x |
A matrix (default) or a Seurat object. |
... |
Passed to the underlying function. |
num_neighbors |
Number of neighbors. |
min_dist |
Minimum distance between points in the embedding. |
suffix |
Tag inserted into the reduction/column names. |
assay |
Assay to use (Seurat method). Always set explicitly. |
reduction |
Existing reduction to take dimensions from (Seurat method). |
num_dim |
Number of dimensions to take from |
features |
Explicit features to use (Seurat method). |
var_features |
Use the assay's variable features (Seurat method). |
graph |
Graph to use as input (Seurat method). |
file_format |
File formats to write the scatter plot in (Seurat method). |
A UMAP embedding matrix (default) or a Seurat object with the
reduction added. The Seurat method also writes a sample-colored scatter of
the result to the working directory, as dr.<reduction>.png/.pdf (or
just .png if file_format = "png").
Layers left split by a merge() are rejoined first, since LayerData()
would otherwise return only the first of them, and warn rather than error
while doing it.
save_counts(x, assay = "RNA", layer = "data", digits = 3, file)save_counts(x, assay = "RNA", layer = "data", digits = 3, file)
x |
A Seurat object. |
assay |
Assay to retrieve the counts from. |
layer |
Layer to retrieve. The default "data" layer holds the normalized and log-transformed expression used for visualization and most differential expression tests. |
digits |
Number of digits to round the values to. Ignored for a layer that already holds whole numbers, such as raw counts. |
file |
Path to write the table to as a csv, or |
A tibble with one row per gene.
Unlike dr_plot_width() (a label-count guess made before the plot exists),
this measures the legend actually rendered on plot - so long label text
widens the saved image even when the label count is small. Requires an
open graphics device to get accurate text metrics, so it opens and closes
a throwaway one around the measurement.
save_dr_plot( plot, file_prefix, file_format = c("png", "pdf"), width = NULL, height = 6, panel_width = height )save_dr_plot( plot, file_prefix, file_format = c("png", "pdf"), width = NULL, height = 6, panel_width = height )
plot |
A ggplot object, such as from |
file_prefix |
Path to save to without an extension. |
file_format |
File formats to write. |
width |
(optional) Saved width in inches. |
height |
Saved height in inches. |
panel_width |
Width of the plot panel itself, excluding the legend, in
inches. Only used when |
plot, invisibly.
Joins the requested reductions onto the cell metadata on a cell column.
Reductions that are not present in the object are skipped, so this works
before and after the dimensionality reduction steps have run.
save_metadata( x, reduction = c("tsne", "umap"), digits = 3, file = "metadata.csv.gz" )save_metadata( x, reduction = c("tsne", "umap"), digits = 3, file = "metadata.csv.gz" )
x |
A Seurat object. |
reduction |
Reductions to join onto the metadata. |
digits |
Number of digits to round the embeddings to. |
file |
Path to write the table to as a csv. |
The table written to file, invisibly.
Wrapper for SeuratObject::Idents() with extra safety checks.
set_identity(x, identity_column)set_identity(x, identity_column)
x |
A Seurat object. |
identity_column |
The name of the identity column to pull from object metadata. |
A Seurat object with an updated identity set.
Drops the scaled data, reductions, graphs, and clustering columns, then
splits the assay layers by a metadata column — splitting the layers rather
than the object is what the Seurat 5 IntegrateLayers() workflow expects.
split_layers_by_batch( x, batch_var = "orig.ident", assay = "RNA", num_variable_genes = 3000, num_dim = 50, log_file = NULL )split_layers_by_batch( x, batch_var = "orig.ident", assay = "RNA", num_variable_genes = 3000, num_dim = 50, log_file = NULL )
x |
Seurat object. |
batch_var |
Metadata column to split the layers by. |
assay |
Assay to split. |
num_variable_genes |
Number of variable features. Matches the single-sample default. |
num_dim |
Number of principal components to compute. |
log_file |
Filename for the log file. |
Everything after the split runs through the same verbs as the single-sample
path (normalize_counts(), run_pca()), so the two workflows cannot drift
apart on parameters. integrate_layers() then consumes the resulting "pca"
reduction.
A Seurat object with split layers and a "pca" reduction.
Reference-based annotation wrapping Seurat's reference-mapping workflow
(Seurat::FindTransferAnchors() + Seurat::TransferData()) to annotate
query with labels (cell type, or any other categorical metadata) from an
already integrated and annotated reference object. Optionally also projects
query onto the reference's UMAP via Seurat::MapQuery().
transfer_labels( query, ref, query_label_col, ref_label_col, query_assay, ref_assay, normalization, ref_reduction = "pca", num_dim, anchor_reduction = "pcaproject", ref_umap = FALSE, verbose = TRUE )transfer_labels( query, ref, query_label_col, ref_label_col, query_assay, ref_assay, normalization, ref_reduction = "pca", num_dim, anchor_reduction = "pcaproject", ref_umap = FALSE, verbose = TRUE )
query |
Query Seurat object. |
ref |
Reference Seurat object - already integrated and annotated. |
query_label_col |
Metadata column name added to |
ref_label_col |
Metadata column in |
query_assay |
Assay in |
ref_assay |
Assay in |
normalization |
Normalization method shared by |
ref_reduction |
Reduction in |
num_dim |
Number of dimensions to use for anchor finding and label transfer. |
anchor_reduction |
Dimensional reduction workflow
|
ref_umap |
If |
verbose |
Print progress messages. |
query with query_label_col (a factor) added to its metadata,
and a "ref.umap" reduction added if ref_umap = TRUE. Also writes
the predictions table (cell/predicted.id/prediction.score.max) to
annotation/annotation-transfer-label-<query_label_col>.csv.gz, and a
dr-<reduction>-<query_label_col>.png UMAP colored by the transferred
labels for each of "umap"/"ref.umap" already present on query.
After split_layers_by_batch() the per-batch variable features are stored
as vf_<method>_<layer>_variable columns in the assay meta data rather than
being reachable through VariableFeatures(), which returns the combined
set.
variable_features_by_batch(x, assay = "RNA")variable_features_by_batch(x, assay = "RNA")
x |
Seurat object with split layers. |
assay |
Assay to read the variable features from. |
normalize_counts() now clears its own assay's vf_* columns before
recomputing them. But an object built before that guard existed can still
carry a whole history of them: each sample's own pre-merge run from
create_seurat_object(), and the merge step's own post-merge preview
run. DietSeurat() clears layers, reductions, and graphs, but never
assay meta data. merge() disambiguates colliding names with a numeric
suffix, for example vf_vst_counts.1_variable.
Matching every _variable$ column would pick up that whole history along
with the batches actually being asked about. This function instead
anchors on Layers(x[[assay]], search = "counts"), the object's current
split state. That keeps stale columns out, regardless of which
generation of the object this is.
A named list of variable gene vectors, one element per batch.
Small function to write to message and to log file.
write_message(message_str, log_file = NULL)write_message(message_str, log_file = NULL)
message_str |
A string to write as a message. |
log_file |
A log filename. |
A message and writes the message to the specified log file.
write_message(message_str = "Finished Step 1", log_file = "log.file.txt")write_message(message_str = "Finished Step 1", log_file = "log.file.txt")