| Title: | Continuous cell state annotation for single-cell and spatial omics data |
|---|---|
| Description: | Continuous phenotyping of bulk, single-cell and spatial omics data using partial least squares regression. The methods are described in Mao et al. (2025) <doi:10.1186/s13059-025-03755-8> and Mao et al. (2026) <doi:10.1016/j.crmeth.2026.101483>. |
| Authors: | Jiadong Mao [aut, cre] (ORCID: <https://orcid.org/0000-0002-3818-1981>) |
| Maintainer: | Jiadong Mao <[email protected]> |
| License: | AGPL-3 |
| Version: | 0.99.0 |
| Built: | 2026-10-13 03:48:39 UTC |
| Source: | https://github.com/BiocStaging/PhiSpace |
Convert a matrix to sparse metrix.
as.sparse.matrix(X)as.sparse.matrix(X)
X |
Matrix. |
Sparse matrix version of X
Plot formatting for presentation and publication
basicPlotFormat( p, theme_overall = "bw", base_size = 8, legend.position = "top", x.text.blank = FALSE, y.text.blank = FALSE, axis.title.bold = TRUE, legend.title.bold = TRUE, axis.title.x.blank = FALSE, axis.title.y.blank = FALSE, legend.title.blank = FALSE, legend.spacing.x = 0, legend.key.spacing = 0, legend.key.spacing.y = 0, legend.box.margin = 0, legend.box.spacing = 0, legend.key.size = 8 )basicPlotFormat( p, theme_overall = "bw", base_size = 8, legend.position = "top", x.text.blank = FALSE, y.text.blank = FALSE, axis.title.bold = TRUE, legend.title.bold = TRUE, axis.title.x.blank = FALSE, axis.title.y.blank = FALSE, legend.title.blank = FALSE, legend.spacing.x = 0, legend.key.spacing = 0, legend.key.spacing.y = 0, legend.box.margin = 0, legend.box.spacing = 0, legend.key.size = 8 )
p |
A ggplot2 object. |
theme_overall |
Theme of p. |
base_size |
base_size of theme. |
legend.position |
Legend position. |
x.text.blank |
Logical. Set x axis text to blank. |
y.text.blank |
Logical. Set y axis text to blank. |
axis.title.bold |
Logical. Set title to be bold. |
legend.title.bold |
Logical. Set legend title to be bold. |
axis.title.x.blank |
Logical. Set x axis title to be bold. |
axis.title.y.blank |
Logical. Set y axis title to be bold. |
legend.title.blank |
Logical. Set legend title to be blank. |
legend.spacing.x |
Legend spacing. |
legend.key.spacing |
Legend key spacing. |
legend.key.spacing.y |
Legend key spacing on vertical direction. |
legend.box.margin |
Legend box margin. |
legend.box.spacing |
Legend box spacing., |
legend.key.size |
Legend key size. |
A ggplot2 object.
A generic function to compute a correlation matrix for different input types, including matrix,
data.frame and SingleCellExperiment objects.
cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'matrix' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'data.frame' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'SingleCellExperiment' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL)cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'matrix' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'data.frame' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL) ## S4 method for signature 'SingleCellExperiment' cellTypeCorMat(input, mask = NULL, reducedDimName = "PhiSpace", groupBy = NULL)
input |
A |
mask |
A zero-one matrix with the same number of rows as the input. Optional. If provided,
each column of |
reducedDimName |
A character string specifying the name of the reduced dimension to use for |
groupBy |
A column of |
This method calculates the correlation matrix directly for the input matrix.
This method first converts the data.frame to a matrix and then calculates the correlation matrix.
This method uses the reduced dimension "PhiSpace" of the SingleCellExperiment object to compute the correlation matrix.
If "PhiSpace" is not available, an error is raised.
If mask is provided, returns a list of correlation matrices (one per column of mask).
Otherwise, returns a single correlation matrix.
set.seed(1) scores <- matrix(rnorm(200), 50, 4, dimnames = list(NULL, LETTERS[1:4])) cellTypeCorMat(scores) # One correlation matrix per group of rows. mask <- cbind(first = rep(c(1, 0), each = 25), second = rep(c(0, 1), each = 25)) names(cellTypeCorMat(scores, mask = mask))set.seed(1) scores <- matrix(rnorm(200), 50, 4, dimnames = list(NULL, LETTERS[1:4])) cellTypeCorMat(scores) # One correlation matrix per group of rows. mask <- cbind(first = rep(c(1, 0), each = 25), second = rep(c(0, 1), each = 25)) names(cellTypeCorMat(scores, mask = mask))
Calculate classification errors.
classErr(classQuery, classOriginal, labPerSample = NULL)classErr(classQuery, classOriginal, labPerSample = NULL)
classQuery |
Character vector. |
classOriginal |
Character vector. |
labPerSample |
Integer. |
A list containing:
err |
Numeric vector: the overall error rate and the balanced error rate (the mean of the per-class error rates). |
byClassErrs |
Named numeric vector of per-class error rates. |
Center log ratio normalisation
CLRnorm(sce, assayName = "counts", targetAssay = "data", offset = 1)CLRnorm(sce, assayName = "counts", targetAssay = "data", offset = 1)
sce |
SCE object |
assayName |
Assay to normalise |
targetAssay |
Name of normalised assay |
offset |
Offset value added to raw counts |
SCE object
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- CLRnorm(sce) assay(sce, "data")[1:3, 1:3]sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- CLRnorm(sce) assay(sce, "data")[1:3, 1:3]
Performs k-means clustering on principal components derived from PhiSpace scores or any other matrix-like data. This is useful for identifying spatial niches or clusters based on cell state compositions or gene expression patterns.
clusterPhiSpace( x, k = NULL, k_range = NULL, select_k_method = c("silhouette", "elbow"), ncomp = NULL, reducedDimName = "PhiSpace", use_assay = NULL, nstart = 20, iter.max = 500, algorithm = c("Lloyd", "Hartigan-Wong", "MacQueen", "Forgy"), center = TRUE, scale = FALSE, seed = NULL, silhouette_max_cells = Inf, return_pca = TRUE, store_in_colData = FALSE, cluster_name = "PhiClust" )clusterPhiSpace( x, k = NULL, k_range = NULL, select_k_method = c("silhouette", "elbow"), ncomp = NULL, reducedDimName = "PhiSpace", use_assay = NULL, nstart = 20, iter.max = 500, algorithm = c("Lloyd", "Hartigan-Wong", "MacQueen", "Forgy"), center = TRUE, scale = FALSE, seed = NULL, silhouette_max_cells = Inf, return_pca = TRUE, store_in_colData = FALSE, cluster_name = "PhiClust" )
x |
Either a SpatialExperiment/SingleCellExperiment object containing PhiSpace scores in reducedDim, OR a matrix-like object (matrix, sparse matrix, data frame) with features in columns and observations in rows. |
k |
Integer specifying the number of clusters. Either provide k or k_range but not both. |
k_range |
Integer vector of length 2 specifying range of k values to test (e.g., c(5, 15)). Will use elbow method or silhouette to select optimal k. Either provide k or k_range but not both. |
select_k_method |
Character string specifying method to select optimal k when k_range is provided. Options: "elbow" (total within-cluster SS) or "silhouette" (average silhouette width). Default is "silhouette". |
ncomp |
Integer specifying number of principal components to use for clustering. If NULL (default), uses min(30, nfeatures - 1). If "all", uses nfeatures - 1 components. |
reducedDimName |
Character string specifying which reducedDim slot contains the PhiSpace scores. Only used when x is a SingleCellExperiment or SpatialExperiment. Default is "PhiSpace". |
use_assay |
Character string specifying which assay to use if extracting data from a SingleCellExperiment/SpatialExperiment object instead of using reducedDim. If NULL (default), uses reducedDim specified by reducedDimName. Common options: "logcounts", "counts", "normcounts". |
nstart |
Integer specifying number of random starts for k-means. Default is 20. |
iter.max |
Integer specifying maximum number of iterations. Default is 500. |
algorithm |
Character string specifying k-means algorithm. Options are "Hartigan-Wong", "Lloyd", "Forgy", "MacQueen". Default is "Lloyd". |
center |
Logical indicating whether to center data before PCA. Default is TRUE. |
scale |
Logical indicating whether to scale data before PCA. Default is FALSE. |
seed |
Integer seed for reproducibility. Default is NULL (no seed set). The function sets the seed with |
silhouette_max_cells |
Number or |
return_pca |
Logical indicating whether to return PCA results. Default is TRUE. |
store_in_colData |
Logical indicating whether to store cluster assignments in the colData of the input object (only applicable when x is an SCE/SPE). Default is FALSE. |
cluster_name |
Character string specifying the column name for cluster assignments if store_in_colData is TRUE. Default is "PhiClust". |
This function implements a common workflow for spatial clustering:
Extract data (from reducedDim, assay, or use directly if matrix)
Perform PCA to reduce dimensionality
Select top principal components
Apply k-means clustering
The function can either:
Use a fixed k value (specify k parameter)
Automatically select k from a range (specify k_range parameter)
When k_range is provided, the function tests all k values in the range and selects the optimal k using either:
Silhouette method (default): Maximizes average silhouette width
Elbow method: Identifies elbow point in total within-cluster sum of squares
A list with class "PhiSpaceClustering" containing:
clusters |
Factor vector of cluster assignments |
cluster_centers |
Matrix of cluster centers in PC space |
kmeans_result |
Full kmeans object from stats::kmeans |
pca_result |
PCA results (if return_pca = TRUE) |
pc_scores |
Matrix of PC scores used for clustering |
optimal_k |
Selected k value (relevant when k_range is used) |
k_selection |
List with selection metrics (if k_range was used) |
parameters |
List of parameters used |
spe |
Updated object (if store_in_colData = TRUE and x is SCE/SPE) |
The function accepts multiple input types:
SingleCellExperiment/SpatialExperiment: Uses reducedDim (default) or assay
Matrix: Standard R matrix with observations in rows
Sparse matrix: dgCMatrix or similar sparse formats
Data frame: Coerced to matrix
The number of PCs to use affects clustering resolution:
Fewer PCs (e.g., 10-15): Broader, more general clusters
More PCs (e.g., 30-50): Finer, more specific clusters
Default (30): Good balance for most applications
Lloyd (default): Standard algorithm, good balance of speed and quality
Hartigan-Wong: Often better results but slower
MacQueen: Faster but may converge to local optima
Forgy: Similar to Lloyd
set.seed(1) scores <- matrix(rnorm(150 * 5), 150, 5, dimnames = list(NULL, LETTERS[1:5])) scores[1:50, 1] <- scores[1:50, 1] + 3 scores[51:100, 2] <- scores[51:100, 2] + 3 res <- clusterPhiSpace(scores, k = 3, seed = 1) res table(res$clusters) # Choose k from a range with the silhouette method. res <- clusterPhiSpace(scores, k_range = 2:5, seed = 1) summary(res) plot(res, type = "silhouette")set.seed(1) scores <- matrix(rnorm(150 * 5), 150, 5, dimnames = list(NULL, LETTERS[1:5])) scores[1:50, 1] <- scores[1:50, 1] + 3 scores[51:100, 2] <- scores[51:100, 2] + 3 res <- clusterPhiSpace(scores, k = 3, seed = 1) res table(res$clusters) # Choose k from a range with the silhouette method. res <- clusterPhiSpace(scores, k_range = 2:5, seed = 1) summary(res) plot(res, type = "silhouette")
Convert discrete annotations to dummy variable matrices.
codeY(sce, phenotypes, method = c("-1,1", "0,1"))codeY(sce, phenotypes, method = c("-1,1", "0,1"))
sce |
SingleCellExperiment object. |
phenotypes |
Which phenotype annotations (e.g. cell types) to convert. |
method |
Which coding to use, either (-1,1) or (0,1). |
YY |
A dummy variable matrix encoding discrete annotation |
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) YY <- codeY(sce, phenotypes = c("Cell_Cycle", "Treatment")) head(YY)sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) YY <- codeY(sce, phenotypes = c("Cell_Cycle", "Treatment")) head(YY)
Convert discrete annotations to dummy variable matrices.
codeY_vec(vec, rowNames = NULL, method = c("-1,1", "0,1"))codeY_vec(vec, rowNames = NULL, method = c("-1,1", "0,1"))
vec |
Factor contanining class labels. |
rowNames |
Optional. Row names for output dummy matrix (eg cell barcode). |
method |
Which coding to use, either (-1,1) or (0,1). |
YY |
A dummy variable matrix encoding discrete annotation |
codeY_vec(c("B", "T", "T", "NK"), rowNames = paste0("cell", 1:4)) codeY_vec(c("B", "T", "T", "NK"), method = "0,1")codeY_vec(c("B", "T", "T", "NK"), rowNames = paste0("cell", 1:4)) codeY_vec(c("B", "T", "T", "NK"), method = "0,1")
Compute kernel weights based on distances
compute_kernel_weights(distances, kernel, sigma = NULL)compute_kernel_weights(distances, kernel, sigma = NULL)
distances |
Matrix of distances (cells x neighbors) |
kernel |
Kernel type: "gaussian", "uniform", or "linear" |
sigma |
Bandwidth parameter (auto-computed if NULL) |
Matrix of weights
Compute UMAP.
computeUMAP( dat, computPC = TRUE, ncomp = 30, center = TRUE, scale = FALSE, config = NULL )computeUMAP( dat, computPC = TRUE, ncomp = 30, center = TRUE, scale = FALSE, config = NULL )
dat |
Input data. |
computPC |
Whether to compute PC first. |
ncomp |
Number of PC components |
center |
Center or not. |
scale |
Scale or not. |
config |
Configuration of UMAP (see |
UMAP coordinates.
set.seed(1) X <- matrix(rnorm(100 * 10), 100, 10, dimnames = list(paste0("cell", 1:100), NULL)) emb <- computeUMAP(X, ncomp = 5) dim(emb)set.seed(1) X <- matrix(rnorm(100 * 10), 100, 10, dimnames = list(paste0("cell", 1:100), NULL)) emb <- computeUMAP(X, ncomp = 5) dim(emb)
Tune ncomp using cross-validation.
CVTune_ncomp( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, center = TRUE, scale = FALSE, ncompLimits = c(1, 100), gridSize = 20, ncompGrid = NULL, selectedFeat = NULL, Kfolds = 5, regMethod = "PCA", labelCode = "-1,1", Ncores = 1, seed = 5202056, ncomp = NULL )CVTune_ncomp( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, center = TRUE, scale = FALSE, ncompLimits = c(1, 100), gridSize = 20, ncompGrid = NULL, selectedFeat = NULL, Kfolds = 5, regMethod = "PCA", labelCode = "-1,1", Ncores = 1, seed = 5202056, ncomp = NULL )
reference |
|
assayName |
Character. |
phenotypes |
Character. |
YY |
Matrix. |
center |
Logic. |
scale |
Logic. |
ncompLimits |
Vector. |
gridSize |
Integer. |
ncompGrid |
Vector. |
selectedFeat |
Vector. |
Kfolds |
Integer. |
regMethod |
Character. |
labelCode |
Character. |
Ncores |
Integer. |
seed |
Integer. The function sets the seed with |
ncomp |
Chosen number of components, or |
A list.
Tune nfeat using cross-validation.
CVTune_nfeat( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, ncomp = NULL, impScores = NULL, center = TRUE, scale = FALSE, nfeatLimits = c(10, 15000), gridSize = 30, nfeatV = NULL, Kfolds = 5, regMethod = "PCA", labelCode = "-1,1", seed = 5202056, Ncores = 1, nfeat = NULL )CVTune_nfeat( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, ncomp = NULL, impScores = NULL, center = TRUE, scale = FALSE, nfeatLimits = c(10, 15000), gridSize = 30, nfeatV = NULL, Kfolds = 5, regMethod = "PCA", labelCode = "-1,1", seed = 5202056, Ncores = 1, nfeat = NULL )
reference |
|
assayName |
Character. |
phenotypes |
Vector. |
YY |
Matrix. |
ncomp |
Integer. |
impScores |
Matrix. |
center |
Logic. |
scale |
Logic. |
nfeatLimits |
Vector. |
gridSize |
Integer. |
nfeatV |
Vector. |
Kfolds |
Integer. |
regMethod |
Character. |
labelCode |
Character. |
seed |
Integer. The function sets the seed with |
Ncores |
Integer. |
nfeat |
Chosen number of features per phenotype, or |
A list.
Double center a matrix by column and row means, resulting in a new matrix with zero row and column means.
doubleCent(X)doubleCent(X)
X |
A matrix or an object convertible to one. |
A double-centred matrix.
X <- matrix(1:12, 3, 4) dc <- doubleCent(X) round(rowMeans(dc), 10) round(colMeans(dc), 10)X <- matrix(1:12, 3, 4) dc <- doubleCent(X) round(rowMeans(dc), 10) round(colMeans(dc), 10)
Identifies spatial niches by performing k-means clustering on PhiSpace cell type scores. Optionally performs PCA before clustering to reduce dimensionality and improve clustering performance. Can test multiple numbers of niches and return all results for comparison.
findNiches( spe, reducedDimName = "PhiSpace", n_niches, use_pca = TRUE, ncomp = NULL, center = TRUE, scale = FALSE, kmeans_iter = 500L, kmeans_nstart = 20L, kmeans_algorithm = "Lloyd", seed = 94863, store_pca = FALSE, pca_name = "PhiSpace_PCA", verbose = TRUE )findNiches( spe, reducedDimName = "PhiSpace", n_niches, use_pca = TRUE, ncomp = NULL, center = TRUE, scale = FALSE, kmeans_iter = 500L, kmeans_nstart = 20L, kmeans_algorithm = "Lloyd", seed = 94863, store_pca = FALSE, pca_name = "PhiSpace_PCA", verbose = TRUE )
spe |
SpatialExperiment or SingleCellExperiment object containing PhiSpace scores. |
reducedDimName |
Name of the reducedDim containing PhiSpace scores (default: "PhiSpace"). |
n_niches |
Integer or vector of integers. Number(s) of niches (clusters) to identify. If a vector is provided, multiple clustering results will be generated. |
use_pca |
Logical. Whether to perform PCA before clustering (default: TRUE). |
ncomp |
Integer. Number of principal components to use if use_pca = TRUE. If NULL, defaults to half the number of cell types in PhiSpace scores. |
center |
Logical. Whether to center data for PCA (default: TRUE). |
scale |
Logical. Whether to scale data for PCA (default: FALSE). |
kmeans_iter |
Integer. Maximum number of iterations for k-means (default: 500). |
kmeans_nstart |
Integer. Number of random starts for k-means (default: 20). |
kmeans_algorithm |
Character. Algorithm for k-means clustering (default: "Lloyd"). |
seed |
Integer. Random seed for reproducibility (default: 94863). The function sets the seed with |
store_pca |
Logical. Whether to store PCA results in the object (default: FALSE). |
pca_name |
Character. Name for stored PCA results if store_pca = TRUE (default: "PhiSpace_PCA"). |
verbose |
Logical. Whether to report progress and niche sizes with
|
This function identifies spatial niches by clustering cells/spots based on their PhiSpace cell type composition scores. The workflow consists of:
Extract PhiSpace scores from the specified reducedDim
Optionally perform PCA to reduce dimensionality and focus on major patterns
Apply k-means clustering to identify niches (for each k in n_niches)
Store niche assignments in colData
PCA is recommended when you have many cell types (>20) as it can improve clustering by focusing on the main axes of variation in cell type composition.
When multiple values of n_niches are provided, the function will test each one and store all results, allowing you to compare different numbers of niches and choose the most appropriate one for your analysis.
The input object with niche assignments added to colData. If a single n_niches is provided, results are stored as "spatial_niches". If multiple n_niches are provided, results are stored as "spatial_niches_k7", "spatial_niches_k8", etc. If store_pca = TRUE, PCA results are also stored in reducedDims.
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) spe <- findNiches(spe, n_niches = 3, ncomp = 3, verbose = FALSE) table(spe$spatial_niches)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) spe <- findNiches(spe, n_niches = 3, ncomp = 3, verbose = FALSE) table(spe$spatial_niches)
Compute different errors for cross-validation.
getErr( ncompGrid, XXtrain, YYtrain, XXtest, YYtest, center = TRUE, scale = FALSE, selectedFeat = NULL, regMethod = "PLS", assayName = "rank", loss = c("Frobenius", "exponential") )getErr( ncompGrid, XXtrain, YYtrain, XXtest, YYtest, center = TRUE, scale = FALSE, selectedFeat = NULL, regMethod = "PLS", assayName = "rank", loss = c("Frobenius", "exponential") )
ncompGrid |
Vector. |
XXtrain |
Matrix. |
YYtrain |
Matrix. |
XXtest |
Matrix. |
YYtest |
Matrix. |
center |
Logic. |
scale |
Logic. |
selectedFeat |
Vector. |
regMethod |
Character. |
assayName |
Character. |
loss |
Type of loss function. |
A list
Calculate errors for the cross-validation for selecting nfeat.
getErr_nfeat( nfeatV, impScores, ncomp, XXtrain, YYtrain, XXtest, YYtest, center = TRUE, scale = FALSE, regMethod = "PLS", assayName = "logcounts", loss = c("Frobenius", "exponential") )getErr_nfeat( nfeatV, impScores, ncomp, XXtrain, YYtrain, XXtest, YYtest, center = TRUE, scale = FALSE, regMethod = "PLS", assayName = "logcounts", loss = c("Frobenius", "exponential") )
nfeatV |
Vector. |
impScores |
Matrix. |
ncomp |
Integer. |
XXtrain |
Matrix. |
YYtrain |
Matrix. |
XXtest |
Matrix. |
YYtest |
Matrix. |
center |
Logic. |
scale |
Logic. |
regMethod |
Character. |
assayName |
Character. |
loss |
Type of loss function. |
A list.
Gives each row of a score matrix the name of the column with the highest
score, or the names of the labPerSample highest-scoring columns. This
function was called getClass() before PhiSpace 0.99.0; it was renamed
because that name masked methods::getClass().
getLabels(X, labPerSample = NULL)getLabels(X, labPerSample = NULL)
X |
Matrix of scores, one row per sample (for example per cell) and one named column per label. |
labPerSample |
Positive integer: the number of labels per row. The
default |
With one label per row, a character vector of column names, one
per row of X. With more, a character matrix with one row per row of
X, labels in decreasing order of score.
set.seed(1) scores <- matrix(rnorm(20), 5, 4, dimnames = list(NULL, LETTERS[1:4])) getLabels(scores) getLabels(scores, labPerSample = 2)set.seed(1) scores <- matrix(rnorm(20), 5, 4, dimnames = list(NULL, LETTERS[1:4])) getLabels(scores) getLabels(scores, labPerSample = 2)
getPC() uses irlba's partial SVD. When ncomp is at least half of the
smaller dimension of X, where irlba can be inaccurate, or when the smaller
dimension is at most 100, it uses a full SVD of a dense copy of X
instead. On such small matrices irlba may not converge, and its result then
depends on its random start; the full SVD does not.
getPC(X, ncomp, center = TRUE, scale = FALSE, sparse = FALSE)getPC(X, ncomp, center = TRUE, scale = FALSE, sparse = FALSE)
X |
Matrix. |
ncomp |
Integer. |
center |
Logic. |
scale |
Logic. |
sparse |
Use sparse matrix or not. |
A list containing
scores |
Score matrix for X. |
loadings |
Laoding matrix for X. |
sdev |
Standard deviations of the principal components. |
totVar |
Total variance of |
props |
Proportion of |
accuProps |
Cumulative sum of |
ncomp |
Number of components. |
Xmeans |
Column means used for centring, or |
Xscals |
Column standard deviations used for scaling, or |
set.seed(1) X <- matrix(rnorm(100 * 10), 100, 10) pc <- getPC(X, ncomp = 3) dim(pc$scores) pc$propsset.seed(1) X <- matrix(rnorm(100 * 10), 100, 10) pc <- getPC(X, ncomp = 3) dim(pc$scores) pc$props
Keep common genes of two SingleCellExperiment objects.
KeepCommonGenes(reference, query, dots2hyphen = FALSE)KeepCommonGenes(reference, query, dots2hyphen = FALSE)
reference |
SingleCellExperiment object. |
query |
SingleCellExperiment object. |
dots2hyphen |
Logic. |
A list containing updated SingleCellExperiment obejcts with matching features.
ref <- scuttle::mockSCE(ncells = 20, ngenes = 10) query <- scuttle::mockSCE(ncells = 20, ngenes = 10) query <- query[3:10, ] res <- KeepCommonGenes(ref, query) nrow(res$reference) nrow(res$query)ref <- scuttle::mockSCE(ncells = 20, ngenes = 10) query <- scuttle::mockSCE(ncells = 20, ngenes = 10) query <- query[3:10, ] res <- KeepCommonGenes(ref, query) nrow(res$reference) nrow(res$query)
Divides the counts of each cell by its size factor and takes
. By default the size factors are the library sizes,
centred to mean 1. This gives the same values as the defaults of
scuttle::logNormCounts(), which Bioconductor 3.24 deprecates.
logNormTransf( sce, assayName = "counts", targetAssay = "logcounts", sizeFactors = NULL )logNormTransf( sce, assayName = "counts", targetAssay = "logcounts", sizeFactors = NULL )
sce |
A |
assayName |
Name of the count assay. |
targetAssay |
Name of the new assay. |
sizeFactors |
Optional positive size factors, one per cell. The
default |
sce with the log-normalised assay targetAssay and the size
factors, centred to mean 1, in colData(sce)$sizeFactor. A sparse or
DelayedArray count matrix gives a dgCMatrix, a dense one a dense
matrix.
scranTransf() for pooled size factors, logTransf() for
log1p() of counts or relative counts.
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- logNormTransf(sce) assay(sce, "logcounts")[1:3, 1:3]sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- logNormTransf(sce) assay(sce, "logcounts")[1:3, 1:3]
Do log1p normalisation by default.
logTransf( sce, scalFactor = 10000, assayName = "counts", targetAssay = "log1p", use_log1p = TRUE, sparse = TRUE )logTransf( sce, scalFactor = 10000, assayName = "counts", targetAssay = "log1p", use_log1p = TRUE, sparse = TRUE )
sce |
SingleCellExperiment object. |
scalFactor |
Scale factor to inflate relative counts. |
assayName |
Character. |
targetAssay |
Character. |
use_log1p |
Logical. Use shifted log (log1p) transform, using raw counts instead of relative counts. |
sparse |
Store the transformed assay as sparse matrix or not. |
A SingleCellExperiment object containing a new assay after relative counts normalisation.
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- logTransf(sce, targetAssay = "log1p") assay(sce, "log1p")[1:3, 1:3]sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- logTransf(sce, targetAssay = "log1p") assay(sce, "log1p")[1:3, 1:3]
Simplified version of pls::mvr, using computationally faster versions of PCA and PLS.
mvr( X, Y, ncomp, method = c("PCA", "PLS"), center = TRUE, sparse = FALSE, scale = FALSE, DRinfo = FALSE, keepComps = seq_len(ncomp) )mvr( X, Y, ncomp, method = c("PCA", "PLS"), center = TRUE, sparse = FALSE, scale = FALSE, DRinfo = FALSE, keepComps = seq_len(ncomp) )
X |
Matrix (dense or sparse). |
Y |
Matrix. |
ncomp |
Integer. |
method |
Character. |
center |
Logic. |
sparse |
Not used; kept for backward compatibility. |
scale |
Logic. |
DRinfo |
Logic. Whether to return dimension reduction information from PCA or PLS. Disable to save memory. |
keepComps |
Integer vector. Numbers of components for which to return
regression coefficients. The default returns all, |
A sparse X (for example a dgCMatrix) stays sparse: centring and
scaling are applied implicitly, without a dense copy of X. PLS uses the
kernel algorithm of pls::kernelpls.fit.
A list containing
coefficients |
Array of regression coefficients with dimensions
features x responses x |
Xmeans |
|
Ymeans |
|
ncomp |
|
method |
set.seed(1) X <- matrix(rnorm(100 * 20), 100, 20) Y <- X[, 1:3] %*% matrix(rnorm(9), 3, 3) + matrix(rnorm(300, sd = 0.1), 100, 3) fit <- mvr(X, Y, ncomp = 3, method = "PLS") dim(fit$coefficients)set.seed(1) X <- matrix(rnorm(100 * 20), 100, 20) Y <- X[, 1:3] %*% matrix(rnorm(9), 3, 3) + matrix(rnorm(300, sd = 0.1), 100, 3) fit <- mvr(X, Y, ncomp = 3, method = "PLS") dim(fit$coefficients)
The by-row normalisation is the same as SingleR:::.trim_byLabel_and_normalize_scores.
normPhiScores(X, method = c("col", "row"))normPhiScores(X, method = c("col", "row"))
X |
Matrix. |
method |
Character. |
A matrix normalised by row or by column.
set.seed(1) scores <- matrix(rnorm(20), 5, 4, dimnames = list(NULL, LETTERS[1:4])) normPhiScores(scores) normPhiScores(scores, method = "row")set.seed(1) scores <- matrix(rnorm(20), 5, 4, dimnames = list(NULL, LETTERS[1:4])) normPhiScores(scores) normPhiScores(scores, method = "row")
Soft phenotyping of query assay.
phenotype( phenoAssay, atlas_re, assayName = "rank", scaleMethod = c("byQuery", "byRef") )phenotype( phenoAssay, atlas_re, assayName = "rank", scaleMethod = c("byQuery", "byRef") )
phenoAssay |
Matrix. Query assay to phenotype. |
atlas_re |
List. |
assayName |
Character. |
scaleMethod |
Character. |
A list containing
Yhat |
|
Proj |
PhiSpace annotates a query dataset or a list of query datasets, given an annotated bulk or single-cell RNA-seq references. PhiSpace can simultaneously model multiple layers of cell phenotypes, e.g. cell type and disease condtion.
PhiSpace( reference, query, phenotypes = NULL, response = NULL, refAssay = "rank", queryAssay = NULL, regMethod = c("PLS", "PCA"), reducedDimName = "PhiSpace", ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, storeUnNorm = FALSE, updateRef = FALSE, cellTypeThreshold = NULL, fallback = c("none", "scoreCells"), fallback_min_classes = 2, fallback_score = c("signature", "correlation") )PhiSpace( reference, query, phenotypes = NULL, response = NULL, refAssay = "rank", queryAssay = NULL, regMethod = c("PLS", "PCA"), reducedDimName = "PhiSpace", ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, storeUnNorm = FALSE, updateRef = FALSE, cellTypeThreshold = NULL, fallback = c("none", "scoreCells"), fallback_min_classes = 2, fallback_score = c("signature", "correlation") )
reference |
The references. A |
query |
The queries. An SCE object or a list of SCE object. Each must contain an assay named by |
phenotypes |
Which phenotypes (e.g. "cell type") to predict. If |
response |
Named matrix. Rows correpond to cells (columns) in reference; columns correspond to phenotypes. If not |
refAssay |
Character. Which assay in reference to use to train PhiSpace. |
queryAssay |
Character. Which assay in query to use to predict. If |
regMethod |
Character. Regression method: one of "PLS" and "PCA". |
reducedDimName |
Name of reducedDim layer to store PhiSpace scores, i.e. PhiSpace scores will be stored in reducedDim(query, reducedDimName); default is "PhiSpace". |
ncomp |
Integer. Number of components. If |
nfeat |
Integer. Number of features to choose to predict each phenotype. See details. |
selectedFeat |
Character. Alternatively, can provide a vector of pre-selected features. |
center |
Logic. Whether to perform centering. See details. |
scale |
Logic. Whether to perform scaling. See details. |
DRinfo |
Logic. Whether to return dimension reduction information from PCA or PLS. By default disabled to save memory. |
storeUnNorm |
Store unnormalised raw PhiSpace scores or not. Default is |
updateRef |
Update reference (store reference PhiSpace scores in reference sce object) or not. |
cellTypeThreshold |
Integer or NULL. If a positive integer, cell types with fewer than this many cells in the reference will be removed before model fitting. Only used when |
fallback |
Character. Optional fallback for references with too few classes. |
fallback_min_classes |
Integer. Minimum number of classes required before fitting the standard
PhiSpace model when |
fallback_score |
Character. Which |
Parameter tuning By default, PhiSpace takes ncomp equal to the total number of phenotypes. For example, if there are
20 cell types and 5 sample sources (e.g. in vivo and in vitro) defined in the reference, ncomp will be set to be 25.
By default, PhiSpace doesn't do any feature selection. However, feature selection is very straightforward in PhiSpace. The partial least squares model automatically rank all features
according to their contribution to predicting each phenotype. For example, if there are 25 phenotypes then PLS will return
25 rankings of all features. Based on this, customised feature selection can be done in two ways. The user either
specify nfeat, i.e. the number of features (or markers) used to predict each phenotype; or specify selectedFeat, i.e.
a subset of features used to predict all phenotypes (e.g. highly variable genes). If nfeat is provided, then selectedFeat
will be automatically defined as the union of the nfeat markers of all phenotypes.
Center and scale By default, PhiSpace only center the data but do not scale. This is because we often use more features than standard single-cell pipelines (e.g. Seurat selects 2,000 highly variable genes) for a better prediction. This means that we might have included genes with small variance and scaling would greatly inflate the expression levels of these genes.
If updateRef = FALSE (default): An updated query SCE object with PhiSpace annotation results stored in reducedDim slot "PhiSpace";
If updateRef = TRUE: A list of updated reference and query SCE objects with PhiSpace annotation results stored in reducedDim slot "PhiSpace".
Mao J., Deng Y. and Lê Cao K.-A. (2025). Φ-Space: continuous phenotyping of single-cell multi-omics data. Genome Biology 26, 323. doi:10.1186/s13059-025-03755-8
Mao J., Choi J. and Lê Cao K.-A. (2026). Φ-Space ST: a platform-agnostic method to identify cell states in spatial transcriptomics studies. Cell Reports Methods 6(8), 101483. doi:10.1016/j.crmeth.2026.101483
# Simulated reference and query; Cell_Cycle is the reference phenotype. set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) query <- PhiSpace(ref, query, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) head(reducedDim(query, "PhiSpace"))# Simulated reference and query; Cell_Cycle is the reference phenotype. set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) query <- PhiSpace(ref, query, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) head(reducedDim(query, "PhiSpace"))
Core single-reference implementation for PhiSpace continuous phenotyping. Given an annotated reference
dataset and one or more query datasets, this function builds a PLS or PCA regression model from the
reference and projects the query onto the learned phenotype space. Both raw and normalised PhiSpace
scores are returned. For a higher-level wrapper that handles multiple references, see PhiSpace().
PhiSpaceR_1ref( reference, query, phenotypes = NULL, response = NULL, refAssay = "log1p", queryAssay = NULL, regMethod = c("PLS", "PCA"), ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, cellTypeThreshold = NULL, fallback = c("none", "scoreCells"), fallback_min_classes = 2, fallback_score = c("signature", "correlation") )PhiSpaceR_1ref( reference, query, phenotypes = NULL, response = NULL, refAssay = "log1p", queryAssay = NULL, regMethod = c("PLS", "PCA"), ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, cellTypeThreshold = NULL, fallback = c("none", "scoreCells"), fallback_min_classes = 2, fallback_score = c("signature", "correlation") )
reference |
A |
query |
An SCE object or a list of SCE objects. The query dataset(s) to annotate.
Each must contain an assay named by |
phenotypes |
Character vector. Column name(s) in |
response |
Named matrix. Rows correspond to cells (columns) in |
refAssay |
Character. Name of the assay in |
queryAssay |
Character. Name of the assay in |
regMethod |
Character. Regression method: one of |
ncomp |
Integer. Number of PLS/PCA components. If |
nfeat |
Integer. Number of top-ranked features to select per phenotype for model fitting. If |
selectedFeat |
Character vector. A set of pre-selected feature names to use for model fitting. If
provided, overrides |
center |
Logical. Whether to center the feature matrix before regression (default: |
scale |
Logical. Whether to scale the feature matrix before regression (default: |
DRinfo |
Logical. Whether to return dimension reduction information from PCA or PLS.
Disable to save memory (default: |
cellTypeThreshold |
Integer or NULL. If a positive integer, cell types with fewer than this many
cells in the reference will be removed before model fitting. Only used when |
fallback |
Character. Optional fallback method for references with too few classes. |
fallback_min_classes |
Integer. Minimum number of classes required before fitting the standard
PhiSpace model when |
fallback_score |
Character. Which |
Parameter tuning By default, PhiSpace takes ncomp equal to the total number of phenotypes.
For example, if there are 20 cell types and 5 sample sources (e.g. in vivo and in vitro) defined
in the reference, ncomp will be set to be 25. By default, PhiSpace doesn't do any feature selection.
However, feature selection is very straightforward in PhiSpace. The partial least squares model
automatically rank all features according to their contribution to predicting each phenotype. For
example, if there are 25 phenotypes then PLS will return 25 rankings of all features. Based on this,
customised feature selection can be done in two ways. The user either specify nfeat, i.e. the number
of features (or markers) used to predict each phenotype; or specify selectedFeat, i.e. a subset of
features used to predict all phenotypes (e.g. highly variable genes). If nfeat is provided, then
selectedFeat will be automatically defined as the union of the nfeat markers of all phenotypes.
Center and scale By default, PhiSpace only center the data but do not scale. This is because we often use more features than standard single-cell pipelines (e.g. Seurat selects 2,000 highly variable genes) for a better prediction. This means that we might have included genes with small variance and scaling would greatly inflate the expression levels of these genes.
A list with the following components:
Integer. Number of components used. NA when the scoreCells fallback is used.
Matrix. Feature importance scores (regression coefficients at the final component).
NULL when the scoreCells fallback is used.
Data frame mapping phenotype labels to their categories, or NULL if response
was provided directly.
Character vector. Features used in the final model. With the scoreCells
fallback, the union of the signature features, or all centroid features if there are no
signatures.
Matrix. Raw (unnormalised) predicted scores for the reference cells.
NULL when the scoreCells fallback is used.
Matrix. Normalised predicted scores for the reference cells (via normPhiScores()).
NULL when the scoreCells fallback is used.
Matrix or list of matrices. Raw (unnormalised) PhiSpace scores for the query dataset(s). A single matrix if one query was provided; a list of matrices if multiple queries.
Matrix or list of matrices. Normalised PhiSpace scores for the query dataset(s)
(via normPhiScores()). Same structure as PhiSpaceScore.
Logical. Whether centering was applied. NA when the scoreCells fallback is used.
Logical. Whether scaling was applied. NA when the scoreCells fallback is used.
List. Internal model object from SuperPC(), containing regression results and
preprocessing parameters needed for prediction. NULL when the scoreCells fallback is used.
A PhiSpaceModel (see trainPhiSpace()) trained on the genes shared with the
queries. It can be saved and used with predict.PhiSpaceModel(). Absent when the
scoreCells fallback is used.
List. Present only when the scoreCells fallback is used. It records the method,
the score type (fallback_score), the phenotype column and its number of classes,
fallback_min_classes, and the scoreCells() metadata.
Mao J., Deng Y. and Lê Cao K.-A. (2025). Φ-Space: continuous phenotyping of single-cell multi-omics data. Genome Biology 26, 323. doi:10.1186/s13059-025-03755-8
PhiSpace() for the main user-facing wrapper that handles multiple references,
normPhiScores() for score normalisation, tunePhiSpace() for parameter tuning.
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) res <- PhiSpaceR_1ref(ref, query, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) names(res) head(res$PhiSpaceNorm)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) res <- PhiSpaceR_1ref(ref, query, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) names(res) head(res$PhiSpaceNorm)
Combines log fold change and p-value into a single significance score
(Xiao et al. 2014). By default returns the signed variant
log2FC * -log10(p) for directional ranking; set signed = FALSE
for the paper's original |log2FC| * -log10(p).
piScore( de_results, logfc_col = "avg_log2FC", pval_col = "p_val_adj", signed = TRUE, pval_floor = .Machine$double.xmin, add_column = TRUE, rank = FALSE )piScore( de_results, logfc_col = "avg_log2FC", pval_col = "p_val_adj", signed = TRUE, pval_floor = .Machine$double.xmin, add_column = TRUE, rank = FALSE )
de_results |
A data.frame-like object containing differential expression results. |
logfc_col |
Character. Column containing log2 fold change. If the default is absent, common alternatives are detected automatically. |
pval_col |
Character. Column containing p-values. If the default is absent, common alternatives are detected automatically. |
signed |
Logical. If |
pval_floor |
Numeric. Minimum p-value used before applying
|
add_column |
Logical. If |
rank |
Logical. If |
If add_column = TRUE, a data.frame with pi_score and optionally
pi_rank appended. Otherwise, a numeric vector aligned to the input rows.
Xiao Y, Hsiao T-H, Suresh U, et al. (2014) A novel significance score for gene selection and ranking. Bioinformatics 30(6):801-807. doi:10.1093/bioinformatics/btr671
de <- data.frame(gene = c("g1", "g2", "g3"), avg_log2FC = c(2, -1, 0.5), p_val_adj = c(1e-10, 0.01, 0.5)) piScore(de, rank = TRUE)de <- data.frame(gene = c("g1", "g2", "g3"), avg_log2FC = c(2, -1, 0.5), p_val_adj = c(1e-10, 0.01, 0.5)) piScore(de, rank = TRUE)
Plot method for PhiSpaceClustering objects
## S3 method for class 'PhiSpaceClustering' plot(x, type = c("pca", "elbow", "silhouette", "variance"), ...)## S3 method for class 'PhiSpaceClustering' plot(x, type = c("pca", "elbow", "silhouette", "variance"), ...)
x |
A PhiSpaceClustering object |
type |
Character string specifying plot type. Options: "pca" (PC1 vs PC2), "elbow" (elbow plot if k_range was used), "silhouette" (silhouette plot if k_range was used), "variance" (PCA variance explained). Default is "pca". |
... |
Additional arguments passed to plotting functions |
A ggplot object.
Plot PhiSpace scores as a heatmap
plotPhiSpaceHeatMap( PhiSpaceScore, phenoDict = NULL, phenotypes = NULL, queryLabs = NULL, refLvls = NULL, queryLvls = NULL, cluster_columns = FALSE, cluster_rows = FALSE, show_row_names = FALSE, show_column_names = TRUE, row_title_rot = 0, ... )plotPhiSpaceHeatMap( PhiSpaceScore, phenoDict = NULL, phenotypes = NULL, queryLabs = NULL, refLvls = NULL, queryLvls = NULL, cluster_columns = FALSE, cluster_rows = FALSE, show_row_names = FALSE, show_column_names = TRUE, row_title_rot = 0, ... )
PhiSpaceScore |
Matrix. |
phenoDict |
A named list, categorising columns (phenotypes) in |
phenotypes |
Optional. Types of phenotypes. If provided, has to be of the same length as phenoDict. |
queryLabs |
Character vector. |
refLvls |
Character vector. |
queryLvls |
Character vector. |
cluster_columns |
Logic. |
cluster_rows |
Logic. |
show_row_names |
Logic. |
show_column_names |
Logic. |
row_title_rot |
Rotation (angle) of row titles, inherited from |
... |
Additional parameters adjusting the |
A heatmap of PhiSpace scores.
set.seed(1) scores <- matrix(rnorm(60 * 5), 60, 5, dimnames = list(NULL, c("T", "B", "NK", "ctrl", "stim"))) plotPhiSpaceHeatMap( scores, phenoDict = list(cellType = c("T", "B", "NK"), treatment = c("ctrl", "stim")), queryLabs = rep(c("cluster1", "cluster2"), each = 30) )set.seed(1) scores <- matrix(rnorm(60 * 5), 60, 5, dimnames = list(NULL, c("T", "B", "NK", "ctrl", "stim"))) plotPhiSpaceHeatMap( scores, phenoDict = list(cellType = c("T", "B", "NK"), treatment = c("ctrl", "stim")), queryLabs = rep(c("cluster1", "cluster2"), each = 30) )
Score a query with a stored PhiSpace model
## S3 method for class 'PhiSpaceModel' predict(object, newdata, assay = NULL, nfeat = NULL, ...)## S3 method for class 'PhiSpaceModel' predict(object, newdata, assay = NULL, nfeat = NULL, ...)
object |
A |
newdata |
The query: a |
assay |
Character. Assay of |
nfeat |
Integer or |
... |
Not used. |
If the query lacks some of the model genes, the model is first restricted to the genes that the query has:
A model trained with nfeat and statistics over candidate genes
(nfeatPool in trainPhiSpace()) selects nfeat genes per phenotype
again, among its candidate genes that the query has, with a message. It
refits the model on these candidate genes, selects the top genes of that
fit and refits the model on them (see trainPhiSpace()).
Another model with stored statistics (see trainPhiSpace()) is refitted
exactly on these genes, with a message. The scores equal those of a model
trained on the reference with selectedFeat set to these genes.
A model without statistics (a "rank" model, a model trained with
keepStats = FALSE, or PhiSpaceR_1ref()$model) keeps the coefficients
of these genes and drops the others, with a warning. These scores are
approximate: the error grows with the share of the coefficients that the
missing genes hold, which the warning reports.
The query must be preprocessed as the reference was. Before scoring, the query values over the model genes are compared with the reference values recorded in the model (in up to 2,000 evenly spaced cells), and a warning is given if
the non-zero values are integers in one and not in the other (for example raw counts against log-transformed values);
one has negative values and the other has none (for example centred or scaled values);
the 99th percentiles of the absolute non-zero values differ by more than a factor of 10;
the model was trained on the "rank" assay and the query assay is not
"rank", or the reverse. Only an assay named "rank" is ranked again
within each cell.
The check cannot detect every difference: for example, values normalised
to different library sizes can pass it. Changes that act on all genes
alike, such as the base of the logarithm, do not change the normalised
scores, because the query is centred and each score is scaled by
normPhiScores().
A cell by phenotype matrix of raw PhiSpace scores. Use
normPhiScores() to normalise them.
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) model <- trainPhiSpace(ref, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) raw <- predict(model, query) # Normalised scores, as PhiSpace() stores them. head(normPhiScores(raw))set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) model <- trainPhiSpace(ref, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) raw <- predict(model, query) # Normalised scores, as PhiSpace() stores them. head(normPhiScores(raw))
Print method for PhiSpaceClustering objects
## S3 method for class 'PhiSpaceClustering' print(x, ...)## S3 method for class 'PhiSpaceClustering' print(x, ...)
x |
A PhiSpaceClustering object |
... |
Additional arguments (not used) |
x, invisibly. Called for the printed summary.
Converting single cells to pseudo-bulks.
pseudoBulk( sce, phenotypes = NULL, response = NULL, clusterid = NULL, assayName = "counts", resampSizes = 100, proportion = NULL, calcMean = FALSE, nPool = 15, seed = 904800 )pseudoBulk( sce, phenotypes = NULL, response = NULL, clusterid = NULL, assayName = "counts", resampSizes = 100, proportion = NULL, calcMean = FALSE, nPool = 15, seed = 904800 )
sce |
|
phenotypes |
Phenotypes to predict. Can be multiple. |
response |
Response matrix. Can be continuous. |
clusterid |
Column name of colData for specifying groups for pseudobulking. |
assayName |
Assay used for pseudobulking. |
resampSizes |
How many pseudo-bulk resamples to generate from each cluster. |
proportion |
Used to determine unequal resampSizes. |
calcMean |
Logical. Calculate mean of sum of expression for pseudobulking. |
nPool |
How many cells to use for pseudobulking. |
seed |
Random seeds. The function sets the seed with |
An updated SingleCellExpeirment object with a pseudobulk assay.
sce <- scuttle::mockSCE(ncells = 200, ngenes = 50) pb <- pseudoBulk(sce, phenotypes = "Cell_Cycle", resampSizes = 10, nPool = 5) dim(pb$reference)sce <- scuttle::mockSCE(ncells = 200, ngenes = 50) pb <- pseudoBulk(sce, phenotypes = "Cell_Cycle", resampSizes = 10, nPool = 5) dim(pb$reference)
Uses supervised learning methods (PLS-DA, PLS, or DWD) to rank features by their ability to discriminate between groups or predict a continuous response. Based on PhiSpace's correlatePhiSpace but generalized to work with any numeric data (not just PhiSpace scores).
rankFeatures( data, response, method = c("PLSDA", "PLS", "DWD"), source = c("reducedDim", "assay"), assay_name = "logcounts", reducedDim_name = "PhiSpace", ncomp = NULL, center = TRUE, scale = FALSE, dwd_params = list(), seed = NULL )rankFeatures( data, response, method = c("PLSDA", "PLS", "DWD"), source = c("reducedDim", "assay"), assay_name = "logcounts", reducedDim_name = "PhiSpace", ncomp = NULL, center = TRUE, scale = FALSE, dwd_params = list(), seed = NULL )
data |
A matrix or data.frame where rows are observations and columns are features. Can also be a SpatialExperiment, SingleCellExperiment, or SummarizedExperiment object. |
response |
Either a character string specifying a column name in colData
(when |
method |
Character string specifying the method: "PLSDA" for classification, "PLS" for regression, or "DWD" for binary classification. Default is "PLSDA". |
source |
Character string specifying data source when |
assay_name |
Character string specifying which assay to use when
|
reducedDim_name |
Character string specifying which reduced dimension
to use when |
ncomp |
Integer specifying number of components. If NULL (default), set automatically: number of classes for PLSDA, min(10, ncol(data)/2) for PLS. Not used for DWD. |
center |
Logical indicating whether to center features. Default is TRUE. |
scale |
Logical indicating whether to scale features. Default is FALSE. |
dwd_params |
List of parameters for DWD method (see Details). |
seed |
Integer seed for reproducibility. Default is NULL. The function sets the seed with |
Methods:
PLSDA: Partial Least Squares Discriminant Analysis for multi-class classification. Features ranked by coefficient magnitude.
PLS: Partial Least Squares regression for continuous response. Features ranked by coefficient magnitude.
DWD: Distance Weighted Discrimination for binary classification. Features ranked by discriminant weights.
DWD Parameters (in dwd_params list):
kernel: Kernel function (default: vanilladot())
qval: q-value parameter (default: 1)
lambda: Regularization parameter or sequence (default: auto-tuned)
cv_folds: Cross-validation folds (default: 5)
max_cells: Optional limit on the number of cells with a
non-linear kernel (default: Inf, no limit). A non-linear kernel needs
a cells by cells kernel matrix (8 bytes per entry: 0.8 GB for 10,000
cells, 80 GB for 100,000). If set, rankFeatures() stops before
fitting when there are more cells than this.
A list with class "FeatureRanking" containing:
method |
The method used |
importance_scores |
Matrix of feature importance scores |
scores |
For PLSDA and PLS, the PLS component scores (observations x
|
model |
The fitted model object |
feature_ranking |
Data frame with features ranked by importance |
response_summary |
Summary of the response variable |
parameters |
List of parameters used |
set.seed(1) X <- matrix(rnorm(100 * 20), 100, 20, dimnames = list(NULL, paste0("gene", 1:20))) group <- rep(c("a", "b"), each = 50) X[group == "b", 1:3] <- X[group == "b", 1:3] + 2 res <- rankFeatures(X, response = group, method = "PLSDA") head(res$feature_ranking)set.seed(1) X <- matrix(rnorm(100 * 20), 100, 20, dimnames = list(NULL, paste0("gene", 1:20))) group <- rep(c("a", "b"), each = 50) X[group == "b", 1:3] <- X[group == "b", 1:3] + 2 res <- rankFeatures(X, response = group, method = "PLSDA") head(res$feature_ranking)
SingleCellExperiment object.Rank transform of a SingleCellExperiment object.
RankTransf(sce, assayname = "counts", targetAssay = "rank", sparse = TRUE)RankTransf(sce, assayname = "counts", targetAssay = "rank", sparse = TRUE)
sce |
|
assayname |
Character. |
targetAssay |
Character. |
sparse |
Logic. |
An updated SingleCellExperiment object with a rank transformed assay.
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- RankTransf(sce) assay(sce, "rank")[1:3, 1:3]sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) sce <- RankTransf(sce) assay(sce, "rank")[1:3, 1:3]
Turn a matrix to a data.frame withe newly defined colnames.
reNameCols(mat, key = "comp")reNameCols(mat, key = "comp")
mat |
Matrix. |
key |
String. |
Data frame.
mat <- matrix(1:6, 2, 3) reNameCols(mat) reNameCols(mat, key = "PC")mat <- matrix(1:6, 2, 3) reNameCols(mat) reNameCols(mat, key = "PC")
Ranks the values within each column (the genes within each cell), with
ties given the minimum rank, and rescales the ranks to 0 to 1:
(rank - 1)/(nrow(X) - 1). A sparse matrix with no negative values stays
sparse, because its zeros have rank 1 and therefore stay 0.
RTassay(X)RTassay(X)
X |
A gene by cell matrix. |
Rank transformed gene by cell matrix (sparse).
Creates and optionally saves spatial heatmaps for all cell types from PhiSpace continuous annotations. This function generates publication-ready visualizations showing the spatial distribution of cell type scores across tissue sections.
saveCellTypeMaps( sce, methodName = "PhiSpace", tissueName = "SpatialSample", coordNames = c("x", "y"), freeColScale = FALSE, quants = c(0.1, 1), psize = 0.5, savePlots = TRUE, returnPlots = FALSE, legendPosition = "none", censQuant = 1, ctypes = NULL, outputDir = "figs/spatialCellTypeHeatmaps", width = 10, height = 10, fignrow = 4, figncol = 4, fsize_title = 10, plot_margin = c(0, 0, 0, 0), fileFormat = "png", dpi = 300 )saveCellTypeMaps( sce, methodName = "PhiSpace", tissueName = "SpatialSample", coordNames = c("x", "y"), freeColScale = FALSE, quants = c(0.1, 1), psize = 0.5, savePlots = TRUE, returnPlots = FALSE, legendPosition = "none", censQuant = 1, ctypes = NULL, outputDir = "figs/spatialCellTypeHeatmaps", width = 10, height = 10, fignrow = 4, figncol = 4, fsize_title = 10, plot_margin = c(0, 0, 0, 0), fileFormat = "png", dpi = 300 )
sce |
A |
methodName |
Character. Name of the reduced dimension containing cell type scores (default: "PhiSpace"). |
tissueName |
Character. Name identifier for the tissue/sample, used in output filenames when saving plots (default: "SpatialSample"). |
coordNames |
Character vector of length 2. Column names in |
freeColScale |
Logical. Whether to use independent color scales for each cell type (TRUE) or a unified scale across all cell types (FALSE). Unified scaling facilitates comparison between cell types (default: FALSE). |
quants |
Numeric vector of length 2. Quantiles used to set color scale
limits when |
psize |
Numeric. Point size for spatial coordinates (default: 0.5). |
savePlots |
Logical. Whether to save plots to disk (default: TRUE). |
returnPlots |
Logical. Whether to return the list of ggplot objects
(default: FALSE). Note: renamed from |
legendPosition |
Character. Position of color legend. One of "none", "left", "right", "bottom", "top" (default: "none"). |
censQuant |
Numeric between 0 and 1. Quantile threshold for censoring low values to reduce noise in visualization (default: 1, no censoring). |
ctypes |
Character vector. Specific cell types to plot. If NULL, all cell types from the annotation will be plotted (default: NULL). |
outputDir |
Character. Directory path where plots will be saved. Directory will be created if it doesn't exist (default: "figs/spatialCellTypeHeatmaps"). |
width |
Numeric. Plot width in inches when saving (default: 10). |
height |
Numeric. Plot height in inches when saving (default: 10). |
fignrow |
Integer. Number of rows in multi-panel figures (default: 4). |
figncol |
Integer. Number of columns in multi-panel figures (default: 4). |
fsize_title |
Numeric. Font size for plot titles (default: 10). |
plot_margin |
Numeric vector of length 4. Plot margins in points (top, right, bottom, left) (default: c(0,0,0,0)). |
fileFormat |
Character. File format for saved plots. One of "png", "pdf", "jpeg", "tiff" (default: "png"). |
dpi |
Numeric. Resolution for raster formats (default: 300). |
This function creates spatial heatmaps showing the distribution of PhiSpace cell type scores across tissue sections. Each cell type is visualized as a separate heatmap where color intensity represents the confidence score for that cell type at each spatial location.
Key features:
Automatic handling of both SingleCellExperiment and SpatialExperiment objects
Flexible color scaling options (unified vs. independent scales)
Multi-panel output for efficient visualization of many cell types
Customizable censoring to reduce visualization noise
Multiple output formats supported
Color scaling:
freeColScale = FALSE: Uses the same color scale across all cell types,
facilitating direct comparison of scores between different cell types
freeColScale = TRUE: Each cell type uses its own optimal color scale,
maximizing contrast within each individual plot
Output organization: When saving plots, multiple cell types are arranged in multi-panel figures (e.g., 4x4 grids). If there are more cell types than can fit in one figure, multiple files will be created with sequential numbering.
If returnPlots = TRUE, returns a named list of ggplot objects,
one for each cell type. If savePlots = TRUE, plots are saved to the
specified directory. Invisible NULL otherwise.
VizSpatial for single cell type visualization
PhiSpace for generating cell type annotations
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) # Return the maps instead of writing files. maps <- saveCellTypeMaps(spe, savePlots = FALSE, returnPlots = TRUE) names(maps)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) # Return the maps instead of writing files. maps <- saveCellTypeMaps(spe, savePlots = FALSE, returnPlots = TRUE) names(maps)
Converts a cell by cell type likelihood matrix to a probability matrix by setting negative values to zero and normalizing each row to sum to 1.
Score2Prob(PhiSc)Score2Prob(PhiSc)
PhiSc |
A numeric matrix containing values ranging from -1 to 1. Rows typically represent cells and columns represent cell types. |
The function performs the following steps:
Sets all negative similarity values to zero
Calculates the sum of each row
Divides each element in a row by the row sum to create probabilities
Handles edge cases where rows sum to zero after removing negatives
For rows that contain all negative values (resulting in zero sums after transformation), the function will issue a warning and set those rows to all zeros. Alternative behavior could be implemented to assign uniform probabilities.
A numeric matrix of the same dimensions as the input, where:
All negative values are set to zero
Each row sums to 1 (forms a probability distribution)
Row and column names are preserved from the input
set.seed(1) scores <- matrix(runif(20, -1, 1), 5, 4, dimnames = list(NULL, LETTERS[1:4])) round(Score2Prob(scores), 2)set.seed(1) scores <- matrix(runif(20, -1, 1), 5, 4, dimnames = list(NULL, LETTERS[1:4])) round(Score2Prob(scores), 2)
scoreCells() provides a lightweight correlation- and signature-based
fallback for regimes where a full PhiSpace model is not meaningful, such as
single-class references or references with very few classes. It stores score
matrices in reducedDim() slots with one column per reference class.
scoreCells( reference, query, class_col = NULL, assay_ref = "logcounts", assay_query = "logcounts", signature_genes = NULL, signature_method = c("mean", "findMarkers"), marker_test = c("t", "wilcox", "binom"), marker_pval_type = "any", marker_direction = c("up", "down", "any"), n_top_genes = 300, n_signature_genes = 100, remove_housekeeping = TRUE, housekeeping_patterns = c("^Rpl", "^Rps", "^mt-", "^MT-", "^Mrpl", "^Mrps"), housekeeping_genes = NULL, shared_genes_only = TRUE, scoring = c("both", "correlation", "signature"), cor_method = c("spearman", "pearson"), zscore_signature = TRUE, score_prefix = "scoreCells", BPPARAM = BiocParallel::SerialParam(), verbose = TRUE )scoreCells( reference, query, class_col = NULL, assay_ref = "logcounts", assay_query = "logcounts", signature_genes = NULL, signature_method = c("mean", "findMarkers"), marker_test = c("t", "wilcox", "binom"), marker_pval_type = "any", marker_direction = c("up", "down", "any"), n_top_genes = 300, n_signature_genes = 100, remove_housekeeping = TRUE, housekeeping_patterns = c("^Rpl", "^Rps", "^mt-", "^MT-", "^Mrpl", "^Mrps"), housekeeping_genes = NULL, shared_genes_only = TRUE, scoring = c("both", "correlation", "signature"), cor_method = c("spearman", "pearson"), zscore_signature = TRUE, score_prefix = "scoreCells", BPPARAM = BiocParallel::SerialParam(), verbose = TRUE )
reference |
A |
query |
A |
class_col |
Character or |
assay_ref |
Character. Assay in |
assay_query |
Character. Assay in |
signature_genes |
|
signature_method |
Character. Signature selection method. |
marker_test |
Character. Test type passed to |
marker_pval_type |
Character. |
marker_direction |
Character. Direction used when selecting markers:
|
n_top_genes |
Integer. Candidate gene pool per class before removing housekeeping genes. |
n_signature_genes |
Integer. Number of final signature genes per class. |
remove_housekeeping |
Logical. Whether to remove housekeeping genes from class signatures. |
housekeeping_patterns |
Character vector of regex patterns identifying housekeeping genes. |
housekeeping_genes |
Character vector of additional housekeeping genes.
If |
shared_genes_only |
Logical. If |
scoring |
Character. Which score matrices to compute: |
cor_method |
Character. Correlation method: |
zscore_signature |
Logical. Whether to z-score signature scores. For multi-class references, z-scoring is across classes within each cell. For a single-class reference, z-scoring is across cells. |
score_prefix |
Character. Prefix for output |
BPPARAM |
BiocParallel parameter object passed to
|
verbose |
Logical. Whether to emit progress messages. |
A correlation score measures similarity between a query cell and a reference
class centroid in the relative expression pattern across that class's
effective signature genes. Different classes can therefore be scored using
different genes. Correlations are NA for query cells with fewer than two
complete observations or zero expression variance across the relevant
signature.
A signature score is the average query expression across the same effective
signature genes, optionally z-scored. When scoring = "both", the
correlation and signature branches use exactly the same genes for each
class.
The modified query object with score matrices stored in
reducedDim() slots and run details stored in metadata(query)$scoreCells.
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) query <- scoreCells(ref, query, class_col = "Cell_Cycle", signature_method = "mean", n_signature_genes = 20, verbose = FALSE) reducedDimNames(query)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) query <- scoreCells(ref, query, class_col = "Cell_Cycle", signature_method = "mean", n_signature_genes = 20, verbose = FALSE) reducedDimNames(query)
Computes pooled size factors with scran::computeSumFactors() and
log-normalises the counts with logNormTransf().
scranTransf(sce, assayName = "counts", clusts = NULL)scranTransf(sce, assayName = "counts", clusts = NULL)
sce |
SCE object. |
assayName |
Assay name. |
clusts |
Cluster labels (optional). |
SCE object with the assay logcounts and the size factors, centred
to mean 1, in colData(sce)$sizeFactor.
sce <- scuttle::mockSCE(ncells = 200, ngenes = 200) # Pool cells within known groups to compute the size factors. sce <- scranTransf(sce, clusts = sce$Cell_Cycle) assayNames(sce)sce <- scuttle::mockSCE(ncells = 200, ngenes = 200) # Pool cells within known groups to compute the size factors. sce <- scranTransf(sce, clusts = sce$Cell_Cycle) assayNames(sce)
Select nfeat top features from each column (label) of impScores
selectFeat(impScores, nfeat = 5, absVal = TRUE)selectFeat(impScores, nfeat = 5, absVal = TRUE)
impScores |
Matrix. Each column corresponds to a phenotype (eg a cell type) and contains importance scores of features for predicting that phenotype. |
nfeat |
Number of top features to select from each column of impScores. |
absVal |
Take absolute value or not. |
Vector of selected features.
set.seed(1) imp <- matrix(rnorm(40), 10, 4, dimnames = list(paste0("gene", 1:10), LETTERS[1:4])) selectFeat(imp, nfeat = 2)$selectedFeatset.seed(1) imp <- matrix(rnorm(40), 10, 4, dimnames = list(paste0("gene", 1:10), LETTERS[1:4])) selectFeat(imp, nfeat = 2)$selectedFeat
Spatial smoothing of gene expression using KNN with kernel weighting
spatial_smooth_expression( expression_matrix, coordinates, k = 10, kernel = "linear", sigma = NULL, include_self = TRUE, verbose = TRUE )spatial_smooth_expression( expression_matrix, coordinates, k = 10, kernel = "linear", sigma = NULL, include_self = TRUE, verbose = TRUE )
expression_matrix |
Gene x Cell matrix of expression values |
coordinates |
Data frame with columns 'x' and 'y' for cell coordinates |
k |
Number of nearest neighbors (default: 10) |
kernel |
Kernel function: "gaussian", "uniform", or "linear" (default: "gaussian") |
sigma |
Bandwidth parameter for Gaussian kernel (default: auto-computed) |
include_self |
Whether to include the cell itself in smoothing (default: TRUE) |
verbose |
Whether to report progress with |
Smoothed gene x cell expression matrix
Spatially-aware subsampling of SpatialExperiment objects
spatialSampler( spe, prop = 0.1, method = "grid", grid_size = NULL, seed = 123, min_cells_per_region = 1, balance_regions = FALSE, verbose = TRUE )spatialSampler( spe, prop = 0.1, method = "grid", grid_size = NULL, seed = 123, min_cells_per_region = 1, balance_regions = FALSE, verbose = TRUE )
spe |
SpatialExperiment object |
prop |
Proportion of cells to sample (between 0 and 1) |
method |
Sampling method: "grid", "kmeans", or "random" (default: "grid") |
grid_size |
Number of grid cells per dimension for grid method (default: auto-calculated) |
seed |
Random seed for reproducibility (default: 123). The function sets the seed with |
min_cells_per_region |
Minimum cells required per spatial region (default: 1) |
balance_regions |
Whether to balance sampling across spatial regions (default: FALSE; if true, might create duplicated spatial units) |
verbose |
Whether to report progress with |
Subsampled SpatialExperiment object
set.seed(1) sce <- logNormTransf(scuttle::mockSCE(ncells = 300, ngenes = 50)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(sce)), spatialCoords = cbind(x = runif(300), y = runif(300)) ) sub <- spatialSampler(spe, prop = 0.2, method = "grid") ncol(sub)set.seed(1) sce <- logNormTransf(scuttle::mockSCE(ncells = 300, ngenes = 50)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(sce)), spatialCoords = cbind(x = runif(300), y = runif(300)) ) sub <- spatialSampler(spe, prop = 0.2, method = "grid") ncol(sub)
Spatial smoother wrapper for SpatialExperiment and SingleCellExperiment objects
spatialSmoother( object, reducedDim2smooth = "PhiSpace", smoothReducedDim = TRUE, assay2smooth = "logcounts", smoothedReducedDim = NULL, smoothedAssay = NULL, x_coord = NULL, y_coord = NULL, k = 10, kernel = "linear", sigma = NULL, include_self = TRUE, verbose = TRUE )spatialSmoother( object, reducedDim2smooth = "PhiSpace", smoothReducedDim = TRUE, assay2smooth = "logcounts", smoothedReducedDim = NULL, smoothedAssay = NULL, x_coord = NULL, y_coord = NULL, k = 10, kernel = "linear", sigma = NULL, include_self = TRUE, verbose = TRUE )
object |
SpatialExperiment or SingleCellExperiment object |
reducedDim2smooth |
Name of reduced dimension to smooth (default: "PhiSpace") |
smoothReducedDim |
Logical, whether to smooth reduced dimensions instead of gene expression |
assay2smooth |
Name of assay to smooth (for gene expression smoothing) |
smoothedReducedDim |
Name for the new smoothed reduced dimension (default: paste0(reducedDim2smooth, "_smoothed")) |
smoothedAssay |
Name for the new smoothed assay (default: paste0(assay2smooth, "_smoothed")) |
x_coord |
Column name in colData for x coordinates (required for SCE objects) |
y_coord |
Column name in colData for y coordinates (required for SCE objects) |
k |
Number of nearest neighbors (default: 10) |
kernel |
Kernel function: "gaussian", "uniform", or "linear" (default: "gaussian") |
sigma |
Bandwidth parameter for Gaussian kernel (default: auto-computed) |
include_self |
Whether to include the cell itself in smoothing (default: TRUE) |
verbose |
Whether to report progress with |
Modified object with new smoothed assay or reduced dimension
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) spe <- spatialSmoother(spe, k = 5, verbose = FALSE) reducedDimNames(spe)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) spe <- spatialSmoother(spe, k = 5, verbose = FALSE) reducedDimNames(spe)
Create partitions of data for cross-validation.
split2(x, n)split2(x, n)
x |
Vector. |
n |
Integer. |
A partition of index vector x to n folds.
Subsample from a sce object
subsample(sce, key = NULL, proportion = 0.1, minCellNum = 50, seed = 5202056)subsample(sce, key = NULL, proportion = 0.1, minCellNum = 50, seed = 5202056)
sce |
SCE object to be sampled from |
key |
Required for stratefied subsampling |
proportion |
Proportion of cells to sample |
minCellNum |
Minimum number of cells in each category |
seed |
Random seed. The function sets the seed with |
A downsized SCE object
sce <- scuttle::mockSCE(ncells = 200, ngenes = 10) small <- subsample(sce, proportion = 0.2) ncol(small) # Stratified by a colData column, keeping at least 20 cells per class. strat <- subsample(sce, key = "Cell_Cycle", proportion = 0.1, minCellNum = 20) table(strat$Cell_Cycle)sce <- scuttle::mockSCE(ncells = 200, ngenes = 10) small <- subsample(sce, proportion = 0.2) ncol(small) # Stratified by a colData column, keeping at least 20 cells per class. strat <- subsample(sce, key = "Cell_Cycle", proportion = 0.1, minCellNum = 20) table(strat$Cell_Cycle)
Summary method for PhiSpaceClustering objects
## S3 method for class 'PhiSpaceClustering' summary(object, ...)## S3 method for class 'PhiSpaceClustering' summary(object, ...)
object |
A PhiSpaceClustering object |
... |
Additional arguments (not used) |
object, invisibly. Called for the printed summary.
Compute regression model using selected features.
SuperPC( reference, YY, ncomp, selectedFeat = NULL, assayName = "logcounts", regMethod = c("PCA", "PLS"), center = TRUE, scale = FALSE, sparse = TRUE, DRinfo = FALSE )SuperPC( reference, YY, ncomp, selectedFeat = NULL, assayName = "logcounts", regMethod = c("PCA", "PLS"), center = TRUE, scale = FALSE, sparse = TRUE, DRinfo = FALSE )
reference |
SingleCellExperiment object (the reference), or a cell by
gene matrix of the |
YY |
Resonse matrix |
ncomp |
Integer. Number of components |
selectedFeat |
Character. Vector containing selected feature names |
assayName |
Which assay in reference to use for prediction |
regMethod |
Character. Regression method to use, either PCA or PLS. |
center |
Logic. |
scale |
Logic. Scale the predictor matrix or not |
sparse |
Use sparse matrices or not. |
DRinfo |
Logic. Whether to return dimension reduction information from PCA or PLS. Disable to save memory. |
A list containing regression input and output.
Fits the PhiSpace regression model on an annotated reference and returns it
as a PhiSpaceModel object. The model can be saved (for example with
saveRDS()) and used later to score queries with predict()
or PhiSpace(), without the reference cells.
trainPhiSpace( reference, phenotypes = NULL, response = NULL, refAssay, regMethod = c("PLS", "PCA"), ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, cellTypeThreshold = NULL, genes = NULL, keepStats = TRUE, nfeatPool = 2000, referenceName = NULL, species = NULL, geneIdType = NULL, preprocessing = NULL )trainPhiSpace( reference, phenotypes = NULL, response = NULL, refAssay, regMethod = c("PLS", "PCA"), ncomp = NULL, nfeat = NULL, selectedFeat = NULL, center = TRUE, scale = FALSE, DRinfo = FALSE, cellTypeThreshold = NULL, genes = NULL, keepStats = TRUE, nfeatPool = 2000, referenceName = NULL, species = NULL, geneIdType = NULL, preprocessing = NULL )
reference |
A |
phenotypes |
Character vector. Column name(s) in |
response |
Named matrix. Rows correspond to cells (columns) in
|
refAssay |
Character. Name of the assay in |
regMethod |
Character. |
ncomp |
Integer. Number of components. If |
nfeat |
Integer. Number of top features per phenotype. If |
selectedFeat |
Character vector. Pre-selected features; overrides
|
center, scale
|
Logical. Centring and scaling of the features. |
DRinfo |
Logical. Whether to keep the PLS or PCA scores and loadings. |
cellTypeThreshold |
Integer or |
genes |
Character vector or |
keepStats |
Logical. Whether to store the cross-product statistics
that refit the model on a subset of its genes. Ignored for the |
nfeatPool |
Number or |
referenceName, species, geneIdType
|
Character or |
preprocessing |
Character or |
PhiSpaceR_1ref() and PhiSpace() fit the same model on the genes that the
reference shares with the query. trainPhiSpace() uses all reference genes,
or the genes given in genes.
A query may lack some of the model genes, for example a targeted spatial
panel. With keepStats = TRUE (the default), the model stores the
cross-products and of the centred (and scaled)
reference over the model genes. predict() then
refits the model on the genes that the query has, without the reference
cells. The refitted model equals a model trained on the reference with
selectedFeat set to those genes.
With nfeat, the genes are selected by a fit on all reference genes,
whereas PhiSpace() selects them among the genes that the reference shares
with the query. A model trained with nfeat therefore stores the
statistics of a larger set of candidate genes: the top nfeatPool genes
per phenotype. If the query lacks some model genes,
predict() refits the model on the candidate genes
that the query has, selects nfeat genes per phenotype from that fit and
refits the model on them. The result approximates the PhiSpace() fit on
the reference cells; with all genes as candidates (nfeatPool = Inf), the
two are equal. When the query genes are known before training, for example
a targeted panel, set genes to them: the model then selects its genes
among the query genes, as PhiSpace() does.
The statistics are not kept for the "rank" assay. Ranks are computed
within each cell over the model genes, so removing genes changes the
reference values and an exact refit needs the reference cells. A "rank"
model therefore scores a query that lacks genes approximately, with a
warning (see predict.PhiSpaceModel()).
has one row and one column per model gene: it takes
bytes for genes, for example 72 MB for 3,000 genes and
3.2 GB for 20,000 genes. Use nfeat (with a smaller nfeatPool),
selectedFeat or genes to train on fewer genes, or keepStats = FALSE.
A larger nfeatPool gives a selection closer to that of PhiSpace(),
and a larger model.
A PhiSpaceModel object: a list with
The fitted model, as returned in PhiSpaceR_1ref()$atlas_re.
Genes used by the model, in model order.
Feature importance scores (see PhiSpaceR_1ref()).
Phenotype labels and their categories, or NULL if
response was given.
Names of the score columns.
The training assay.
Number of reference cells used for training.
Number of reference cells in each phenotype label, in
the order of phenoDict, or NULL if response was given. Labels with
few cells give less reliable scores.
NULL, or a list with XtX (genes x genes) and XtY
(genes x phenotypes): the cross-products of the centred (and scaled)
reference over the model genes (or over the candidate genes, see
nfeatPool), with the uncoded response, and the column means
Xmeans and standard deviations Xscals used.
The nfeat used for gene selection, or NULL;
the nfeatPool of the stored candidate genes, or NULL if the
statistics cover only the selected genes.
As supplied, or
NULL.
A summary of the reference values over the model genes, used to check queries: whether all non-zero values are integers, the share of negative values and the 99th percentile of the absolute non-zero values, in up to 2,000 evenly spaced cells.
Model format version, the PhiSpace version that trained the model, and the date.
predict.PhiSpaceModel(), PhiSpace(), PhiSpaceR_1ref().
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) model <- trainPhiSpace(ref, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3, referenceName = "mock reference") model scores <- predict(model, query) head(scores) # A model can replace the reference in PhiSpace(). query <- PhiSpace(model, query)set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) model <- trainPhiSpace(ref, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3, referenceName = "mock reference") model scores <- predict(model, query) head(scores) # A model can replace the reference in PhiSpace(). query <- PhiSpace(model, query)
Translate cell type labels from finer to coarser according to a dictionary.
translateLabel(text, dictionary, dFrom = "label.fine", dTo = "label.main")translateLabel(text, dictionary, dFrom = "label.fine", dTo = "label.main")
text |
Character vector. |
dictionary |
Data frame. |
dFrom |
Character. |
dTo |
Character. |
A vector containing translated labels.
dictionary <- data.frame( label.fine = c("CD4 T", "CD8 T", "Naive B"), label.main = c("T cell", "T cell", "B cell") ) translateLabel(c("CD8 T", "Naive B", "CD4 T"), dictionary)dictionary <- data.frame( label.fine = c("CD4 T", "CD8 T", "Naive B"), label.main = c("T cell", "T cell", "B cell") ) translateLabel(c("CD8 T", "Naive B", "CD4 T"), dictionary)
Computes the K-fold cross-validation loss of a PhiSpace model over a grid
of numbers of components (ncomp) and then over a grid of numbers of
features per phenotype (nfeat), and returns the chosen values with the
selected features. In an interactive session the function plots each loss
curve and asks for a value unless ncomp or nfeat is given. In a
non-interactive session it chooses the ncomp with the lowest loss, and
nfeat must be given when tune_nfeat = TRUE.
tunePhiSpace( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, ncomp = NULL, impScores = NULL, center = TRUE, scale = FALSE, tune_ncomp = TRUE, tune_nfeat = TRUE, ncompLimits = c(1, 100), ncompGridSize = 20, ncompGrid = NULL, selectedFeat = NULL, nfeatLimits = c(10, 15000), nfeatGridSize = 30, nfeatV = NULL, Kfolds = 5, regMethod = "PLS", labelCode = "-1,1", Ncores = 1, seed = 5202056, cellTypeThreshold = NULL, nfeat = NULL )tunePhiSpace( reference, assayName = "logcounts", phenotypes = NULL, YY = NULL, ncomp = NULL, impScores = NULL, center = TRUE, scale = FALSE, tune_ncomp = TRUE, tune_nfeat = TRUE, ncompLimits = c(1, 100), ncompGridSize = 20, ncompGrid = NULL, selectedFeat = NULL, nfeatLimits = c(10, 15000), nfeatGridSize = 30, nfeatV = NULL, Kfolds = 5, regMethod = "PLS", labelCode = "-1,1", Ncores = 1, seed = 5202056, cellTypeThreshold = NULL, nfeat = NULL )
reference |
|
assayName |
Character. |
phenotypes |
Character. |
YY |
Matrix. |
ncomp |
Integer. With |
impScores |
Matrix. |
center |
Logical. |
scale |
Logical. |
tune_ncomp |
Logical: compute the cross-validation loss for each value in the ncomp grid. |
tune_nfeat |
Logical: compute the cross-validation loss for each value in the nfeat grid. |
ncompLimits |
Vector. |
ncompGridSize |
Integer. |
ncompGrid |
Vector. |
selectedFeat |
Vector. |
nfeatLimits |
Vector. |
nfeatGridSize |
Integer. |
nfeatV |
Vector. |
Kfolds |
Integer. |
regMethod |
Character. |
labelCode |
Character. |
Ncores |
Integer. |
seed |
Integer. The function sets the seed with |
cellTypeThreshold |
Integer or NULL. If a positive integer, cell types with fewer than this many cells in the reference will be removed before tuning. Only used when |
nfeat |
Integer. With |
A list with ncomp, nfeat, impScores (feature importance
scores), selectedFeat (selected features), and tuneNcompErrs and
tuneNfeatErrs (data frames of the cross-validation loss for each grid
value, or NULL when that parameter was not tuned).
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) # Outside an interactive session, nfeat must be given. tuned <- tunePhiSpace(ref, assayName = "logcounts", phenotypes = "Cell_Cycle", ncompGrid = 1:4, nfeatV = c(20, 50), Kfolds = 3, nfeat = 50) tuned$ncomp tuned$tuneNcompErrsset.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) # Outside an interactive session, nfeat must be given. tuned <- tunePhiSpace(ref, assayName = "logcounts", phenotypes = "Cell_Cycle", ncompGrid = 1:4, nfeatV = c(20, 50), Kfolds = 3, nfeat = 50) tuned$ncomp tuned$tuneNcompErrs
The 2D spatial coordinates (x and y) should be stored as two columns in colData.
VizSpatial( obj, x_coord = "x", y_coord = "y", ptSize = 2, ptShape = 16, colBy = NULL, feature = NULL, assay2use = NULL, reducedDim = NULL, reducedDim2use = "PhiSpace", censor = FALSE, quant = 0.5, legend.position = "right", legend.symb.size = NULL, legend.title = NULL, fsize = 14, reOrder = FALSE, ... )VizSpatial( obj, x_coord = "x", y_coord = "y", ptSize = 2, ptShape = 16, colBy = NULL, feature = NULL, assay2use = NULL, reducedDim = NULL, reducedDim2use = "PhiSpace", censor = FALSE, quant = 0.5, legend.position = "right", legend.symb.size = NULL, legend.title = NULL, fsize = 14, reOrder = FALSE, ... )
obj |
Input object; either |
x_coord |
x coordinate name of a column of colData (if |
y_coord |
y coordinate name of a column of colData (if |
ptSize |
Size of point, representing spatial cell like objects (segmented cells, spots etc). |
ptShape |
Shape of point. |
colBy |
Name of a metadata column to colour points by. |
feature |
Name of a feature (eg gene) to colour points by. |
assay2use |
Which assay to use when feature is specified. |
reducedDim |
Name of reducedDim column to colour points by. |
reducedDim2use |
Name of reducedDim layer to use when reducedDim is specified. |
censor |
Logical. Whether to set smaller colour values to zero. Default is |
quant |
A value between 0 and 1. Colour values below |
legend.position |
Position of legened, one of "right", "bottome", "left" and "top". |
legend.symb.size |
Legend symbol size (for discrete legend). |
legend.title |
Alternative legend name to replace the original. |
fsize |
Base font size of figure. |
reOrder |
Logical. Whether to reorder points according to their values (ascending) or not. Set to be |
... |
Other arguments to pass to |
A ggplot2 object.
set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) VizSpatial(spe, reducedDim = "G1") VizSpatial(spe, feature = "Gene_0001", assay2use = "logcounts")set.seed(1) ref <- logNormTransf(scuttle::mockSCE(ncells = 200, ngenes = 300)) query <- logNormTransf(scuttle::mockSCE(ncells = 100, ngenes = 300)) spe <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = logcounts(query)), spatialCoords = cbind(x = runif(100), y = runif(100)) ) spe <- PhiSpace(ref, spe, phenotypes = "Cell_Cycle", refAssay = "logcounts", ncomp = 3) VizSpatial(spe, reducedDim = "G1") VizSpatial(spe, feature = "Gene_0001", assay2use = "logcounts")
Minimal quality control (QC): remove features with all zero values.
zeroFeatQC(sce, assayName = "counts", verbose = TRUE)zeroFeatQC(sce, assayName = "counts", verbose = TRUE)
sce |
SingleCellExperiment object. |
assayName |
Character. |
verbose |
Logical. Whether to report the result with |
An updated SingleCellExperiment object after minimal QC.
sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) counts(sce)[1:2, ] <- 0 sce <- zeroFeatQC(sce) dim(sce)sce <- scuttle::mockSCE(ncells = 20, ngenes = 10) counts(sce)[1:2, ] <- 0 sce <- zeroFeatQC(sce) dim(sce)