Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,37 @@ singlets with the workflow's chain, and its PCA guard gives the message of
require_min_cells_for_pca(context = "doubletfinder") (silhouette_utils.R),
in crates/cluster/src/chain.rs.

SCTransform's vars.to.regress and the workflow's percent.mt (milestone M15b)
port:

- R 4.5.3 (GPL-2 | GPL-3): LINPACK's QR as R modified it, src/appl/dqrdc2.f
(Householder reflections with R's limited column pivoting and rank, tol
1e-07 as lm.fit() passes it through src/library/stats/src/lm.c's Cdqrls and
src/appl/dqrls.f), src/appl/dqrsl.f (job 10: Q'y and the residuals) and
src/appl/dqrutl.f's dqrrsd, as qr.resid() (src/library/base/R/qr.R) calls
them, translated statement by statement into crates/rcompat/src/linpack.rs;
the BLAS routines they call (dnrm2, dscal, ddot, daxpy) are the conda env's
OpenBLAS 0.3.34 through FFI, as R's own are. make.unique()
(src/main/unique.c's do_makeunique), in crates/scio/src/features.rs.
- Seurat 5.5.1 (MIT): ScaleData.default's regression and RegressOutMatrix()
(R/preprocessing.R: lm()'s QR once, qr.resid() per row, then FastRowScale's
centring and ScaleData's NA to 0), as SCTransform.default calls them on
scale.data's clipped rows, in crates/sctransform/src/regress.rs and
residuals.rs; PercentageFeatureSet() (R/utilities.R) and the row names
Read10X() and CreateSeuratObject() give features (with SeuratObject 5.4.0's
CheckFeaturesNames()), in crates/scio/src/features.rs; vars.to.regress'
checks and covariates (SCTransform.Seurat's latent.data), in
crates/cluster/src/covariates.rs.
- Matrix 1.7-6 (GPL (>= 2)): colSums() of a dgCMatrix (src/sparse.c's
Csparse_colsum: each column's stored values, in stored order, added in
double), PercentageFeatureSet()'s numerator and denominator.
- The workflow's percent.mt (scRNAseq-preprocessing, workflow/scripts/*.R:
PercentageFeatureSet(obj, pattern = "(?i)^mt-") before SCTransform), and the
workflow's scripts before its commit 8d34de1, which passed
vars.to.regress = "percent.mt" to SCTransform: the benchmark's
validation/benchmark/workflow_regress/ copies them at 8d34de1^, with
phase-marker lines added and nothing else changed (its SOURCES.tsv).

The benchmark's harness, validation/benchmark/ (moved there from
data/benchmarks/scripts/ in milestone M15), runs copies of the workflow's
tenx2seuratrds.R, soupx.R, emptydrops.R, cellbender2seurat.R, doubletfinder.R
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ The steps:
- **M6b:** the singlets' counts as a new 10x directory, `singlets/` ([doubletfinder.md](docs/validation/doubletfinder.md#m6b-the-singlets-counts)).
- **M7:** the full panel, all 150 production objects against their saved workflow outputs ([doubletfinder_m7.md](docs/validation/doubletfinder_m7.md)).

**Step 2, the clustering chain** ([docs/PLAN.md](docs/PLAN.md) A7b and Part C), is under way: M8 (the R reference data), M9 (Annoy and the SNN graph), M10 (FindClusters), M11 (the chain end to end), M12 (neighbourhood purity), M13 (SCTransform's corrected counts and the export), M14 (the loaders) and M15 (clustering on the fly) are done. `scrust cluster --counts <10x dir> --preset workflow` runs the workflow's chain, SCTransform, RunPCA, FindNeighbors, FindClusters, the silhouette widths and the neighbourhood purities, and reproduces R bit for bit under R's OpenBLAS kernel on all 27 test and 7 production objects ([docs/validation/clustering.md](docs/validation/clustering.md)). Purity's search is exhaustive; where R's KMKNN search could treat a pair differently (on an object with an odd number of cells, the median cell and its 50th neighbour, which lie on the radius), the pair is reported. `scrust cluster --export` adds the export: the input counts, SCTransform's corrected counts and their log1p, and the per-cell metadata, as plain files that no 10x reader takes for raw counts, each listed with its role and scale in `summary.json`'s manifest ([docs/output_manifest.md](docs/output_manifest.md)). The loaders in `loaders/` build Seurat and SingleCellExperiment objects (R) and AnnData objects (Python) from any scrust output, each matrix in a slot meant for its scale, and reproduce the workflow's saved objects (M14). The chain is one library entry point (M15), which `scrust doubletfinder` also calls: given no cluster labels, it clusters its input in the same process, reproducing the labels the workflow gave all 150 production DoubletFinder inputs and M7's outputs byte for byte, and with `--recluster` it re-clusters the singlets as the workflow's DoubletFinder step does, from memory, reproducing the saved objects' labels, silhouette widths and purities on all 150 ([docs/validation/clustering.md](docs/validation/clustering.md#m15-outcome)). Substituting `scrust` into the preprocessing workflow is a separate, later change.
**Step 2, the clustering chain** ([docs/PLAN.md](docs/PLAN.md) A7b and Part C), is under way: M8 (the R reference data), M9 (Annoy and the SNN graph), M10 (FindClusters), M11 (the chain end to end), M12 (neighbourhood purity), M13 (SCTransform's corrected counts and the export), M14 (the loaders), M15 (clustering on the fly) and M15b (SCTransform's `vars.to.regress` and the workflow's `percent.mt`) are done. `scrust cluster --counts <10x dir> --preset workflow` runs the workflow's chain, SCTransform, RunPCA, FindNeighbors, FindClusters, the silhouette widths and the neighbourhood purities, and reproduces R bit for bit under R's OpenBLAS kernel on all 27 test and 7 production objects ([docs/validation/clustering.md](docs/validation/clustering.md)). Purity's search is exhaustive; where R's KMKNN search could treat a pair differently (on an object with an odd number of cells, the median cell and its 50th neighbour, which lie on the radius), the pair is reported. `scrust cluster --export` adds the export: the input counts, SCTransform's corrected counts and their log1p, and the per-cell metadata, as plain files that no 10x reader takes for raw counts, each listed with its role and scale in `summary.json`'s manifest ([docs/output_manifest.md](docs/output_manifest.md)). The loaders in `loaders/` build Seurat and SingleCellExperiment objects (R) and AnnData objects (Python) from any scrust output, each matrix in a slot meant for its scale, and reproduce the workflow's saved objects (M14). The chain is one library entry point (M15), which `scrust doubletfinder` also calls: given no cluster labels, it clusters its input in the same process, reproducing the labels the workflow gave all 150 production DoubletFinder inputs and M7's outputs byte for byte, and with `--recluster` it re-clusters the singlets as the workflow's DoubletFinder step does, from memory, reproducing the saved objects' labels, silhouette widths and purities on all 150 ([docs/validation/clustering.md](docs/validation/clustering.md#m15-outcome)). M15b adds SCTransform's `vars.to.regress`, regressing `percent.mt`, the counts' columns or a column of a per-cell table out of `scale.data`, and `percent.mt` by the workflow's pattern or by a list of mitochondrial gene ids; none by default, so every output is as before. With the regression, scrust reproduces R's runs bit for bit under R's kernel on all 134 cases checked, in both profiles ([docs/validation/clustering.md](docs/validation/clustering.md#m15b-outcome)). Substituting `scrust` into the preprocessing workflow is a separate, later change.

- Plan and validation framework: [docs/PLAN.md](docs/PLAN.md)
- Working in this repository (AI agents and contributors): [AGENTS.md](AGENTS.md)
Expand Down Expand Up @@ -76,6 +76,7 @@ target/release/scrust cluster --counts <10x dir> --preset workflow --out <dir> -
- **What it runs:** the workflow's `SCTransform(seed.use = 12345)`, its PCA guard, `RunPCA(seed.use = 12345)`, `FindNeighbors(dims = 1:30)`, `FindClusters(random.seed = 12345)` and bluster's `approxSilhouette` and `neighborPurity`, as Seurat 5.5.1 and bluster 1.20.0 do. Without `--preset workflow`, Seurat's defaults.
- **Outputs:** `seurat_clusters.tsv` (the layout `scrust doubletfinder --clusters` reads) with its levels, `clusters.tsv`, `metadata.tsv` (the counts' columns, the labels, `silhouette_width`, `silhouette_other`, `neighborhood_purity`, `purity_maximum`), `pca/`, `neighbors/` (the kNN lists and both graphs) and `summary.json` (with purity's radius and certificate).
- **Parameters:** every Seurat argument of the chain has a flag, and a TOML file (`--params`) can hold them; `scrust cluster --help` lists them.
- **Regressing out covariates** (M15b; none by default, as the workflow runs now): `--vars-to-regress percent.mt[,nCount_RNA,...]` is SCTransform's `vars.to.regress`, the regression of `scale.data` on per-cell covariates before it is centred, through R's own QR (`lm()` and `qr.resid()`); the covariates are `percent.mt`, `nCount_RNA`, `nFeature_RNA` or a numeric column of `--metadata`. `percent.mt` is Seurat's `PercentageFeatureSet()` of the mitochondrial features: by default the workflow's pattern `"(?i)^mt-"` on Seurat's feature names, which finds them only where the annotation names them `mt-`; `--mt-genes <file>` lists their ids instead (one per line, matched against `features.tsv`'s column 1). `--percent-mt` adds the column to `metadata.tsv` without regressing it. The same options go in `scrust sctransform` and, through their parameter files' `[sctransform]` section, in `scrust doubletfinder`'s clusterings.
- **Staged:** `scrust sctransform`, `scrust pca`, `scrust neighbors`, then `scrust cluster --sct`, `--pca` or `--snn` give the same files, so a sweep over k or the resolution reuses one SCTransform and PCA.
- **The export** (`--export`, from `--counts`): `counts/` (the input, copied byte for byte: the only raw counts), `sct/` with Seurat's SCT layers (`corrected_counts.mtx.gz`, `log1p_corrected_counts.mtx.gz`, `scale_data.npy`, the model), `nCount_SCT` and `nFeature_SCT` in `metadata.tsv`, and a `README.txt` saying how to load each file. None of the normalised files has a name a 10x reader looks for, and each says in its header that it is not raw counts. `scrust sctransform --corrected-counts` writes the SCT part alone; `scrust validate manifest --dir <dir>` checks any output against its manifest.

Expand Down
88 changes: 80 additions & 8 deletions crates/cluster/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,16 @@
//! **Random numbers.** R's stream (`&mut RRng`) is reseeded by SCTransform and by RunPCA, as in
//! R; Annoy and the modularity optimizer have their own generators; GroupSingletons reseeds R's
//! with `set.seed(1)`. The thread count changes no result.
//!
//! **`vars.to.regress` and `percent.mt`** (milestone M15b; [`crate::covariates`]):
//! [`cluster_counts_with`] takes what the parameters' covariates need in memory
//! ([`CellCovariates`]: `--mt-genes`' ids, `--metadata`'s columns), computes `percent.mt` from
//! the counts when asked (before SCTransform, as the workflow's scripts do), takes the QR of the
//! covariates once and hands it to SCTransform, which regresses `scale.data`'s clipped rows on
//! them before centring them. Without them the code path is the one before M15b, unchanged.

use crate::chain_params::ChainParams;
use crate::covariates::{covariate_values, CellCovariates, MtGenes, PercentMt};
use crate::find_clusters::{find_clusters, ClusterError, Factor, FindClusters};
use crate::metadata::RnaMetadata;
use crate::purity::{neighbor_purity, Purity};
Expand All @@ -46,7 +54,7 @@ use neighbors::{find_neighbors, Neighbors, NeighborsError};
use pca::{Pca, PcaError};
use rcompat::RRng;
use scio::{CscMatrix, Json};
use sctransform::{Sct, SctError};
use sctransform::{Regression, Sct, SctError};
use std::borrow::Cow;
use std::fmt;
use std::io;
Expand Down Expand Up @@ -239,8 +247,14 @@ pub struct Clustered {
pub cells: Vec<String>,
/// The counts' features (id, name): the rows of `sct/` and of the loadings.
pub features: Vec<(String, String)>,
/// `nCount_RNA` and `nFeature_RNA`, as `CreateSeuratObject()` computes them.
/// `nCount_RNA` and `nFeature_RNA`, as `CreateSeuratObject()` computes them, and `percent.mt`
/// when asked for (M15b).
pub rna: RnaMetadata,
/// `percent.mt`'s definition and record, when computed (M15b; its values are in `rna`).
pub percent_mt: Option<PercentMt>,
/// Warnings about `percent.mt` and the regression (ids not found, no feature matched, a
/// rank-deficient model), for the caller to print and record.
pub notes: Vec<String>,
pub sct: SctResult,
pub pca: PcaResult,
pub neighbors: NeighborsResult,
Expand Down Expand Up @@ -269,8 +283,16 @@ impl Clustered {
/// has what it needs, unless `opts` keeps it in the result. `obs` sees each stage as it is made
/// (stage dumps, timings); [`NoObserver`] sees nothing.
pub fn cluster_counts(counts: Cow<'_, scio::Counts>, params: &ChainParams, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result<Clustered, ChainError> {
cluster_counts_with(counts, params, &CellCovariates::default(), threads, opts, obs)
}

/// [`cluster_counts`] with what `percent.mt` and `vars.to.regress` need besides the counts
/// (M15b): `--mt-genes`' ids and `--metadata`'s columns, in memory (`cov`; the pattern when no
/// ids are given). When the parameters ask for neither, this is [`cluster_counts`].
pub fn cluster_counts_with(counts: Cow<'_, scio::Counts>, params: &ChainParams, cov: &CellCovariates, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result<Clustered, ChainError> {
params.check().map_err(ChainError::Params)?;
let rna = RnaMetadata::of(&counts.matrix);
let mut rna = RnaMetadata::of(&counts.matrix);
let (percent_mt, regression, notes) = covariates_for(&counts, params, cov, &mut rna)?;
let features: Vec<(String, String)> = counts.features().into_iter().map(|f| (f.id, f.name)).collect();
let (matrix, cells) = match counts {
Cow::Owned(c) => {
Expand All @@ -279,16 +301,66 @@ pub fn cluster_counts(counts: Cow<'_, scio::Counts>, params: &ChainParams, threa
}
Cow::Borrowed(c) => (Cow::Borrowed(&c.matrix), c.barcodes.clone()),
};
let s = stages_from_counts(matrix, params, threads, opts, obs)?;
Ok(Clustered { cells, features, rna, sct: s.sct, pca: s.pca, neighbors: s.neighbors, chain: s.chain })
let mut s = stages_from_counts(matrix, params, regression, threads, opts, obs)?;
if let (Some(p), Json::Object(m)) = (&percent_mt, &mut s.sct.summary) {
m.push(("percent_mt".into(), p.record_json()));
}
Ok(Clustered { cells, features, rna, percent_mt, notes, sct: s.sct, pca: s.pca, neighbors: s.neighbors, chain: s.chain })
}

/// `percent.mt` (when the parameters ask for it) into `rna`, and `vars.to.regress`' regression
/// (when they name covariates), from the counts and `cov` (M15b). Returns `percent.mt`'s record,
/// the regression, and the warnings for the caller.
pub fn covariates_for(counts: &scio::Counts, params: &ChainParams, cov: &CellCovariates, rna: &mut RnaMetadata) -> Result<(Option<PercentMt>, Option<Regression>, Vec<String>), ChainError> {
let mut notes = Vec::new();
let vars = &params.sct.vars_to_regress;
if params.mt_genes.is_some() != cov.mt_genes.is_some() {
return Err(ChainError::Params("--mt-genes: the parameters name a file, but its ids were not handed to the chain (or the other way round)".into()));
}
let percent_mt = if params.wants_percent_mt() {
let mt = cov.mt_genes.clone().unwrap_or(MtGenes::Pattern);
let p = PercentMt::compute(counts, &mt).map_err(ChainError::Params)?;
if p.rows.is_empty() && vars.iter().any(|v| v == crate::covariates::PERCENT_MT) {
return Err(ChainError::Params(format!(
"--vars-to-regress percent.mt: no feature's name matches the workflow's pattern \"{}\", so percent.mt would be 0 in every cell; give the mitochondrial genes' ids (column 1 of features.tsv) with --mt-genes <file>",
scio::features::MT_PATTERN
)));
}
notes.extend(p.notes());
rna.percent_mt = Some(p.values.clone());
Some(p)
} else {
None
};
let regression = if vars.is_empty() {
None
} else {
let names = counts.seurat_names();
let values = covariate_values(vars, rna, cov.metadata.as_ref(), &names).map_err(ChainError::Params)?;
let r = Regression::new(vars.clone(), &values, counts.n_cells()).map_err(ChainError::Params)?;
let (rank, p) = r.rank();
if rank < p {
notes.push(format!(
"vars.to.regress: the model matrix (the intercept and {}) has rank {rank} of {p}: lm()'s QR moved {} column(s) to the end as negligible (pivot {}), and the regression uses the first {rank}, as R's does",
vars.join(", "),
p - rank,
r.qr.pivot.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")
));
}
Some(r)
};
Ok((percent_mt, regression, notes))
}

/// From the counts (genes x cells, every stored entry as read): the whole chain, keeping only the
/// clustering and the scores (and what `opts` keeps, which this form drops); the observer sees the
/// stages. [`cluster_counts`] returns them.
pub fn from_counts(counts: CscMatrix, params: &ChainParams, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result<Chain, ChainError> {
params.check().map_err(ChainError::Params)?;
Ok(stages_from_counts(Cow::Owned(counts), params, threads, opts, obs)?.chain)
if params.needs_covariates() {
return Err(ChainError::Params("percent.mt and vars.to.regress need the counts' features and the covariates: use cluster_counts_with".into()));
}
Ok(stages_from_counts(Cow::Owned(counts), params, None, threads, opts, obs)?.chain)
}

struct Stages {
Expand All @@ -299,15 +371,15 @@ struct Stages {
}

/// The chain from the counts, stage by stage, freeing what no later stage or the result needs.
fn stages_from_counts(matrix: Cow<'_, CscMatrix>, params: &ChainParams, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result<Stages, ChainError> {
fn stages_from_counts(matrix: Cow<'_, CscMatrix>, params: &ChainParams, regression: Option<Regression>, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result<Stages, ChainError> {
let t0 = Instant::now();
let n_features = matrix.nrow;
// SCTransform.Seurat calls set.seed(seed.use) first: R's state before it does not matter
let mut rng = RRng::new(params.sct.seed_use.expect("checked"));
let started = sctransform::start(&matrix, &params.sct, &mut rng).map_err(ChainError::Sct)?;
// taken counts are freed here; borrowed ones stay with the caller
drop(matrix);
let mut sct = sctransform::finish_with(started, &params.sct, &mut rng, opts.keep_residuals, opts.correct, threads).map_err(ChainError::Sct)?;
let mut sct = sctransform::finish_full(started, &params.sct, &mut rng, opts.keep_residuals, opts.correct, regression, threads).map_err(ChainError::Sct)?;
let mut sct_result = SctResult {
summary: sctransform::output::result_json(&sct, n_features),
rng_exit: sct.rng_exit.clone(),
Expand Down
Loading