diff --git a/NOTICE b/NOTICE
index fd6ec54..9d05660 100644
--- a/NOTICE
+++ b/NOTICE
@@ -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
diff --git a/README.md b/README.md
index fe6a722..10fce43 100644
--- a/README.md
+++ b/README.md
@@ -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)
@@ -76,6 +76,7 @@ target/release/scrust cluster --counts <10x dir> --preset workflow --out
-
- **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 ` 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 ` checks any output against its manifest.
diff --git a/crates/cluster/src/chain.rs b/crates/cluster/src/chain.rs
index 39e4b91..b8c9aad 100644
--- a/crates/cluster/src/chain.rs
+++ b/crates/cluster/src/chain.rs
@@ -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};
@@ -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;
@@ -239,8 +247,14 @@ pub struct Clustered {
pub cells: Vec,
/// 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,
+ /// 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,
pub sct: SctResult,
pub pca: PcaResult,
pub neighbors: NeighborsResult,
@@ -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 {
+ 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 {
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) => {
@@ -279,8 +301,55 @@ 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, Option, Vec), ChainError> {
+ let mut notes = Vec::new();
+ let vars = ¶ms.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 ",
+ 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::>().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
@@ -288,7 +357,10 @@ pub fn cluster_counts(counts: Cow<'_, scio::Counts>, params: &ChainParams, threa
/// stages. [`cluster_counts`] returns them.
pub fn from_counts(counts: CscMatrix, params: &ChainParams, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result {
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 {
@@ -299,7 +371,7 @@ 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 {
+fn stages_from_counts(matrix: Cow<'_, CscMatrix>, params: &ChainParams, regression: Option, threads: usize, opts: Options, obs: &mut dyn Observer) -> Result {
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
@@ -307,7 +379,7 @@ fn stages_from_counts(matrix: Cow<'_, CscMatrix>, params: &ChainParams, threads:
let started = sctransform::start(&matrix, ¶ms.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, ¶ms.sct, &mut rng, opts.keep_residuals, opts.correct, threads).map_err(ChainError::Sct)?;
+ let mut sct = sctransform::finish_full(started, ¶ms.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(),
diff --git a/crates/cluster/src/chain_output.rs b/crates/cluster/src/chain_output.rs
index f7a25ec..03f270a 100644
--- a/crates/cluster/src/chain_output.rs
+++ b/crates/cluster/src/chain_output.rs
@@ -5,9 +5,10 @@
//! - `neighbors/`: FindNeighbors' result in `scrust neighbors`' layout (`neighbors::output`);
//! - the labels' files (`seurat_clusters.tsv`, `clusters.tsv`, the levels, `cluster_ids.txt`,
//! `nclusters.txt`, `optimizer_ids.tsv`; [`crate::output`]);
-//! - `metadata.tsv`: `barcode`, `nCount_RNA` and `nFeature_RNA` (when known), each `res.`
-//! column, `seurat_clusters`, `silhouette_width` and `silhouette_other`, `neighborhood_purity`
-//! and `purity_maximum` (when computed), then the columns of `--metadata`;
+//! - `metadata.tsv`: `barcode`, `nCount_RNA` and `nFeature_RNA` (when known), `percent.mt`
+//! (when asked for, M15b), each `res.` column, `seurat_clusters`, `silhouette_width` and
+//! `silhouette_other`, `neighborhood_purity` and `purity_maximum` (when computed), then the
+//! columns of `--metadata`;
//! - with `--keep-stages`: `sct/` in `scrust sctransform`'s layout (`sctransform::output`), and
//! every random start's partition (`stages/_partitions.npy`);
//! - with `--export` (M13): `sct/` with the SCT assay's corrected counts and their `log1p`
@@ -210,6 +211,12 @@ impl Writer {
cols.push(a);
names.push("nFeature_RNA".into());
cols.push(b);
+ // percent.mt (M15b), when asked for: before SCTransform's columns, as the workflow's
+ // objects hold it
+ if let Some(pm) = rna.percent_mt_texts() {
+ names.push(crate::covariates::PERCENT_MT.into());
+ cols.push(pm);
+ }
}
// with --export (M13): the SCT assay's columns, after the counts', as Seurat orders them
if let Some((nc, nf)) = &self.sct_columns {
@@ -417,9 +424,13 @@ impl Writer {
}
let found = |v: &[Entry]| v.iter().find(|e| &e.path == f).cloned();
let e = match f.as_str() {
- "metadata.tsv" => Entry::new(f, "cell_metadata", "none", "tsv", "one row per cell, in the counts' column order: barcode, nCount_RNA, nFeature_RNA, nCount_SCT and nFeature_SCT (with --export), each res. column, seurat_clusters, silhouette_width, silhouette_other, neighborhood_purity, purity_maximum, then --metadata's columns; Seurat's meta.data")
- .header(true)
- .rows(cells(f)),
+ "metadata.tsv" => Entry::new(f, "cell_metadata", "none", "tsv", if self.rna.as_ref().is_some_and(|r| r.percent_mt.is_some()) {
+ "one row per cell, in the counts' column order: barcode, nCount_RNA, nFeature_RNA, percent.mt (PercentageFeatureSet of the mitochondrial features; summary.json's result.sctransform.percent_mt says which), nCount_SCT and nFeature_SCT (with --export), each res. column, seurat_clusters, silhouette_width, silhouette_other, neighborhood_purity, purity_maximum, then --metadata's columns; Seurat's meta.data"
+ } else {
+ "one row per cell, in the counts' column order: barcode, nCount_RNA, nFeature_RNA, nCount_SCT and nFeature_SCT (with --export), each res. column, seurat_clusters, silhouette_width, silhouette_other, neighborhood_purity, purity_maximum, then --metadata's columns; Seurat's meta.data"
+ })
+ .header(true)
+ .rows(cells(f)),
"seurat_clusters.tsv" => Entry::new(f, "cluster_labels", "none", "tsv", "the cluster labels (seurat_clusters), as scrust doubletfinder --clusters reads them: barcode, seurat_clusters").header(true).rows(cells(f)),
"seurat_clusters_levels.txt" => Entry::new(f, "cluster_levels", "none", "tsv", "seurat_clusters' levels, in the factor's order, one per line").header(false),
"clusters.tsv" => Entry::new(f, "cluster_columns", "none", "tsv", "one column per resolution, named as Seurat names it (SCT_snn_res.0.8): barcode, then the columns").header(true).rows(cells(f)),
diff --git a/crates/cluster/src/chain_params.rs b/crates/cluster/src/chain_params.rs
index 562827c..2fda472 100644
--- a/crates/cluster/src/chain_params.rs
+++ b/crates/cluster/src/chain_params.rs
@@ -18,10 +18,17 @@
//! **`workflow`** is the workflow's calls (C1): seed 12345 in SCTransform, RunPCA and
//! FindClusters, `dims = 1:30`, and the PCA guard.
//!
+//! **`vars.to.regress` and `percent.mt`** (milestone M15b; [`crate::covariates`]): SCTransform's
+//! `vars.to.regress` (`--vars-to-regress`, `[sctransform] vars_to_regress`; none by default),
+//! `percent.mt` asked for without regressing it (`--percent-mt`, `percent_mt`), and its
+//! mitochondrial features given by id (`--mt-genes `, `mt_genes`; a relative path in a
+//! parameter file is read from the file's directory). `percent.mt` is computed when any of them
+//! asks for it.
+//!
//! **Other code paths are refused** with a message, as [`sctransform::SctParams::check`] does:
-//! `vars.to.regress`, another `vst.flavor` or `method`, `do.scale`, `nn.method = "rann"` or
-//! `"hnsw"`, `l2.norm = TRUE`, `annoy.metric = "hamming"`, Leiden (`algorithm = 4`), and seeds of
-//! `NULL` (which would leave R's stream where an earlier session left it).
+//! another `vst.flavor` or `method`, `do.scale`, `nn.method = "rann"` or `"hnsw"`,
+//! `l2.norm = TRUE`, `annoy.metric = "hamming"`, Leiden (`algorithm = 4`), and seeds of `NULL`
+//! (which would leave R's stream where an earlier session left it).
//!
//! **Numbers are read as R reads them:** each number's text goes through R's own decimal parser
//! (`as.numeric`), and a fraction written as text, `"1/15"`, is divided in double, as R
@@ -91,7 +98,13 @@ impl Stats {
pub struct ChainParams {
/// The preset applied (`None` for Seurat's defaults).
pub preset: Option,
+ /// SCTransform's arguments, `vars.to.regress` among them (M15b).
pub sct: SctParams,
+ /// `percent.mt` asked for without regressing it (`--percent-mt`; M15b).
+ pub percent_mt: bool,
+ /// `--mt-genes`: the file listing the mitochondrial features' ids (M15b); the command reads it
+ /// and hands its ids to the chain ([`crate::covariates::CellCovariates`]).
+ pub mt_genes: Option,
pub pca: PcaParams,
/// The workflow's `require_min_cells_for_pca()`: stop with this many cells or fewer.
pub pca_guard: Option,
@@ -106,6 +119,8 @@ impl Default for ChainParams {
ChainParams {
preset: None,
sct: SctParams::default(),
+ percent_mt: false,
+ mt_genes: None,
pca: PcaParams::default(),
pca_guard: None,
neighbors: NeighborParams::default(),
@@ -140,9 +155,20 @@ impl ChainParams {
}
}
+ /// Whether `percent.mt` is computed (M15b): asked for, given a list of features, or regressed.
+ pub fn wants_percent_mt(&self) -> bool {
+ self.percent_mt || self.mt_genes.is_some() || self.sct.vars_to_regress.iter().any(|v| v == crate::covariates::PERCENT_MT)
+ }
+
+ /// Whether the chain needs more than the counts (M15b): `percent.mt`, or covariates.
+ pub fn needs_covariates(&self) -> bool {
+ self.wants_percent_mt() || !self.sct.vars_to_regress.is_empty()
+ }
+
/// Checks every stage's parameters and refuses the paths that are not ported.
pub fn check(&self) -> Result<(), String> {
self.sct.check().map_err(|e| format!("SCTransform: {e}"))?;
+ crate::covariates::check_names(&self.sct.vars_to_regress).map_err(|e| format!("SCTransform: {e}"))?;
if self.sct.seed_use.is_none() {
return Err(refused("SCTransform's seed.use = NULL", "it leaves R's stream where an earlier session left it; give a seed"));
}
@@ -181,7 +207,7 @@ fn refused(what: &str, why: &str) -> String {
/// [`PARAM_SWITCHES`]).
pub const PARAM_FLAGS: &[&str] = &[
// SCTransform
- "sct-seed", "ncells", "variable-features", "clip-range", "vars-to-regress", "vst-flavor", "sct-method", "do-scale",
+ "sct-seed", "ncells", "variable-features", "clip-range", "vars-to-regress", "mt-genes", "vst-flavor", "sct-method", "do-scale",
// RunPCA
"npcs", "pca-seed", "weight-by-var", "pca-guard",
// FindNeighbors
@@ -193,7 +219,7 @@ pub const PARAM_FLAGS: &[&str] = &[
];
/// Flags without a value.
-pub const PARAM_SWITCHES: &[&str] = &["no-group-singletons"];
+pub const PARAM_SWITCHES: &[&str] = &["no-group-singletons", "percent-mt"];
fn int_of(name: &str, s: &str) -> Result {
s.trim().parse::().map_err(|_| format!("{name}: '{s}' is not an integer"))
@@ -235,7 +261,19 @@ pub fn set(p: &mut ChainParams, name: &str, v: &str) -> Result<(), String> {
"ncells" => p.sct.ncells = usize_of(n, v)?,
"variable-features" => p.sct.variable_features_n = Some(usize_of(n, v)?),
"clip-range" => p.sct.clip_range = Some(clip_of(n, v)?),
- "vars-to-regress" => return Err(refused("SCTransform's vars.to.regress", "regressing out variables takes sctransform down another code path, which is not ported")),
+ "vars-to-regress" => {
+ // comma-separated names, in the formula's order; empty for none
+ let vars: Vec = v.split(',').map(str::trim).filter(|t| !t.is_empty()).map(str::to_string).collect();
+ crate::covariates::check_names(&vars).map_err(|e| format!("{n}: {e}"))?;
+ p.sct.vars_to_regress = vars;
+ }
+ "mt-genes" => {
+ if v.trim().is_empty() {
+ return Err(format!("{n}: a file is needed"));
+ }
+ p.mt_genes = Some(v.to_string());
+ }
+ "percent-mt" => p.percent_mt = bool_of(n, v)?,
"vst-flavor" => {
if v.trim() != "v2" {
return Err(refused(&format!("vst.flavor = \"{v}\""), "only sctransform's v2 flavour (Seurat's default) is ported"));
@@ -304,6 +342,8 @@ const TOML_KEYS: &[(&str, &str, &str)] = &[
("sctransform", "variable_features", "variable-features"),
("sctransform", "clip_range", "clip-range"),
("sctransform", "vars_to_regress", "vars-to-regress"),
+ ("sctransform", "mt_genes", "mt-genes"),
+ ("sctransform", "percent_mt", "percent-mt"),
("sctransform", "vst_flavor", "vst-flavor"),
("sctransform", "method", "sct-method"),
("sctransform", "do_scale", "do-scale"),
@@ -375,8 +415,14 @@ pub fn read_toml(text: &str) -> Result<(Option, Vec<(String, String)>),
/// Builds the parameters: Seurat's defaults, then the preset (`cli_preset`, else the file's),
/// then the file's values, then the flags (`(name, value)`, in the order given;
-/// `no-group-singletons` as a switch). Checks the result.
+/// `no-group-singletons` and `percent-mt` as switches). Checks the result.
pub fn build(cli_preset: Option<&str>, toml_text: Option<&str>, flags: &[(String, String)]) -> Result {
+ build_in(cli_preset, toml_text, None, flags)
+}
+
+/// [`build`], with the parameter file's directory (`toml_dir`), from which a relative `mt_genes`
+/// path in the file is read (M15b).
+pub fn build_in(cli_preset: Option<&str>, toml_text: Option<&str>, toml_dir: Option<&std::path::Path>, flags: &[(String, String)]) -> Result {
let mut p = ChainParams::default();
let (file_preset, file_values) = match toml_text {
Some(t) => read_toml(t).map_err(|e| format!("--params: {e}"))?,
@@ -386,11 +432,17 @@ pub fn build(cli_preset: Option<&str>, toml_text: Option<&str>, flags: &[(String
p.apply_preset(&name)?;
}
for (k, v) in &file_values {
- set(&mut p, k, v).map_err(|e| format!("--params: {e}"))?;
+ let v = match (k.as_str(), toml_dir) {
+ ("mt-genes", Some(d)) if std::path::Path::new(v).is_relative() => d.join(v).display().to_string(),
+ _ => v.clone(),
+ };
+ set(&mut p, k, &v).map_err(|e| format!("--params: {e}"))?;
}
for (k, v) in flags {
if k == "no-group-singletons" {
p.cluster.group_singletons = false;
+ } else if k == "percent-mt" {
+ p.percent_mt = true;
} else {
set(&mut p, k, v)?;
}
@@ -457,7 +509,8 @@ mod tests {
bad("", &[("nn-method", "rann")], "nn.method");
bad("", &[("nn-method", "hnsw")], "only Annoy");
bad("", &[("l2-norm", "true")], "l2.norm");
- bad("", &[("vars-to-regress", "percent.mt")], "vars.to.regress");
+ bad("", &[("vars-to-regress", "percent.mt,percent.mt")], "twice");
+ bad("", &[("vars-to-regress", "my-col")], "not a syntactic name");
bad("", &[("metric", "hamming")], "hamming");
bad("", &[("vst-flavor", "v1")], "vst.flavor");
bad("", &[("do-scale", "TRUE")], "do.scale");
@@ -473,4 +526,25 @@ mod tests {
// the default code path's own values are accepted
assert!(build(None, None, &f(&[("nn-method", "annoy"), ("l2-norm", "false"), ("vst-flavor", "v2")])).is_ok());
}
+
+ #[test]
+ fn vars_to_regress_and_percent_mt() {
+ let d = build(Some("workflow"), None, &[]).unwrap();
+ assert!(d.sct.vars_to_regress.is_empty() && !d.wants_percent_mt() && !d.needs_covariates());
+ let p = build(None, None, &f(&[("vars-to-regress", " percent.mt , nCount_RNA")])).unwrap();
+ assert_eq!(p.sct.vars_to_regress, vec!["percent.mt", "nCount_RNA"]);
+ assert!(p.wants_percent_mt() && p.needs_covariates());
+ let p = build(None, None, &f(&[("vars-to-regress", "nCount_RNA")])).unwrap();
+ assert!(!p.wants_percent_mt() && p.needs_covariates());
+ let p = build(None, None, &f(&[("percent-mt", "")])).unwrap();
+ assert!(p.percent_mt && p.wants_percent_mt());
+ // the file: a relative mt_genes path is the file's directory's
+ let toml = "[sctransform]\nvars_to_regress = [\"percent.mt\", \"score\"]\nmt_genes = \"mt.txt\"\npercent_mt = true\n";
+ let p = build_in(None, Some(toml), Some(std::path::Path::new("/some/dir")), &[]).unwrap();
+ assert_eq!(p.sct.vars_to_regress, vec!["percent.mt", "score"]);
+ assert_eq!(p.mt_genes.as_deref(), Some("/some/dir/mt.txt"));
+ assert!(p.percent_mt);
+ let p = build_in(None, Some("[sctransform]\nvars_to_regress = []\n"), None, &[]).unwrap();
+ assert!(p.sct.vars_to_regress.is_empty());
+ }
}
diff --git a/crates/cluster/src/covariates.rs b/crates/cluster/src/covariates.rs
new file mode 100644
index 0000000..fd7fb43
--- /dev/null
+++ b/crates/cluster/src/covariates.rs
@@ -0,0 +1,281 @@
+//! The per-cell covariates of SCTransform's `vars.to.regress`, and the workflow's `percent.mt`
+//! (milestone M15b; docs/PLAN.md C3, "vars.to.regress and percent.mt").
+//!
+//! **percent.mt** is `PercentageFeatureSet()` ([`scio::Counts::percent_feature_set`]) of the
+//! mitochondrial features, which are either the workflow's ([`MtGenes::Pattern`]: `"(?i)^mt-"` on
+//! Seurat's row names, as every workflow script computes it before SCTransform) or the features
+//! whose id (the features file's column 1) a list names ([`MtGenes::Ids`], `--mt-genes`). Listed
+//! ids that no feature has are reported and skipped; a list that matches no feature is an error.
+//! A pattern that matches no feature gives zeros, with a warning, and is refused as a covariate
+//! (`--vars-to-regress percent.mt`), naming the remedy (`--mt-genes`).
+//!
+//! **The covariates** are named as Seurat names them (`vars.to.regress`): `percent.mt`,
+//! `nCount_RNA`, `nFeature_RNA` (the counts' own columns, as `CreateSeuratObject()` computes
+//! them), or a numeric column of `--metadata` ([`covariate_values`]). Seurat builds a formula from
+//! the names (`RegressOutMatrix`: `paste("GENE ~", paste(vars, collapse = "+"))`) and takes
+//! `ScaleData`'s rows named like a covariate as covariates too, so the port refuses what R would
+//! not regress as written: an unknown name, a repeated one, a name that is not syntactic in R
+//! (`make.names(x) != x`, reserved words included), `GENE` (the formula's response), and a name
+//! that is also a feature's. Values are read as R's `read.table()` reads them (`R_strtod`,
+//! [`rcompat::as_numeric`]), so the covariates are the bits R regresses; a value that is missing,
+//! not a number or not finite is an error (R drops the cell from `lm()`'s model frame, or stops,
+//! and `qr.resid()` then fails).
+//!
+//! The values reach the chain in memory ([`CellCovariates`]); the commands read the files.
+
+use crate::metadata::RnaMetadata;
+use scio::features::{id_rows, mt_pattern_rows, parse_id_list, MT_PATTERN};
+use scio::{Counts, Json};
+use std::collections::HashSet;
+
+/// The covariate `PercentageFeatureSet()` makes.
+pub const PERCENT_MT: &str = "percent.mt";
+
+/// The covariates the counts themselves give.
+pub const FROM_COUNTS: [&str; 3] = [PERCENT_MT, "nCount_RNA", "nFeature_RNA"];
+
+/// How many of the mitochondrial features `summary.json` lists by name, and how many of the ids
+/// not found.
+pub const FEATURES_LISTED: usize = 50;
+pub const NOT_FOUND_LISTED: usize = 10;
+
+/// Which features `percent.mt` counts.
+#[derive(Debug, Clone, PartialEq)]
+pub enum MtGenes {
+ /// The workflow's: Seurat's row names that match `"(?i)^mt-"`.
+ Pattern,
+ /// The features whose id (column 1 of `features.tsv`) is listed: `--mt-genes`' ids, in the
+ /// file's order (repeats included), with the file's path and SHA-256 for the record.
+ Ids { ids: Vec, file: String, sha256: String },
+}
+
+impl MtGenes {
+ /// `--mt-genes`' file: one id per line; blank lines and lines starting with `#` are skipped,
+ /// and each line's surrounding whitespace is ignored ([`scio::features::parse_id_list`]).
+ pub fn from_file_text(text: &str, file: &str, sha256: &str) -> MtGenes {
+ MtGenes::Ids { ids: parse_id_list(text), file: file.to_string(), sha256: sha256.to_string() }
+ }
+}
+
+/// `percent.mt`, with what defined it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PercentMt {
+ /// Per cell, in the counts' column order.
+ pub values: Vec,
+ pub definition: MtGenes,
+ /// The features counted (rows, 0-based, in the counts' order) and their Seurat names.
+ pub rows: Vec,
+ pub features: Vec,
+ /// With a list: the distinct ids listed, and those no feature has (in the list's order).
+ pub ids_listed: usize,
+ pub ids_not_found: Vec,
+}
+
+impl PercentMt {
+ /// `PercentageFeatureSet()` of the features `mt` selects. A list that selects none is an error.
+ pub fn compute(counts: &Counts, mt: &MtGenes) -> Result {
+ let feats = counts.features();
+ let (rows, ids_listed, ids_not_found) = match mt {
+ MtGenes::Pattern => (mt_pattern_rows(&feats), 0, Vec::new()),
+ MtGenes::Ids { ids, file, .. } => {
+ let distinct: HashSet<&str> = ids.iter().map(String::as_str).collect();
+ let (rows, missing) = id_rows(&feats, ids);
+ if rows.is_empty() {
+ return Err(format!(
+ "--mt-genes {file}: none of its {} id(s) is among the counts' features (column 1 of features.tsv){}",
+ distinct.len(),
+ if missing.is_empty() { String::new() } else { format!("; first: {}", missing.iter().take(NOT_FOUND_LISTED).cloned().collect::>().join(", ")) }
+ ));
+ }
+ (rows, distinct.len(), missing)
+ }
+ };
+ let names = counts.seurat_names();
+ let features = rows.iter().map(|&r| names[r].clone()).collect();
+ Ok(PercentMt { values: counts.percent_feature_set(&rows), definition: mt.clone(), rows, features, ids_listed, ids_not_found })
+ }
+
+ /// The warnings to print and record: ids not found, no feature matched, no counts at all.
+ pub fn notes(&self) -> Vec {
+ let mut v = Vec::new();
+ if let MtGenes::Ids { file, .. } = &self.definition {
+ if !self.ids_not_found.is_empty() {
+ v.push(format!(
+ "--mt-genes {file}: {} of its {} id(s) are not among the counts' features and are skipped (first: {})",
+ self.ids_not_found.len(),
+ self.ids_listed,
+ self.ids_not_found.iter().take(NOT_FOUND_LISTED).cloned().collect::>().join(", ")
+ ));
+ }
+ }
+ if self.rows.is_empty() {
+ v.push(format!("percent.mt: no feature's name matches \"{MT_PATTERN}\", so percent.mt is 0 in every cell; give the mitochondrial genes' ids with --mt-genes"));
+ } else if self.values.iter().all(|&x| x == 0.0) {
+ v.push(format!("percent.mt: the {} mitochondrial feature(s) have no counts, so percent.mt is 0 in every cell", self.rows.len()));
+ }
+ v
+ }
+
+ /// `summary.json`'s record (`result.sctransform.percent_mt`).
+ pub fn record_json(&self) -> Json {
+ let mut m: Vec<(&str, Json)> = Vec::new();
+ match &self.definition {
+ MtGenes::Pattern => {
+ m.push(("definition", Json::Str("pattern".into())));
+ m.push(("pattern", Json::Str(MT_PATTERN.into())));
+ m.push(("matched_on", Json::Str("Seurat's row names: features.tsv's column 2, made unique (Read10X), with _ and | replaced by - (CreateSeuratObject)".into())));
+ }
+ MtGenes::Ids { file, sha256, .. } => {
+ m.push(("definition", Json::Str("ids".into())));
+ m.push(("file", Json::Str(file.clone())));
+ m.push(("sha256", Json::Str(sha256.clone())));
+ m.push(("matched_on", Json::Str("features.tsv's column 1".into())));
+ m.push(("ids_listed", Json::Int(self.ids_listed as i64)));
+ m.push(("ids_not_found", Json::Int(self.ids_not_found.len() as i64)));
+ m.push(("ids_not_found_first", Json::strs(&self.ids_not_found.iter().take(NOT_FOUND_LISTED).cloned().collect::>())));
+ }
+ }
+ m.push(("n_features", Json::Int(self.rows.len() as i64)));
+ m.push(("features_first", Json::strs(&self.features.iter().take(FEATURES_LISTED).cloned().collect::>())));
+ m.push(("cells_zero", Json::Int(self.values.iter().filter(|&&x| x == 0.0).count() as i64)));
+ m.push(("cells_nan", Json::Int(self.values.iter().filter(|x| x.is_nan()).count() as i64)));
+ Json::obj(m)
+ }
+}
+
+/// What the chain needs besides the counts and the parameters to compute `percent.mt` and the
+/// covariates, handed over in memory (docs/PLAN.md A3): the list `--mt-genes` gives (the pattern
+/// when there is none), and `--metadata`'s columns for the cells, as text.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct CellCovariates {
+ pub mt_genes: Option,
+ /// The columns' names and, per column, each cell's text (`NA` where the table has no row
+ /// for a cell), in the counts' column order ([`crate::metadata::extra_columns`]).
+ pub metadata: Option<(Vec, Vec>)>,
+}
+
+/// R's reserved words (`?Reserved`), which `make.names()` does not leave as they are.
+const RESERVED: [&str; 19] = [
+ "if", "else", "repeat", "while", "function", "for", "in", "next", "break", "TRUE", "FALSE", "NULL", "Inf", "NaN", "NA", "NA_integer_", "NA_real_", "NA_character_", "NA_complex_",
+];
+
+/// Whether `make.names(name) == name` in R, for ASCII names: letters, digits, `.` and `_`, starting
+/// with a letter or with a `.` not followed by a digit, and not a reserved word (`...` and `..1`,
+/// `..2`, ... included). Names with other characters are treated as not syntactic.
+pub fn is_syntactic(name: &str) -> bool {
+ let b = name.as_bytes();
+ if b.is_empty() || !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'.' || *c == b'_') {
+ return false;
+ }
+ let starts = b[0].is_ascii_alphabetic() || (b[0] == b'.' && !b.get(1).is_some_and(|c| c.is_ascii_digit()));
+ let dots = name == "..." || (name.starts_with("..") && name.len() > 2 && name[2..].bytes().all(|c| c.is_ascii_digit()));
+ starts && !dots && !RESERVED.contains(&name)
+}
+
+/// Checks `vars.to.regress`' names before any data is read: each is syntactic in R, none is
+/// `GENE`, none repeats.
+pub fn check_names(vars: &[String]) -> Result<(), String> {
+ let mut seen = HashSet::new();
+ for v in vars {
+ if !seen.insert(v.as_str()) {
+ return Err(format!("vars.to.regress: '{v}' is given twice"));
+ }
+ if v == "GENE" {
+ return Err("vars.to.regress: 'GENE' is the response Seurat's RegressOutMatrix names in its formula (GENE ~ ...); rename the column".into());
+ }
+ if !is_syntactic(v) {
+ return Err(format!("vars.to.regress: '{v}' is not a syntactic name in R (letters, digits, . and _, starting with a letter or a . not followed by a digit; not a reserved word): Seurat builds the formula GENE ~ {v} from it, which would not regress the column as named; rename the column"));
+ }
+ }
+ Ok(())
+}
+
+/// The covariates' values, in `vars`' order (the formula's): `percent.mt`, `nCount_RNA` and
+/// `nFeature_RNA` from `rna` (`percent.mt` must have been computed), any other name from
+/// `metadata`'s column of that name, read as R reads numbers. `feature_names` are Seurat's row
+/// names, which no covariate may share.
+pub fn covariate_values(vars: &[String], rna: &RnaMetadata, metadata: Option<&(Vec, Vec>)>, feature_names: &[String]) -> Result>, String> {
+ check_names(vars)?;
+ let features: HashSet<&str> = feature_names.iter().map(String::as_str).collect();
+ let n = rna.n_count.len();
+ let mut out = Vec::with_capacity(vars.len());
+ for v in vars {
+ if features.contains(v.as_str()) {
+ return Err(format!("vars.to.regress: '{v}' is also a feature's name; Seurat's ScaleData would add that feature's residuals as a covariate too; rename the column"));
+ }
+ let vals: Vec = match v.as_str() {
+ PERCENT_MT => rna.percent_mt.clone().ok_or("vars.to.regress: percent.mt was not computed")?,
+ "nCount_RNA" => rna.n_count.clone(),
+ "nFeature_RNA" => rna.n_feature.iter().map(|&x| x as f64).collect(),
+ name => {
+ let Some((names, cols)) = metadata else {
+ return Err(format!("vars.to.regress: '{name}' is not percent.mt, nCount_RNA or nFeature_RNA, and no --metadata table is given"));
+ };
+ let Some(k) = names.iter().position(|c| c == name) else {
+ return Err(format!("vars.to.regress: '{name}' is not percent.mt, nCount_RNA, nFeature_RNA or a column of --metadata (its columns: {})", names.join(", ")));
+ };
+ let mut vals = Vec::with_capacity(n);
+ for (i, t) in cols[k].iter().enumerate() {
+ let x = rcompat::as_numeric(t);
+ if rcompat::is_na(x) || x.is_nan() {
+ return Err(format!("vars.to.regress: --metadata column '{name}' has no number for cell {} ('{t}'): a missing or non-numeric value", i + 1));
+ }
+ vals.push(x);
+ }
+ vals
+ }
+ };
+ if let Some(i) = vals.iter().position(|x| !x.is_finite()) {
+ return Err(format!("vars.to.regress: '{v}' is not finite in cell {} ({}); R's lm() stops on NA/NaN/Inf", i + 1, scio::fmt17(vals[i])));
+ }
+ if vals.len() != n {
+ return Err(format!("vars.to.regress: '{v}' has {} values for {n} cells", vals.len()));
+ }
+ out.push(vals);
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn syntactic_names_as_make_names() {
+ for ok in ["percent.mt", "nCount_RNA", "x", ".x", "a1", "a_b.c", "T", "F", "pi", ".a.2", "..a"] {
+ assert!(is_syntactic(ok), "{ok}");
+ }
+ for bad in ["", "1x", ".2way", "my-col", "a b", "TRUE", "NULL", "if", "in", "...", "..1", "..12", "_x", "é", "a+b"] {
+ assert!(!is_syntactic(bad), "{bad}");
+ }
+ }
+
+ #[test]
+ fn names_and_values() {
+ let rna = RnaMetadata { n_count: vec![10.0, 20.0, 30.0], n_feature: vec![1, 2, 3], percent_mt: Some(vec![0.5, 1.5, 0.0]) };
+ let md = (vec!["score".to_string(), "text".to_string(), "gappy".to_string()], vec![
+ vec!["0.1".into(), "1e-3".into(), " 2 ".into()],
+ vec!["a".into(), "b".into(), "c".into()],
+ vec!["1".into(), "NA".into(), "3".into()],
+ ]);
+ let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>();
+ let got = covariate_values(&v(&["percent.mt", "nFeature_RNA", "score"]), &rna, Some(&md), &v(&["Gapdh"])).unwrap();
+ assert_eq!(got[0], vec![0.5, 1.5, 0.0]);
+ assert_eq!(got[1], vec![1.0, 2.0, 3.0]);
+ assert_eq!(got[2].iter().map(|x| x.to_bits()).collect::>(), [rcompat::as_numeric("0.1"), rcompat::as_numeric("1e-3"), 2.0].iter().map(|x| x.to_bits()).collect::>());
+ let err = |vars: &[&str], needle: &str| {
+ let e = covariate_values(&v(vars), &rna, Some(&md), &v(&["Gapdh"])).unwrap_err();
+ assert!(e.contains(needle), "{vars:?}: {e}");
+ };
+ err(&["text"], "non-numeric");
+ err(&["gappy"], "missing");
+ err(&["nope"], "not percent.mt");
+ err(&["score", "score"], "twice");
+ err(&["GENE"], "response");
+ err(&["Gapdh"], "feature");
+ let mut no_pm = rna.clone();
+ no_pm.percent_mt = None;
+ assert!(covariate_values(&v(&["percent.mt"]), &no_pm, None, &[]).is_err());
+ assert!(covariate_values(&v(&["score"]), &rna, None, &[]).unwrap_err().contains("no --metadata"));
+ }
+}
diff --git a/crates/cluster/src/lib.rs b/crates/cluster/src/lib.rs
index 783b9de..646d5a8 100644
--- a/crates/cluster/src/lib.rs
+++ b/crates/cluster/src/lib.rs
@@ -7,7 +7,8 @@
//! SCTransform, the workflow's PCA guard, RunPCA, FindNeighbors, FindClusters, the silhouette
//! widths and the purities, through the `sctransform`, `pca`, `neighbors` and `knn` crates), with
//! its parameters ([`chain_params`]), its outputs ([`chain_output`]) and its comparison with R
-//! ([`validate`], kernel-gated).
+//! ([`validate`], kernel-gated); SCTransform's `vars.to.regress` and the workflow's `percent.mt`
+//! ([`covariates`], milestone M15b).
//!
//! FindClusters, as `FindClusters(obj, random.seed = 12345)` runs it on the `SCT_snn` graph with
//! its defaults (modularity function 1, resolution 0.8, algorithm 1, 10 starts, 10 iterations):
@@ -32,6 +33,7 @@ pub mod chain;
pub mod chain_output;
pub mod chain_params;
pub mod clustering;
+pub mod covariates;
pub mod find_clusters;
pub mod input;
pub mod java_random;
@@ -51,7 +53,8 @@ pub use find_clusters::{find_clusters, ClusterError, Factor, FindClusters, Resol
pub use java_random::JavaRandom;
pub use network::Network;
pub use optimizer::{OptimizerParams, OptimizerResult};
-pub use chain::{cluster_counts, Chain, ChainError, Clustered, Observer};
+pub use chain::{cluster_counts, cluster_counts_with, Chain, ChainError, Clustered, Observer};
+pub use covariates::{CellCovariates, MtGenes, PercentMt};
pub use chain_params::{ChainParams, Stats};
pub use params::{parse_resolutions, ClusterParams};
pub use silhouette::{approx_silhouette, Silhouette};
diff --git a/crates/cluster/src/metadata.rs b/crates/cluster/src/metadata.rs
index 474805e..15209bb 100644
--- a/crates/cluster/src/metadata.rs
+++ b/crates/cluster/src/metadata.rs
@@ -5,7 +5,8 @@
//! `.CalcN.default`): `nCount_RNA = Matrix::colSums(counts)`, which sums each column's stored
//! values in stored order in double (Matrix 1.7-6's `Csparse_colsum`), and
//! `nFeature_RNA = Matrix::colSums(counts > 0)`, the stored values above 0 (explicit zeros do
-//! not count);
+//! not count); and, when asked for (milestone M15b), `percent.mt`, as the workflow's scripts
+//! compute it with `PercentageFeatureSet()` before SCTransform ([`crate::covariates`]);
//! - **the columns of `--metadata`**, carried over by barcode.
//!
//! The staged route needs the counts' columns too, without the counts: `scrust sctransform`
@@ -20,11 +21,13 @@ use std::path::Path;
/// The file the counts' columns go to in a stage's output directory.
pub const FILE: &str = "cell_metadata.tsv";
-/// `nCount_RNA` and `nFeature_RNA` of every cell, in the counts' column order.
+/// `nCount_RNA` and `nFeature_RNA` of every cell, in the counts' column order, and `percent.mt`
+/// when it was asked for (M15b).
#[derive(Debug, Clone, PartialEq)]
pub struct RnaMetadata {
pub n_count: Vec,
pub n_feature: Vec,
+ pub percent_mt: Option>,
}
impl RnaMetadata {
@@ -41,7 +44,7 @@ impl RnaMetadata {
n_count.push(s);
n_feature.push(x.iter().filter(|&&v| v > 0.0).count() as i64);
}
- RnaMetadata { n_count, n_feature }
+ RnaMetadata { n_count, n_feature, percent_mt: None }
}
/// The column texts as R's reference scripts write them (doubles with 17 significant digits,
@@ -50,35 +53,59 @@ impl RnaMetadata {
(self.n_count.iter().map(|&v| fmt17(v)).collect(), self.n_feature.iter().map(|v| v.to_string()).collect())
}
- /// Writes [`FILE`]'s layout: `barcode`, `nCount_RNA`, `nFeature_RNA`.
+ /// `percent.mt`'s texts (17 significant digits, `NaN` for a cell with no counts), when computed.
+ pub fn percent_mt_texts(&self) -> Option> {
+ self.percent_mt.as_ref().map(|v| v.iter().map(|&x| fmt17(x)).collect())
+ }
+
+ /// The columns [`FILE`] holds: 3 (`barcode`, `nCount_RNA`, `nFeature_RNA`), or 4 with `percent.mt`.
+ pub fn n_columns(&self) -> usize {
+ if self.percent_mt.is_some() {
+ 4
+ } else {
+ 3
+ }
+ }
+
+ /// Writes [`FILE`]'s layout: `barcode`, `nCount_RNA`, `nFeature_RNA`, and `percent.mt` when
+ /// computed.
pub fn write(&self, path: &Path, barcodes: &[String]) -> io::Result<()> {
assert_eq!(barcodes.len(), self.n_count.len());
let (a, b) = self.texts();
- let mut s = String::from("barcode\tnCount_RNA\tnFeature_RNA\n");
+ let pm = self.percent_mt_texts();
+ let mut s = String::from(if pm.is_some() { "barcode\tnCount_RNA\tnFeature_RNA\tpercent.mt\n" } else { "barcode\tnCount_RNA\tnFeature_RNA\n" });
for (i, bc) in barcodes.iter().enumerate() {
s.push_str(bc);
s.push('\t');
s.push_str(&a[i]);
s.push('\t');
s.push_str(&b[i]);
+ if let Some(p) = &pm {
+ s.push('\t');
+ s.push_str(&p[i]);
+ }
s.push('\n');
}
std::fs::write(path, s).map_err(|e| io::Error::new(e.kind(), format!("{}: {e}", path.display())))
}
- /// Reads [`FILE`]'s layout: the barcodes and the columns.
+ /// Reads [`FILE`]'s layout: the barcodes and the columns (`percent.mt` when the file has it).
pub fn read(path: &Path) -> Result<(Vec, RnaMetadata), String> {
let t = Table::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
- if t.header != ["barcode", "nCount_RNA", "nFeature_RNA"] {
- return Err(format!("{}: expected the columns barcode, nCount_RNA, nFeature_RNA", path.display()));
+ let with_pm = t.header == ["barcode", "nCount_RNA", "nFeature_RNA", "percent.mt"];
+ if !with_pm && t.header != ["barcode", "nCount_RNA", "nFeature_RNA"] {
+ return Err(format!("{}: expected the columns barcode, nCount_RNA, nFeature_RNA (and percent.mt)", path.display()));
}
let mut barcodes = Vec::with_capacity(t.rows.len());
- let mut m = RnaMetadata { n_count: Vec::with_capacity(t.rows.len()), n_feature: Vec::with_capacity(t.rows.len()) };
+ let mut m = RnaMetadata { n_count: Vec::with_capacity(t.rows.len()), n_feature: Vec::with_capacity(t.rows.len()), percent_mt: with_pm.then(|| Vec::with_capacity(t.rows.len())) };
for (i, r) in t.rows.iter().enumerate() {
let bad = || format!("{}: row {}", path.display(), i + 1);
barcodes.push(r[0].clone());
m.n_count.push(scio::parse17(r.get(1).ok_or_else(bad)?).ok_or_else(bad)?);
m.n_feature.push(r.get(2).ok_or_else(bad)?.parse().map_err(|_| bad())?);
+ if let Some(p) = m.percent_mt.as_mut() {
+ p.push(scio::parse17(r.get(3).ok_or_else(bad)?).ok_or_else(bad)?);
+ }
}
Ok((barcodes, m))
}
diff --git a/crates/cluster/src/validate.rs b/crates/cluster/src/validate.rs
index e6db923..40c1d9a 100644
--- a/crates/cluster/src/validate.rs
+++ b/crates/cluster/src/validate.rs
@@ -42,6 +42,14 @@
//! attributes and the counts, against R's corrected counts, log1p data, `nCount_SCT`,
//! `nFeature_SCT` and K10 scalars. Its `mu` is a BLAS product, so it is graded under the
//! validator's own kernel against R's;
+//! - **vars.to.regress and percent.mt** (M15b), when the runs have them: `metadata.tsv`'s
+//! `percent.mt` (as text: computed from the counts, BLAS-free), every other column both
+//! `metadata.tsv` files hold that the chain does not write (a regressed `--metadata` column: R
+//! wrote the double `read.delim()` parsed, `%.17g`; the candidate carries the table's text, which
+//! is parsed again as R parses it, `rcompat::as_numeric`, and compared bit for bit), and the
+//! `result` records: the regression's covariates, the rank and pivot of `lm()`'s QR (R's
+//! `result.regression` against `result.sctransform.regression`), and percent.mt's features (R's
+//! `result.covariates.percent_mt.features` against the candidate's count and its first names);
//! - **the manifest** (M13): the candidate's `summary.json` `files` section describes its
//! directory: every file listed, every listed file present with its size and SHA-256, the
//! naming rules that keep normalised data from being read as raw counts;
@@ -65,7 +73,12 @@
//! SNN graph, none. When both runs recorded the same OpenBLAS kernel, every check is exact.
//! Otherwise ([`Mode::Tolerance`]) BLAS-dependent checks are graded against
//! `[clustering.floor.kernel]` (`validation/tolerances.toml`, embedded at build time), and the
-//! report says so.
+//! report says so. When both runs regressed the same covariates out of `scale.data`
+//! (SCTransform's `vars.to.regress`, M15b: R's `result.regression.vars`, the candidate's
+//! `run.parameters.sctransform.vars_to_regress`), they are graded against
+//! `[clustering.floor.kernel_regressed]` instead, R's own differences across kernels measured
+//! with the regression ([`floor_for`]); every other comparison, the saved object's included, keeps
+//! `[clustering.floor.kernel]`.
use crate::find_clusters::Factor;
use crate::purity::neighbor_purity;
@@ -83,6 +96,42 @@ pub fn floor() -> Floor {
Floor::from_toml(TOLERANCES, "clustering.floor.kernel").expect("validation/tolerances.toml has [clustering.floor.kernel]")
}
+/// The floor of runs that regressed covariates out of `scale.data` (SCTransform's
+/// `vars.to.regress`, M15b): R against R across kernels with the regression, on M15b's cases. Used
+/// only by [`floor_for`]; it stands alone: an array it does not list is identical across kernels,
+/// so exact.
+pub fn floor_regressed() -> Floor {
+ Floor::from_toml(TOLERANCES, "clustering.floor.kernel_regressed").expect("validation/tolerances.toml has [clustering.floor.kernel_regressed]")
+}
+
+/// The covariates a run regressed out of `scale.data`, as its `summary.json` records them: R's
+/// reference runs in `result.regression.vars`, scrust's in `run.parameters.sctransform.
+/// vars_to_regress` (and `result.sctransform.regression.vars_to_regress`); none when it did not.
+pub fn regressed(summary: Option<&Json>) -> Vec {
+ let Some(s) = summary else { return Vec::new() };
+ let r = s.get("result");
+ let mut v = str_list(r.and_then(|r| r.get("regression")).and_then(|g| g.get("vars")));
+ if v.is_empty() {
+ v = str_list(s.get("run").and_then(|r| r.get("parameters")).and_then(|p| p.get("sctransform")).and_then(|p| p.get("vars_to_regress")));
+ }
+ if v.is_empty() {
+ v = str_list(r.and_then(|r| r.get("sctransform")).and_then(|t| t.get("regression")).and_then(|g| g.get("vars_to_regress")));
+ }
+ v
+}
+
+/// The floor a comparison is graded against: `[clustering.floor.kernel_regressed]` when both runs
+/// record the same non-empty `vars.to.regress`, otherwise `[clustering.floor.kernel]`, as before
+/// M15b. Returns the covariates when the regressed floor applies.
+pub fn floor_for(reference: Option<&Json>, candidate: &Json) -> (Floor, Option>) {
+ let (r, c) = (regressed(reference), regressed(Some(candidate)));
+ if !c.is_empty() && r == c {
+ (floor_regressed(), Some(c))
+ } else {
+ (floor(), None)
+ }
+}
+
/// The outcome of one check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
@@ -132,6 +181,9 @@ pub struct Report {
pub reference: PathBuf,
pub candidate: PathBuf,
pub mode: Mode,
+ /// The floor tolerance mode grades against (`clustering.floor.kernel`, or
+ /// `clustering.floor.kernel_regressed` when both runs regressed the same covariates).
+ pub floor: String,
/// The mode of the checks against the saved object, under its own kernel.
pub saved_mode: Option,
pub checks: Vec,
@@ -175,6 +227,7 @@ impl Report {
("candidate", Json::Str(self.candidate.display().to_string())),
("pass", Json::Bool(self.pass())),
("grading", mode(&self.mode)),
+ ("floor", Json::Str(self.floor.clone())),
("saved_grading", self.saved_mode.as_ref().map(mode).unwrap_or(Json::Null)),
(
"by_stage",
@@ -517,14 +570,21 @@ pub fn compare(reference: &Path, candidate: &Path, opts: &CompareOptions) -> Res
let c_params = c_params_all.get("cluster").cloned().unwrap_or(c_params_all.clone());
let start = c_run.get("start").and_then(Json::as_str).unwrap_or("snn").to_string();
let mode = grade::mode(grade::recorded_kernel(r_summary.as_ref()).as_deref(), grade::recorded_kernel(Some(&c_summary)).as_deref());
- let mut g = Grader { mode, floor: floor(), start, checks: Vec::new() };
+ let (floor, regressed_vars) = floor_for(r_summary.as_ref(), &c_summary);
+ let floor_name = floor.source.clone();
+ let mut g = Grader { mode, floor, start, checks: Vec::new() };
- // the environment: which mode, and why
+ // the environment: which mode, and why; and the floor
{
let rk = grade::recorded_kernel(r_summary.as_ref()).unwrap_or_else(|| "none recorded".into());
let ck = grade::recorded_kernel(Some(&c_summary)).unwrap_or_else(|| "none recorded".into());
let detail = format!("R {rk}, Rust {ck}; {} mode: {}", g.mode.name(), g.mode.reason());
g.push("environment", "OpenBLAS kernel", Class::BlasFree, "-".into(), Status::NotApplicable, 1, 0, detail);
+ let detail = match ®ressed_vars {
+ Some(v) => format!("[{floor_name}]: both runs regressed {} out of scale.data (vars.to.regress); used only in tolerance mode", v.join(",")),
+ None => format!("[{floor_name}]: used only in tolerance mode"),
+ };
+ g.push("environment", "the floor", Class::BlasFree, "-".into(), Status::NotApplicable, 1, 0, detail);
}
// settings
@@ -560,7 +620,7 @@ pub fn compare(reference: &Path, candidate: &Path, opts: &CompareOptions) -> Res
teacher_forced_purity(&mut g, reference, &r_meta, r_scalars.as_ref())?;
teacher_forced_correct(&mut g, reference, candidate, opts.counts.as_deref(), &r_summary, &r_meta, r_scalars.as_ref())?;
manifest_check(&mut g, candidate, &c_summary);
- Ok(Report { reference: reference.to_path_buf(), candidate: candidate.to_path_buf(), mode: g.mode, saved_mode, checks: g.checks })
+ Ok(Report { reference: reference.to_path_buf(), candidate: candidate.to_path_buf(), mode: g.mode, floor: floor_name, saved_mode, checks: g.checks })
}
/// K7 (M10): FindClusters, resolution by resolution, and the workflow's files.
@@ -1133,6 +1193,40 @@ fn compare_files(g: &mut Grader, reference: &Path, candidate: &Path, r_summary:
_ => {}
}
}
+ // M15b: percent.mt (from the counts, BLAS-free), and the other columns both hold that the
+ // chain does not write: a regressed --metadata column, which R wrote as the double read.delim()
+ // parsed (%.17g) and the candidate carries as the table's text, parsed again as R parses it
+ match (r_meta.col("percent.mt"), c_meta.col("percent.mt")) {
+ (Some(a), Some(b)) if same_n => {
+ let nd = (0..n).filter(|&i| r_meta.rows[i].get(a) != c_meta.rows[i].get(b)).count();
+ g.exact("M15b", "metadata.tsv: percent.mt", Inputs::Free, n, nd, "as text".into());
+ }
+ (Some(_), None) => g.missing("M15b", "metadata.tsv: percent.mt", Inputs::Free, "not in the candidate's metadata.tsv".into()),
+ (None, Some(_)) => g.not_applicable("M15b", "metadata.tsv: percent.mt", Inputs::Free, "R's run has no percent.mt".into()),
+ _ => {}
+ }
+ const CHAIN_COLUMNS: [&str; 14] = ["barcode", "nCount_RNA", "nFeature_RNA", "percent.mt", "nCount_SCT", "nFeature_SCT", "seurat_clusters", "silhouette_width", "silhouette_other", "neighborhood_purity", "purity_maximum", "orig.ident", "ident", "label"];
+ for (j, col) in r_meta.header.iter().enumerate() {
+ if CHAIN_COLUMNS.contains(&col.as_str()) || col.contains("_res.") {
+ continue;
+ }
+ match c_meta.col(col) {
+ Some(b) if same_n => {
+ let nd = (0..n)
+ .filter(|&i| {
+ let rv = r_meta.rows[i].get(j).and_then(|v| scio::parse17(v));
+ let cv = c_meta.rows[i].get(b).map(|v| rcompat::as_numeric(v));
+ match (rv, cv) {
+ (Some(x), Some(y)) => x.to_bits() != y.to_bits(),
+ _ => true,
+ }
+ })
+ .count();
+ g.exact("M15b", &format!("metadata.tsv: {col} (R's read.delim() double = R_strtod of the candidate's text)"), Inputs::Free, n, nd, "bit for bit".into());
+ }
+ _ => g.missing("M15b", &format!("metadata.tsv: {col}"), Inputs::Free, "a column of R's metadata.tsv the candidate does not carry".into()),
+ }
+ }
match (r_meta.col("silhouette_width"), c_meta.col("silhouette_width")) {
(Some(a), Some(b)) if same_n => {
let s = grade::stats(&meta_numbers(r_meta, a), &meta_numbers(c_meta, b), n, 1, false);
@@ -1328,6 +1422,48 @@ fn compare_files(g: &mut Grader, reference: &Path, candidate: &Path, r_summary:
None => g.not_applicable("K1", "result: scale_data_sha256", Inputs::Sct, "the candidate did not run SCTransform".into()),
}
}
+ // M15b: the regression and percent.mt's features, when R's run records them
+ if let Some(rg) = rr.get("regression") {
+ let c_rg = c_sct.and_then(|s| s.get("regression"));
+ let text = |j: Option<&Json>, key: &str| str_list(j.and_then(|x| x.get(key))).join(",");
+ let ints = |j: Option<&Json>, key: &str| num_list(j.and_then(|x| x.get(key))).iter().map(|v| (*v as i64).to_string()).collect::>().join(",");
+ for (key, a, b, inputs) in [
+ ("vars_to_regress", text(Some(rg), "vars"), text(c_rg, "vars_to_regress"), Inputs::Free),
+ ("columns", ints(Some(rg), "n_columns"), ints(c_rg, "n_columns"), Inputs::Free),
+ ("rank", ints(Some(rg), "rank"), ints(c_rg, "rank"), Inputs::Sct),
+ ("pivot", ints(Some(rg), "pivot"), ints(c_rg, "pivot"), Inputs::Sct),
+ ] {
+ if c_rg.is_none() {
+ g.missing("M15b", &format!("result: regression {key}"), inputs, "the candidate did not regress".into());
+ } else {
+ g.exact("M15b", &format!("result: regression {key}"), inputs, 1, (a != b) as usize, if a == b { a } else { format!("R {a}, Rust {b}") });
+ }
+ }
+ }
+ if let Some(pm) = rr.get("covariates").and_then(|c| c.get("percent_mt")) {
+ let c_pm = c_sct.and_then(|s| s.get("percent_mt"));
+ let r_feats = str_list(pm.get("features"));
+ let defs = (pm.get("definition").and_then(Json::as_str), c_pm.and_then(|c| c.get("definition")).and_then(Json::as_str));
+ match c_pm {
+ // R's pattern and the candidate's list of ids (a case that gives R's all-zero
+ // column through features without counts): the values are compared, not the
+ // features
+ Some(_) if defs.0 != defs.1 => g.not_applicable(
+ "M15b",
+ "result: percent.mt's features",
+ Inputs::Free,
+ format!("R's definition is {}, the candidate's {} ({} feature(s) in R's run): metadata.tsv's percent.mt is compared", defs.0.unwrap_or("?"), defs.1.unwrap_or("?"), r_feats.len()),
+ ),
+ Some(cp) => {
+ let c_n = jnum(cp, "n_features").map(|v| v as usize);
+ let c_first = str_list(cp.get("features_first"));
+ let want_first: Vec = r_feats.iter().take(crate::covariates::FEATURES_LISTED).cloned().collect();
+ let ok = c_n == Some(r_feats.len()) && c_first == want_first;
+ g.exact("M15b", "result: percent.mt's features", Inputs::Free, 1, (!ok) as usize, format!("{} feature(s){}", r_feats.len(), if ok { String::new() } else { format!("; Rust {c_n:?}: {}", c_first.join(",")) }));
+ }
+ None => g.missing("M15b", "result: percent.mt's features", Inputs::Free, "the candidate did not compute percent.mt".into()),
+ }
+ }
let rng_after = rr.get("rng_after");
for (key, label, inputs) in [("SCTransform", "K1", Inputs::Free), ("RunPCA", "K2", Inputs::Pca)] {
let a = rng_after.and_then(|x| x.get(key)).and_then(Json::as_str);
@@ -1339,6 +1475,34 @@ fn compare_files(g: &mut Grader, reference: &Path, candidate: &Path, r_summary:
}
}
}
+ // M15b: scale.data value by value, when R kept it (sct/scale_data.npy, levels full and
+ // standard) and the candidate did (--keep-stages, --export): the rows matched by name (R's in
+ // the assay's gene order, the candidate's in VariableFeatures() order). A digest cannot be
+ // graded across kernels; the values can, against the floor's S2d_scale_data.
+ let (r_sd, c_sd) = (reference.join("sct/scale_data.npy"), candidate.join("sct/scale_data.npy"));
+ if r_sd.is_file() && c_sd.is_file() {
+ let r_names: Vec = read_text(&reference.join("sct/scale_data_features.tsv")).unwrap_or_default().lines().map(String::from).collect();
+ let c_names: Vec = read_table(&candidate.join("sct/variable_features.tsv")).map(|t| t.rows.iter().map(|r| r.get(1).cloned().unwrap_or_default()).collect()).unwrap_or_default();
+ let (r, rn, rc) = scio::npy::read_f64_row_major(&r_sd).map_err(|e| e.to_string())?;
+ let (c, cn, cc) = scio::npy::read_f64_row_major(&c_sd).map_err(|e| e.to_string())?;
+ let pos: std::collections::HashMap<&str, usize> = c_names.iter().enumerate().map(|(i, x)| (x.as_str(), i)).collect();
+ let rows: Option> = r_names.iter().map(|x| pos.get(x.as_str()).copied()).collect();
+ match rows {
+ Some(rows) if rn == r_names.len() && cn == c_names.len() && rn == cn && rc == cc => {
+ // column-major features x cells, R's row order
+ let (mut a, mut b) = (vec![0.0f64; rn * rc], vec![0.0f64; rn * rc]);
+ for (i, &k) in rows.iter().enumerate() {
+ for j in 0..rc {
+ a[i + j * rn] = r[i * rc + j];
+ b[i + j * rn] = c[k * cc + j];
+ }
+ }
+ let st = grade::stats(&a, &b, rn, rc, false);
+ g.numeric("K1", "sct/scale_data.npy (value by value, rows matched by name)", Inputs::Sct, "S2d_scale_data", &st, "");
+ }
+ _ => g.missing("K1", "sct/scale_data.npy (value by value)", Inputs::Sct, format!("R's {rn} x {rc} and the candidate's {cn} x {cc} rows do not match by name")),
+ }
+ }
Ok(())
}
@@ -1370,10 +1534,13 @@ fn compare_saved(g: &mut Grader, saved: &Path, saved_kernel: &str, c_summary: &J
match (s_meta.col("silhouette_width"), c_meta.col("silhouette_width")) {
(Some(a), Some(b)) if same_n => {
let s = grade::stats(&meta_numbers(&s_meta, a), &meta_numbers(c_meta, b), n, 1, false);
- // graded under the saved object's kernel
+ // graded under the saved object's kernel, against [clustering.floor.kernel]: the
+ // workflow's saved objects did not regress
let keep = std::mem::replace(&mut g.mode, mode.clone());
+ let keep_floor = std::mem::replace(&mut g.floor, floor());
g.numeric("saved", "silhouette_width", Inputs::Pca, "K8_silhouette_width", &s, &format!("saved under {saved_kernel}"));
g.mode = keep;
+ g.floor = keep_floor;
}
(Some(_), _) => g.not_applicable("saved", "silhouette_width", Inputs::Pca, "the candidate did not compute silhouette widths".into()),
_ => {}
@@ -1382,8 +1549,10 @@ fn compare_saved(g: &mut Grader, saved: &Path, saved_kernel: &str, c_summary: &J
(Some(a), Some(b)) if same_n => {
let s = grade::stats(&meta_numbers(&s_meta, a), &meta_numbers(c_meta, b), n, 1, false);
let keep = std::mem::replace(&mut g.mode, mode.clone());
+ let keep_floor = std::mem::replace(&mut g.floor, floor());
g.numeric("saved", "neighborhood_purity", Inputs::Pca, "K9_purity", &s, &format!("saved under {saved_kernel}"));
g.mode = keep;
+ g.floor = keep_floor;
}
(Some(_), _) => g.not_applicable("saved", "neighborhood_purity", Inputs::Pca, "the candidate did not compute purities".into()),
_ => {}
diff --git a/crates/cluster/tests/m15b_covariates.rs b/crates/cluster/tests/m15b_covariates.rs
new file mode 100644
index 0000000..0878ce3
--- /dev/null
+++ b/crates/cluster/tests/m15b_covariates.rs
@@ -0,0 +1,90 @@
+//! Milestone M15b: `percent.mt` against Seurat 5.5.1 (validation/R/regress_vectors.R; fixtures in
+//! tests/fixtures/clustering/percent_mt/): a 10x directory with tricky feature names (case,
+//! underscores and pipes Seurat turns into dashes, names Read10X makes unique, a mitochondrial
+//! feature without counts, a cell without mitochondrial counts), with integer counts and with
+//! non-integer ones, and R's results:
+//!
+//! - Seurat's row names (`Read10X()`'s `make.unique()`, then `CreateSeuratObject()`'s `_` and `|`
+//! to `-`), and `make.unique()` on its own (`make_unique.tsv`);
+//! - `PercentageFeatureSet(obj, pattern = "(?i)^mt-")`: the features matched and the values, bit
+//! for bit;
+//! - `PercentageFeatureSet(obj, features = )`, the list
+//! read as `--mt-genes` reads it (blank lines, comments, an id twice, ids not found);
+//! - `nCount_RNA`, `PercentageFeatureSet()`'s denominator.
+//!
+//! No BLAS is involved: the checks are exact on any machine.
+
+use cluster::covariates::{MtGenes, PercentMt};
+use scio::features::make_unique;
+use std::path::PathBuf;
+
+fn dir() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/clustering/percent_mt")
+}
+
+fn hexl(s: &str) -> Vec {
+ s.split(',').map(|h| f64::from_bits(u64::from_str_radix(h, 16).unwrap())).collect()
+}
+
+fn list(s: &str) -> Vec {
+ if s == "-" {
+ Vec::new()
+ } else {
+ s.split(',').map(str::to_owned).collect()
+ }
+}
+
+fn bits(v: &[f64]) -> Vec {
+ v.iter().map(|x| x.to_bits()).collect()
+}
+
+#[test]
+fn make_unique_as_r() {
+ let text = std::fs::read_to_string(dir().join("make_unique.tsv")).unwrap();
+ let mut n = 0;
+ for l in text.lines().filter(|l| !l.starts_with('#')) {
+ let f: Vec<&str> = l.split('\t').collect();
+ assert_eq!(make_unique(&list(f[0])), list(f[1]), "make.unique({})", f[0]);
+ n += 1;
+ }
+ assert_eq!(n, 5);
+}
+
+#[test]
+fn percent_mt_as_seurat_computes_it() {
+ let expected = std::fs::read_to_string(dir().join("expected.tsv")).unwrap();
+ let rows: Vec> = expected.lines().filter(|l| !l.starts_with('#')).map(|l| l.split('\t').collect()).collect();
+ assert_eq!(rows.len(), 6);
+ let want_names: Vec = std::fs::read_to_string(dir().join("seurat_names.txt")).unwrap().lines().map(str::to_owned).collect();
+ let ids_file = dir().join("mt_genes.txt");
+ let ids_text = std::fs::read_to_string(&ids_file).unwrap();
+ for kind in ["integer", "real"] {
+ let c = scio::Counts::read(&dir().join(kind)).unwrap();
+ assert_eq!(c.seurat_names(), want_names, "{kind}: Seurat's row names");
+ let rna = cluster::metadata::RnaMetadata::of(&c.matrix);
+ for r in rows.iter().filter(|r| r[0] == kind) {
+ match r[1] {
+ "nCount_RNA" => assert_eq!(bits(&rna.n_count), bits(&hexl(r[3])), "{kind}: nCount_RNA"),
+ "pattern" => {
+ let p = PercentMt::compute(&c, &MtGenes::Pattern).unwrap();
+ assert_eq!(p.features, list(r[2]), "{kind}: the features the pattern matches");
+ assert_eq!(bits(&p.values), bits(&hexl(r[3])), "{kind}: percent.mt by the pattern");
+ assert!(p.notes().is_empty(), "{:?}", p.notes());
+ }
+ "list" => {
+ let mt = MtGenes::from_file_text(&ids_text, &ids_file.display().to_string(), "-");
+ let p = PercentMt::compute(&c, &mt).unwrap();
+ assert_eq!(p.features, list(r[2]), "{kind}: the listed features");
+ assert_eq!(bits(&p.values), bits(&hexl(r[3])), "{kind}: percent.mt by the list");
+ assert_eq!((p.ids_listed, p.ids_not_found.clone()), (6, vec!["NOPE1".to_string(), "NOPE2".to_string()]));
+ assert_eq!(p.notes().len(), 1, "the ids not found are reported");
+ }
+ other => panic!("unknown row {other}"),
+ }
+ }
+ }
+ // a list that matches nothing is an error; a pattern that matches nothing gives zeros
+ let c = scio::Counts::read(&dir().join("integer")).unwrap();
+ let none = MtGenes::Ids { ids: vec!["NOPE".into()], file: "x".into(), sha256: "-".into() };
+ assert!(PercentMt::compute(&c, &none).unwrap_err().contains("none of its 1 id(s)"));
+}
diff --git a/crates/cluster/tests/m15b_floor.rs b/crates/cluster/tests/m15b_floor.rs
new file mode 100644
index 0000000..cf36b92
--- /dev/null
+++ b/crates/cluster/tests/m15b_floor.rs
@@ -0,0 +1,93 @@
+//! Milestone M15b (docs/PLAN.md A5b, C5's K14): the floor of runs that regressed covariates out of
+//! `scale.data` (SCTransform's `vars.to.regress`), `[clustering.floor.kernel_regressed]`.
+//!
+//! - **When it applies:** only when both runs record the same non-empty `vars.to.regress` (R's
+//! reference runs in `result.regression.vars`, scrust's in `run.parameters.sctransform`);
+//! every other comparison keeps `[clustering.floor.kernel]`, as before M15b.
+//! - **What it holds:** R's own differences across kernels with the regression, the maxima
+//! validation/python/m15b_floor.py measured on M15b's 134 cases (R's production runs against
+//! its portable runs, both directions), and no more; they exceed `[clustering.floor.kernel]`
+//! where the regression makes `scale.data` kernel-dependent.
+
+use cluster::validate::{floor, floor_for, floor_regressed, regressed};
+use scio::grade::{self, Class, Outcome, Stats};
+use scio::Json;
+
+fn r_run(vars: &[&str]) -> Json {
+ let v: Vec = vars.iter().map(|v| format!("{v:?}")).collect();
+ Json::parse(&format!("{{\"result\": {{\"regression\": {{\"vars\": [{}], \"rank\": 2}}}}}}", v.join(", "))).unwrap()
+}
+
+fn scrust_run(vars: &[&str]) -> Json {
+ let v: Vec = vars.iter().map(|v| format!("{v:?}")).collect();
+ let sct = if vars.is_empty() { "{\"seed_use\": 12345}".to_string() } else { format!("{{\"seed_use\": 12345, \"vars_to_regress\": [{}]}}", v.join(", ")) };
+ Json::parse(&format!("{{\"run\": {{\"parameters\": {{\"sctransform\": {sct}}}}}, \"result\": {{}}}}")).unwrap()
+}
+
+#[test]
+fn the_regressed_floor_only_when_both_runs_regressed_the_same() {
+ let name = |r: Option<&Json>, c: &Json| floor_for(r, c).0.source;
+ assert_eq!(regressed(Some(&r_run(&["percent.mt", "nCount_RNA"]))), vec!["percent.mt", "nCount_RNA"]);
+ assert_eq!(regressed(Some(&scrust_run(&["percent.mt"]))), vec!["percent.mt"]);
+ assert!(regressed(Some(&scrust_run(&[]))).is_empty() && regressed(None).is_empty());
+ let (f, v) = floor_for(Some(&r_run(&["percent.mt", "nCount_RNA"])), &scrust_run(&["percent.mt", "nCount_RNA"]));
+ assert_eq!((f.source.as_str(), v), ("clustering.floor.kernel_regressed", Some(vec!["percent.mt".to_string(), "nCount_RNA".to_string()])));
+ // no regression, another list, another order, one side only, or no reference: as before M15b
+ for (r, c) in [(r_run(&[]), scrust_run(&[])), (r_run(&["percent.mt"]), scrust_run(&["percent.mt", "nCount_RNA"])),
+ (r_run(&["nCount_RNA", "percent.mt"]), scrust_run(&["percent.mt", "nCount_RNA"])), (r_run(&["percent.mt"]), scrust_run(&[])),
+ (r_run(&[]), scrust_run(&["percent.mt"]))] {
+ assert_eq!(name(Some(&r), &c), "clustering.floor.kernel");
+ }
+ assert_eq!(name(None, &scrust_run(&["percent.mt"])), "clustering.floor.kernel");
+ // a run of scrust as the reference (both scrust's records)
+ assert_eq!(name(Some(&scrust_run(&["score"])), &scrust_run(&["score"])), "clustering.floor.kernel_regressed");
+}
+
+/// One measured array: the maxima over M15b's 134 cases of R's production runs against its
+/// portable runs (validation/python/m15b_floor.py, data/clustering/m15b/floor/r_vs_r.tsv), each
+/// statistic at its own maximum, so the worst any case showed.
+fn measured(n: usize, n_differ: usize, rows_differ: usize, max_abs: f64, max_scaled: f64) -> Stats {
+ Stats { n, n_differ, rows_differ, max_abs, max_scaled, max_rel: 0.0, flipped: 0, incomparable: false }
+}
+
+#[test]
+fn the_regressed_floor_holds_r_against_r_and_no_more() {
+ let tolerance = grade::mode(Some("Haswell"), Some("SapphireRapids"));
+ let (regressed_floor, unregressed_floor) = (floor_regressed(), floor());
+ let graded = |f: &scio::grade::Floor, key: &str, s: &Stats| grade::grade(s, Class::BlasDependent, &tolerance, f, key);
+ let cases: Vec<(&str, Stats)> = vec![
+ // scale.data: max_abs on soupx_emptydrops_4500871lane ids_ncount; the fraction (0.7145) on
+ // posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test ids_ncount (43,639 of 61,074)
+ ("S2d_scale_data", measured(61_074, 43_639, 702, 5.577760475716786e-13, 2.5636277230434938e-14)),
+ ("S3_embeddings_dims_1_30", measured(2_382_270, 2_373_288, 79_409, 6.181126721571673e-10, 2.541942065390956e-12)),
+ ("S3_embeddings_dims_31_50", measured(3_260, 3_260, 163, 5.462276971124336e-06, 6.558590028828964e-07)),
+ ("S3_loadings", measured(39_650, 39_536, 793, 1.6660416942912426e-07, 5.947046484191046e-07)),
+ ("S3_sdev", measured(50, 48, 48, 2.617905892066119e-13, 4.959296748297619e-14)),
+ ("total_variance", measured(1, 1, 1, 1.1368683772161603e-13, 2.1158087588688924e-16)),
+ ("K8_silhouette_width", measured(79_409, 79_366, 79_366, 1.945443806050662e-12, 2.0765184218349937e-12)),
+ // purity: 34 cells over 18 cases (at most 2 in one), the largest difference 0.0258
+ ("K9_purity", measured(247, 34, 34, 0.0258032275131006, 0.0258032275131006)),
+ ];
+ for (key, s) in &cases {
+ assert_eq!(graded(®ressed_floor, key, s), Outcome::WithinFloor, "{key}: R's own difference across kernels, with the regression");
+ // beyond [clustering.floor.kernel], which the regression's runs therefore do not use
+ assert!(matches!(graded(&unregressed_floor, key, s), Outcome::Differ(_)), "{key}: within the unregressed floor");
+ }
+ // and no more: past any bound, a difference
+ let past = |s: &Stats, f: &dyn Fn(&mut Stats)| {
+ let mut t = s.clone();
+ f(&mut t);
+ t
+ };
+ let sd = &cases[0].1;
+ assert!(matches!(graded(®ressed_floor, "S2d_scale_data", &past(sd, &|t| t.max_abs = 5.7e-13)), Outcome::Differ(m) if m.contains("max_abs")));
+ assert!(matches!(graded(®ressed_floor, "S2d_scale_data", &past(sd, &|t| t.n_differ = t.n * 73 / 100)), Outcome::Differ(m) if m.contains("max_fraction_differing")));
+ let pur = &cases[7].1;
+ assert!(matches!(graded(®ressed_floor, "K9_purity", &past(pur, &|t| t.rows_differ = 35)), Outcome::Differ(m) if m.contains("cells_differing")));
+ assert!(matches!(graded(®ressed_floor, "K9_purity", &past(pur, &|t| t.max_abs = 0.027)), Outcome::Differ(m) if m.contains("max_abs")));
+ // an array the regressed floor does not list stays exact (it stands alone)
+ assert!(matches!(graded(®ressed_floor, "K5_nn_dist", &cases[1].1), Outcome::Differ(m) if m.contains("not in the floor")));
+ // the same kernel: exact, whatever the floor
+ let exact = grade::mode(Some("SapphireRapids"), Some("SapphireRapids"));
+ assert!(matches!(grade::grade(&cases[0].1, Class::BlasDependent, &exact, ®ressed_floor, "S2d_scale_data"), Outcome::Differ(_)));
+}
diff --git a/crates/rcompat/src/blas.rs b/crates/rcompat/src/blas.rs
index 6f41a26..9e1ce80 100644
--- a/crates/rcompat/src/blas.rs
+++ b/crates/rcompat/src/blas.rs
@@ -73,6 +73,8 @@ mod sys {
);
pub fn ddot_(n: *const c_int, x: *const f64, incx: *const c_int, y: *const f64, incy: *const c_int) -> f64;
pub fn dnrm2_(n: *const c_int, x: *const f64, incx: *const c_int) -> f64;
+ pub fn daxpy_(n: *const c_int, alpha: *const f64, x: *const f64, incx: *const c_int, y: *mut f64, incy: *const c_int);
+ pub fn dscal_(n: *const c_int, alpha: *const f64, x: *mut f64, incx: *const c_int);
}
}
@@ -152,6 +154,23 @@ pub fn dnrm2(x: &[f64]) -> f64 {
unsafe { sys::dnrm2_(&n, x.as_ptr(), &one) }
}
+/// `daxpy(n, alpha, x, 1, y, 1)`: `y := alpha * x + y` (milestone M15b: LINPACK's `dqrdc2` and
+/// `dqrsl`, [`crate::linpack`]). OpenBLAS's kernels fuse the multiply and the add on some CPUs, so
+/// the result is R's only through this call.
+pub fn daxpy(alpha: f64, x: &[f64], y: &mut [f64]) {
+ assert_eq!(x.len(), y.len(), "daxpy: lengths differ");
+ let (n, one) = (int(x.len(), "n"), 1 as c_int);
+ // SAFETY: both slices hold n elements, and they are distinct (`y` is borrowed mutably).
+ unsafe { sys::daxpy_(&n, &alpha, x.as_ptr(), &one, y.as_mut_ptr(), &one) }
+}
+
+/// `dscal(n, alpha, x, 1)`: `x := alpha * x` (M15b, [`crate::linpack`]).
+pub fn dscal(alpha: f64, x: &mut [f64]) {
+ let (n, one) = (int(x.len(), "n"), 1 as c_int);
+ // SAFETY: the slice holds n elements.
+ unsafe { sys::dscal_(&n, &alpha, x.as_mut_ptr(), &one) }
+}
+
/// The OpenBLAS kernel ("core") in use, as `openblas_get_corename()` reports it: `Haswell`,
/// `SkylakeX`, `Cooperlake`, `SapphireRapids`, ...
pub fn corename() -> String {
diff --git a/crates/rcompat/src/lib.rs b/crates/rcompat/src/lib.rs
index ee181c8..fba876f 100644
--- a/crates/rcompat/src/lib.rs
+++ b/crates/rcompat/src/lib.rs
@@ -33,7 +33,10 @@
//! - [`gamma`]: R's `lgammafn`, `digamma`, `trigamma`, and glibc's `lgamma` (M4);
//! - [`port`]: `nlminb()`, R's PORT library (`DRMNHB` and its call tree) (M4);
//! - [`matrixstats`]: matrixStats' `rowMeans2`, `colMeans2`, `rowVars`, `weightedMedian`, and
-//! R's `R_qsort_I` (M4).
+//! R's `R_qsort_I` (M4);
+//! - [`linpack`]: R's LINPACK QR (`dqrdc2`, `dqrsl`) as `lm()` makes it and `qr.resid()` applies
+//! it, through OpenBLAS's `dnrm2`, `dscal`, `ddot` and `daxpy` (M15b: SCTransform's
+//! `vars.to.regress`).
//!
//! Indices are 0-based throughout (R's minus one). Functions that call the C math library ([`libm`])
//! use the system glibc, as R does.
@@ -48,6 +51,7 @@ pub mod format;
pub mod gamma;
pub mod ldouble;
pub mod libm;
+pub mod linpack;
pub mod matrixstats;
pub mod nbinom;
pub mod normal;
diff --git a/crates/rcompat/src/linpack.rs b/crates/rcompat/src/linpack.rs
new file mode 100644
index 0000000..1cc3d79
--- /dev/null
+++ b/crates/rcompat/src/linpack.rs
@@ -0,0 +1,315 @@
+//! R's LINPACK QR decomposition, as `lm()` makes it and `qr.resid()` applies it (milestone M15b:
+//! SCTransform's `vars.to.regress`, docs/PLAN.md C3).
+//!
+//! Seurat 5.5.1's `RegressOutMatrix()` regresses every row of `scale.data` on the same covariates:
+//! it takes `lm(GENE ~ , data, qr = TRUE)$qr` once, then `qr.resid(qr, y = )` per row.
+//! In R 4.5.3 that is:
+//!
+//! - **the QR** ([`lm_qr`]): `lm.fit()` calls `.Call(C_Cdqrls, x, y, tol = 1e-07, FALSE)`
+//! (`src/library/stats/src/lm.c`), which stops on a non-finite value of `x` ("NA/NaN/Inf in
+//! 'x'") and calls `dqrls` (`src/appl/dqrls.f`), which calls [`dqrdc2`] (`src/appl/dqrdc2.f`):
+//! R's modification of LINPACK's `dqrdc`, Householder reflections with a limited column
+//! pivoting that moves each column whose norm falls below `tol` times its original norm to the
+//! right-hand edge, and computes the rank. `x` is the model matrix: the intercept (1.0), then the
+//! covariates in the formula's order;
+//! - **the residuals** ([`QrResid`]): `qr.resid()` (`src/library/base/R/qr.R`) returns `y` when the
+//! rank is 0, else calls `dqrrsd` (`src/appl/dqrutl.f`), which calls `dqrsl(..., job = 10)`
+//! (`src/appl/dqrsl.f`): `qty = Q' y` in place, then `rsd` = `qty` with its first `rank`
+//! entries zeroed, multiplied by `Q`.
+//!
+//! `dqrdc2` and `dqrsl` are Fortran in `libR.so`, compiled without FMA (`-march=nocona`; no
+//! `vfmadd` in their code), and call BLAS `dnrm2`, `dscal`, `ddot` and `daxpy`, which `libR.so`
+//! takes from `libblas.so.3`, the conda env's OpenBLAS 0.3.34 (`ldd`, `nm -D`). Its kernels differ
+//! by CPU (Haswell's `ddot` and `daxpy` fuse multiply and add), so the port calls the same
+//! routines with the same lengths ([`crate::blas`]): the results are R's bit for bit under the
+//! same kernel. OpenBLAS's level-1 kernels load unaligned and peel nothing for alignment, so a
+//! result depends on the vector's length and values, not on where it lies in memory: the port
+//! passes each Householder vector as a contiguous copy with its leading element replaced, where
+//! `dqrsl` swaps `qraux(j)` into `x(j,j)` for the call and back. `dcopy` copies values unchanged
+//! and is done in Rust.
+
+use crate::blas::{daxpy, ddot, dnrm2, dscal};
+
+/// `lm.fit()`'s default tolerance (`tol = 1e-07`).
+pub const LM_TOL: f64 = 1e-7;
+
+/// R's `qr` object as `lm(..., qr = TRUE)$qr` holds it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Qr {
+ /// Rows (cells) and columns (the intercept and the covariates).
+ pub n: usize,
+ pub p: usize,
+ /// `qr$qr`: the compact decomposition, `n x p`, column-major.
+ pub qr: Vec,
+ /// `qr$qraux`.
+ pub qraux: Vec,
+ /// `qr$pivot`: 1-based column numbers of `x`, in their order after pivoting.
+ pub pivot: Vec,
+ /// `qr$rank`.
+ pub rank: usize,
+ /// `qr$tol`.
+ pub tol: f64,
+}
+
+/// LINPACK `dqrdc2` as R 4.5.3 has it (`src/appl/dqrdc2.f`, "modernized to F77, 2024-05"), on
+/// `x` (`n x p`, column-major, overwritten with the decomposition) with `ldx = n`. Returns
+/// `qraux`, `jpvt` (1-based; it starts as `1..p`, as `Cdqrls` sets it) and the rank `k`.
+pub fn dqrdc2(x: &mut [f64], n: usize, p: usize, tol: f64) -> (Vec, Vec, usize) {
+ assert_eq!(x.len(), n * p, "dqrdc2: x is not n x p");
+ let mut qraux = vec![0.0f64; p];
+ // work(p, 2): the columns' norms as updated, and their original norms (1 for a zero column)
+ let mut work1 = vec![0.0f64; p];
+ let mut work2 = vec![0.0f64; p];
+ let mut jpvt: Vec = (1..=p).collect();
+ let at = |i: usize, j: usize| i + j * n;
+ // compute the norms of the columns of x
+ if n > 0 {
+ for j in 0..p {
+ qraux[j] = dnrm2(&x[at(0, j)..at(0, j) + n]);
+ work1[j] = qraux[j];
+ work2[j] = qraux[j];
+ if work2[j] == 0.0 {
+ work2[j] = 1.0;
+ }
+ }
+ }
+ // perform the householder reduction of x; `l` and `k` are Fortran's (1-based)
+ let lup = n.min(p);
+ let mut k = p + 1;
+ for l in 1..=lup {
+ let c = l - 1; // column l, 0-based
+ // cycle the columns from l to p left-to-right until one with non-negligible norm is
+ // located; the check for l .ge. k avoids infinite cycling
+ loop {
+ if l >= k || qraux[c] >= work2[c] * tol {
+ break;
+ }
+ for i in 0..n {
+ let t = x[at(i, c)];
+ for j in (l + 1)..=p {
+ x[at(i, j - 2)] = x[at(i, j - 1)];
+ }
+ x[at(i, p - 1)] = t;
+ }
+ let i = jpvt[c];
+ let t = qraux[c];
+ let tt = work1[c];
+ let ttt = work2[c];
+ for j in (l + 1)..=p {
+ jpvt[j - 2] = jpvt[j - 1];
+ qraux[j - 2] = qraux[j - 1];
+ work1[j - 2] = work1[j - 1];
+ work2[j - 2] = work2[j - 1];
+ }
+ jpvt[p - 1] = i;
+ qraux[p - 1] = t;
+ work1[p - 1] = tt;
+ work2[p - 1] = ttt;
+ k -= 1;
+ }
+ if l != n {
+ // compute the householder transformation for column l: rows l..n
+ let (head, tail) = x.split_at_mut(at(0, c) + n);
+ let col_l = &mut head[at(c, c)..];
+ let mut nrmxl = dnrm2(col_l);
+ if nrmxl != 0.0 {
+ // Fortran's sign(a, b): |a| with b's sign
+ if col_l[0] != 0.0 {
+ nrmxl = nrmxl.abs().copysign(col_l[0]);
+ }
+ dscal(1.0 / nrmxl, col_l);
+ col_l[0] = 1.0 + col_l[0];
+ // apply the transformation to the remaining columns, updating the norms
+ let xll = col_l[0];
+ for j in (l + 1)..=p {
+ let cj = j - 1;
+ let off = at(0, cj) - (at(0, c) + n);
+ let col_j = &mut tail[off + c..off + n];
+ // t = -ddot(n-l+1, x(l,l), 1, x(l,j), 1) / x(l,l): divsd, then the sign flip
+ let t = -(ddot(col_l, col_j) / xll);
+ daxpy(t, col_l, col_j);
+ if qraux[cj] != 0.0 {
+ // tt = 1 - (|x(l,j)| / qraux(j))**2 (y**2 is y*y); max(tt, 0) as maxsd
+ let q = col_j[0].abs() / qraux[cj];
+ let tt = 1.0 - q * q;
+ let t = if tt > 0.0 { tt } else { 0.0 };
+ // re-compute the norm when it has dropped a lot (relative to the original)
+ if t.abs() >= 1e-6 {
+ qraux[cj] *= t.sqrt();
+ } else {
+ qraux[cj] = dnrm2(&col_j[1..]);
+ work1[cj] = qraux[cj];
+ }
+ }
+ }
+ // save the transformation
+ qraux[c] = col_l[0];
+ col_l[0] = -nrmxl;
+ }
+ }
+ }
+ let k = (k - 1).min(n);
+ (qraux, jpvt, k)
+}
+
+/// The QR that `lm.fit(x, y)` returns (`Cdqrls` with `tol = 1e-07`): `x` is the model matrix,
+/// `n x p`, column-major. R's checks first: `n == 0` stops ("0 (non-NA) cases"), and a non-finite
+/// value of `x` stops ("NA/NaN/Inf in 'x'").
+pub fn lm_qr(mut x: Vec, n: usize, p: usize) -> Result {
+ if x.len() != n * p {
+ return Err(format!("lm: the model matrix holds {} values, not {n} x {p}", x.len()));
+ }
+ if n == 0 {
+ return Err("lm.fit: 0 (non-NA) cases".into());
+ }
+ if p == 0 {
+ return Err("lm.fit: a model matrix without columns (the null model) is not supported".into());
+ }
+ if x.iter().any(|v| !v.is_finite()) {
+ return Err("lm.fit: NA/NaN/Inf in 'x'".into());
+ }
+ let (qraux, pivot, rank) = dqrdc2(&mut x, n, p, LM_TOL);
+ Ok(Qr { n, p, qr: x, qraux, pivot, rank, tol: LM_TOL })
+}
+
+/// `model.matrix(GENE ~ v1 + v2 + ...)` for numeric covariates: the intercept (1.0), then each
+/// covariate's values as they are, `n x (1 + q)`, column-major.
+pub fn model_matrix(covariates: &[&[f64]], n: usize) -> Vec {
+ let mut x = vec![1.0f64; n * (1 + covariates.len())];
+ for (j, c) in covariates.iter().enumerate() {
+ assert_eq!(c.len(), n, "model_matrix: a covariate does not have one value per row");
+ x[(j + 1) * n..(j + 2) * n].copy_from_slice(c);
+ }
+ x
+}
+
+/// `qr.resid(qr, y)` for many `y` with one QR: the Householder vectors `dqrsl` uses, prepared
+/// once. It only reads, so threads may share it.
+#[derive(Debug, Clone)]
+pub struct QrResid<'a> {
+ qr: &'a Qr,
+ /// `ju = min(rank, n - 1)` vectors: column `j`'s rows `j..n` with `qraux(j)` in place of
+ /// `x(j,j)`, as `dqrsl` passes them to `ddot` and `daxpy` (empty where `qraux(j) == 0`,
+ /// which `dqrsl` skips)
+ v: Vec>,
+}
+
+impl<'a> QrResid<'a> {
+ pub fn new(qr: &'a Qr) -> QrResid<'a> {
+ let n = qr.n;
+ let ju = if n == 0 { 0 } else { qr.rank.min(n - 1) };
+ let v = (0..ju)
+ .map(|j| {
+ if qr.qraux[j] == 0.0 {
+ return Vec::new();
+ }
+ let mut v = qr.qr[j + j * n..(j + 1) * n].to_vec();
+ v[0] = qr.qraux[j];
+ v
+ })
+ .collect();
+ QrResid { qr, v }
+ }
+
+ /// `qr.resid(qr, y)` into `rsd`; `qty` is the work vector `dqrsl` computes `Q' y` in (`y`'s
+ /// own copy, in `dqrrsd`). All three hold `n` values.
+ pub fn resid(&self, y: &[f64], qty: &mut [f64], rsd: &mut [f64]) {
+ let (n, k) = (self.qr.n, self.qr.rank);
+ assert!(y.len() == n && qty.len() == n && rsd.len() == n, "qr.resid: 'qr' and 'y' must have the same number of rows");
+ if k == 0 {
+ // qr.resid: if (k == 0) return(y)
+ rsd.copy_from_slice(y);
+ return;
+ }
+ // dqrsl, job = 10: qty, then rsd (cqty and cr; not qy, b or xb)
+ let ju = k.min(n - 1);
+ if ju == 0 {
+ // special action when n = 1
+ qty[0] = y[0];
+ rsd[0] = 0.0;
+ return;
+ }
+ // dcopy(n, y, 1, qty, 1)
+ qty.copy_from_slice(y);
+ // compute trans(q) * y
+ for j in 0..ju {
+ if self.qr.qraux[j] == 0.0 {
+ continue;
+ }
+ let v = &self.v[j];
+ let t = -(ddot(v, &qty[j..]) / v[0]);
+ daxpy(t, v, &mut qty[j..]);
+ }
+ // set up to compute rsd: dcopy(n-k, qty(k+1), 1, rsd(k+1), 1), then rsd(1..k) = 0
+ if k < n {
+ rsd[k..].copy_from_slice(&qty[k..]);
+ }
+ for r in rsd.iter_mut().take(k) {
+ *r = 0.0;
+ }
+ // compute rsd
+ for j in (0..ju).rev() {
+ if self.qr.qraux[j] == 0.0 {
+ continue;
+ }
+ let v = &self.v[j];
+ let t = -(ddot(v, &rsd[j..]) / v[0]);
+ daxpy(t, v, &mut rsd[j..]);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The residuals are orthogonal to the model's columns, and y minus them lies in its span.
+ #[test]
+ fn residuals_of_an_exact_fit_and_of_noise() {
+ let n = 50;
+ let v: Vec = (0..n).map(|i| (i as f64 * 0.37).sin() * 3.0).collect();
+ let x = model_matrix(&[&v], n);
+ let qr = lm_qr(x, n, 2).unwrap();
+ assert_eq!((qr.rank, qr.pivot.clone()), (2, vec![1, 2]));
+ let r = QrResid::new(&qr);
+ // y = 2 + 5 v: residuals ~ 0
+ let y: Vec = v.iter().map(|a| 2.0 + 5.0 * a).collect();
+ let (mut qty, mut rsd) = (vec![0.0; n], vec![0.0; n]);
+ r.resid(&y, &mut qty, &mut rsd);
+ assert!(rsd.iter().all(|e| e.abs() < 1e-12), "{rsd:?}");
+ // noise: residuals orthogonal to 1 and v
+ let y: Vec = (0..n).map(|i| ((i * 7919) % 101) as f64 / 10.0).collect();
+ r.resid(&y, &mut qty, &mut rsd);
+ let s1: f64 = rsd.iter().sum();
+ let s2: f64 = rsd.iter().zip(&v).map(|(a, b)| a * b).sum();
+ assert!(s1.abs() < 1e-10 && s2.abs() < 1e-10, "{s1} {s2}");
+ }
+
+ /// A zero column is moved to the edge and leaves rank 1: the regression on the intercept
+ /// alone, so the residuals are the centred values.
+ #[test]
+ fn a_zero_column_is_pivoted_out() {
+ let n = 9;
+ let zero = vec![0.0; n];
+ let qr = lm_qr(model_matrix(&[&zero], n), n, 2).unwrap();
+ assert_eq!((qr.rank, qr.pivot.clone()), (1, vec![1, 2]));
+ let r = QrResid::new(&qr);
+ let y: Vec = (0..n).map(|i| i as f64).collect();
+ let (mut qty, mut rsd) = (vec![0.0; n], vec![0.0; n]);
+ r.resid(&y, &mut qty, &mut rsd);
+ for (i, e) in rsd.iter().enumerate() {
+ assert!((e - (i as f64 - 4.0)).abs() < 1e-12);
+ }
+ // the zero column first: it moves behind the intercept
+ let x: Vec = zero.iter().copied().chain(std::iter::repeat(1.0).take(n)).collect();
+ let qr = lm_qr(x, n, 2).unwrap();
+ assert_eq!((qr.rank, qr.pivot.clone()), (1, vec![2, 1]));
+ }
+
+ #[test]
+ fn r_stops_on_non_finite_values_and_no_rows() {
+ assert!(lm_qr(vec![1.0, f64::NAN], 1, 2).unwrap_err().contains("NA/NaN/Inf"));
+ assert!(lm_qr(vec![1.0, f64::INFINITY], 1, 2).unwrap_err().contains("NA/NaN/Inf"));
+ assert!(lm_qr(Vec::new(), 0, 2).unwrap_err().contains("0 (non-NA) cases"));
+ }
+}
diff --git a/crates/scio/src/features.rs b/crates/scio/src/features.rs
new file mode 100644
index 0000000..a713589
--- /dev/null
+++ b/crates/scio/src/features.rs
@@ -0,0 +1,195 @@
+//! Features as Seurat names them, and Seurat's `PercentageFeatureSet()` (milestone M15b: the
+//! workflow's `percent.mt`, docs/PLAN.md C3).
+//!
+//! The workflow computes, before SCTransform,
+//! `obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = "(?i)^mt-")`, on the object's
+//! row names:
+//!
+//! - **Seurat's row names** ([`seurat_names`]): `Read10X()` names the rows by the features file's
+//! column 2 made unique (`make.unique()`, `unique.features = TRUE`), and SeuratObject's
+//! `CreateSeuratObject()` replaces `_` and `|` with `-`. The R loader names them the same way
+//! (`loaders/R/scrustio/R/names.R`);
+//! - **the pattern** ([`matches_mt_pattern`]): R's `grep()` with `perl = FALSE` is the TRE engine,
+//! where `(?i)` makes the rest case-insensitive and `^` anchors at the start: a name matches
+//! when it begins with `m` or `M`, then `t` or `T`, then `-` (checked in the pinned env on
+//! names such as `MT-ND1`, `mT-Cytb`, `MT--`, ` mt-a`, `mt_a` and a fullwidth `m`:
+//! `validation/R/regress_vectors.R`). `make.unique()` only appends `.1`, `.2`, ... to a name,
+//! so it never changes whether a name matches; the `_` and `|` replacement does (`Mt_Atp6`
+//! becomes `Mt-Atp6`);
+//! - **the percentage** ([`Counts::percent_feature_set`]): Seurat 5.5.1's
+//! `layer.sums / object[[]][cells, "nCount_RNA"] * 100`, where `layer.sums` is
+//! `Matrix::colSums()` of the counts' rows for the features (Matrix 1.7-6's `Csparse_colsum`:
+//! each column's stored values in stored order, added in double) and `nCount_RNA` is
+//! `CreateSeuratObject()`'s `colSums()` of the whole column, the same way. The rows are taken in
+//! the counts' order, as `grep()` returns them (for integer counts the order cannot matter:
+//! every partial sum is exact). A cell with no counts gets `0/0 * 100`, NaN, as in R; a feature
+//! set that matches nothing gives zeros.
+
+use crate::counts::Counts;
+use crate::tenx::Feature;
+use std::collections::HashSet;
+
+/// The workflow's pattern for mitochondrial features (`PercentageFeatureSet(pattern = )`).
+pub const MT_PATTERN: &str = "(?i)^mt-";
+
+/// R's `make.unique(names, sep = ".")` (`do_makeunique` in R 4.5.3's `src/main/unique.c`): a name
+/// seen before becomes `name.`, trying `cnt` from the first unused value for that name
+/// upwards until the result is not among the names so far (the original names and those already
+/// made). The first occurrence keeps its name.
+pub fn make_unique(names: &[String]) -> Vec {
+ let n = names.len();
+ let mut out: Vec = names.to_vec();
+ if n < 2 {
+ return out;
+ }
+ let mut used: HashSet = names.iter().cloned().collect();
+ // index of each name's first occurrence, and the next count to try for it
+ let mut first: std::collections::HashMap<&str, usize> = std::collections::HashMap::with_capacity(n);
+ let mut cnts = vec![1usize; n];
+ // R's one-element buffer `newx`, reused from name to name
+ let mut newx = String::new();
+ for (i, s) in names.iter().enumerate() {
+ let Some(&dp) = first.get(s.as_str()) else {
+ first.insert(s.as_str(), i);
+ continue;
+ };
+ // try appending 1, 2, 3, ..., n - 1 until it is not already in use
+ let mut cnt = cnts[dp];
+ while cnt < n {
+ newx = format!("{s}.{cnt}");
+ if !used.contains(&newx) {
+ break;
+ }
+ cnt += 1;
+ }
+ used.insert(newx.clone());
+ out[i] = newx.clone();
+ cnts[dp] = cnt + 1;
+ }
+ out
+}
+
+/// Seurat's row names for features named `names` (the features file's column 2, in row order):
+/// `make.unique()` as `Read10X()` applies it, then `_` and `|` replaced with `-` as
+/// `CreateSeuratObject()` does.
+pub fn seurat_names(names: &[String]) -> Vec {
+ make_unique(names).into_iter().map(|s| s.replace(['_', '|'], "-")).collect()
+}
+
+/// Whether a Seurat row name matches the workflow's [`MT_PATTERN`], `"(?i)^mt-"`, as R's
+/// `grep()` (TRE) matches it: it begins with `m` or `M`, `t` or `T`, then `-`.
+pub fn matches_mt_pattern(name: &str) -> bool {
+ let b = name.as_bytes();
+ b.len() >= 3 && (b[0] == b'm' || b[0] == b'M') && (b[1] == b't' || b[1] == b'T') && b[2] == b'-'
+}
+
+/// The rows (0-based, in the counts' order) whose Seurat name matches [`MT_PATTERN`].
+pub fn mt_pattern_rows(features: &[Feature]) -> Vec {
+ let names: Vec = features.iter().map(|f| f.name.clone()).collect();
+ seurat_names(&names).iter().enumerate().filter(|(_, s)| matches_mt_pattern(s)).map(|(i, _)| i).collect()
+}
+
+/// Which rows a list of feature ids (the features file's column 1) selects: the rows whose id is
+/// listed, in the counts' order, and the listed ids found among none of the features, in the
+/// list's order (each once).
+pub fn id_rows(features: &[Feature], ids: &[String]) -> (Vec, Vec) {
+ let listed: HashSet<&str> = ids.iter().map(String::as_str).collect();
+ let rows: Vec = features.iter().enumerate().filter(|(_, f)| listed.contains(f.id.as_str())).map(|(i, _)| i).collect();
+ let present: HashSet<&str> = features.iter().map(|f| f.id.as_str()).collect();
+ let mut seen = HashSet::new();
+ let missing = ids.iter().filter(|id| !present.contains(id.as_str()) && seen.insert(id.as_str())).cloned().collect();
+ (rows, missing)
+}
+
+/// A list of feature ids as a file holds it: one id per line, each line's surrounding whitespace
+/// (spaces, tabs, a carriage return) ignored, blank lines and lines starting with `#` skipped.
+/// Returns the ids in the file's order, repeats included.
+pub fn parse_id_list(text: &str) -> Vec {
+ text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(str::to_string).collect()
+}
+
+impl Counts {
+ /// Seurat's row names for these counts ([`seurat_names`] of the features' names).
+ pub fn seurat_names(&self) -> Vec {
+ let names: Vec = self.features().into_iter().map(|f| f.name).collect();
+ seurat_names(&names)
+ }
+
+ /// `PercentageFeatureSet()` for the features in `rows` (0-based, ascending): per cell, their
+ /// counts summed in stored order, divided by the cell's `nCount_RNA` (all its counts, summed
+ /// in stored order), times 100, in R's order of operations.
+ pub fn percent_feature_set(&self, rows: &[usize]) -> Vec {
+ let m = &self.matrix;
+ let mut set = vec![false; m.nrow];
+ for &r in rows {
+ set[r] = true;
+ }
+ (0..m.ncol)
+ .map(|j| {
+ let (i, x) = m.col(j);
+ let mut s = 0.0f64;
+ let mut total = 0.0f64;
+ for (&r, &v) in i.iter().zip(x) {
+ total += v;
+ if set[r as usize] {
+ s += v;
+ }
+ }
+ s / total * 100.0
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sparse::CscMatrix;
+
+ fn strs(v: &[&str]) -> Vec {
+ v.iter().map(|s| s.to_string()).collect()
+ }
+
+ #[test]
+ fn make_unique_as_r() {
+ // R: make.unique(c("a", "a", "b", "a", "a.1", "b")): "a.1" is an original name, so the
+ // first repeat of "a" becomes "a.2" (tests/fixtures/clustering/percent_mt/make_unique.tsv
+ // has R's results for more cases)
+ assert_eq!(make_unique(&strs(&["a", "a", "b", "a", "a.1", "b"])), strs(&["a", "a.2", "b", "a.3", "a.1", "b.1"]));
+ // R: make.unique(c("a", "a.1", "a")): "a.1" is taken, so the duplicate becomes "a.2"
+ assert_eq!(make_unique(&strs(&["a", "a.1", "a"])), strs(&["a", "a.1", "a.2"]));
+ assert_eq!(make_unique(&strs(&["x"])), strs(&["x"]));
+ }
+
+ #[test]
+ fn seurat_names_and_the_pattern() {
+ let names = strs(&["mt-Co1", "MT-ND2", "Mt_Atp6", "mT|Cytb", "Mtor", "xmt-a", "mt", "mt", "Gene_1", "Gene_1", "MT-"]);
+ let s = seurat_names(&names);
+ assert_eq!(s, strs(&["mt-Co1", "MT-ND2", "Mt-Atp6", "mT-Cytb", "Mtor", "xmt-a", "mt", "mt.1", "Gene-1", "Gene-1.1", "MT-"]));
+ let hits: Vec = s.iter().map(|n| matches_mt_pattern(n)).collect();
+ assert_eq!(hits, vec![true, true, true, true, false, false, false, false, false, false, true]);
+ assert!(!matches_mt_pattern("mt-a") && !matches_mt_pattern(" mt-a") && matches_mt_pattern("MT--"));
+ }
+
+ #[test]
+ fn id_lists() {
+ let f: Vec = ["A\ta\tG", "B\tb\tG", "C\tc\tG"].iter().map(|l| Feature::parse(l)).collect();
+ let ids = parse_id_list("# mt\nC\n\n A \r\nC\nZ\nZ\n#B\n");
+ assert_eq!(ids, strs(&["C", "A", "C", "Z", "Z"]));
+ assert_eq!(id_rows(&f, &ids), (vec![0, 2], strs(&["Z"])));
+ }
+
+ #[test]
+ fn percent_feature_set_as_r() {
+ // 3 genes x 3 cells; the third cell has no counts
+ let m = CscMatrix { nrow: 3, ncol: 3, p: vec![0, 3, 4, 4], i: vec![0, 1, 2, 1], x: vec![1.0, 2.0, 5.0, 4.0] };
+ let c = Counts::new(m, strs(&["c1", "c2", "c3"]), strs(&["g1\tg1\tG", "g2\tg2\tG", "g3\tg3\tG"])).unwrap();
+ let p = c.percent_feature_set(&[0, 2]);
+ assert_eq!(p[0].to_bits(), (6.0f64 / 8.0 * 100.0).to_bits());
+ assert_eq!(p[1], 0.0);
+ assert!(p[2].is_nan());
+ let none = c.percent_feature_set(&[]);
+ assert_eq!((none[0], none[1]), (0.0, 0.0));
+ assert!(none[2].is_nan());
+ }
+}
diff --git a/crates/scio/src/lib.rs b/crates/scio/src/lib.rs
index 383ab2d..1518f58 100644
--- a/crates/scio/src/lib.rs
+++ b/crates/scio/src/lib.rs
@@ -31,6 +31,7 @@ pub mod copy;
pub mod counts;
pub mod deflate;
pub mod factor;
+pub mod features;
pub mod grade;
pub mod gz;
pub mod json;
diff --git a/crates/scrust/src/cmd_cluster.rs b/crates/scrust/src/cmd_cluster.rs
index 97bf006..dcfa7e0 100644
--- a/crates/scrust/src/cmd_cluster.rs
+++ b/crates/scrust/src/cmd_cluster.rs
@@ -9,6 +9,7 @@ use crate::cli::{self, Args, Phases};
use cluster::chain::{self, Chain, Options};
use cluster::chain_output::Writer;
use cluster::chain_params::{self, ChainParams, PARAM_FLAGS, PARAM_SWITCHES};
+use cluster::covariates::{CellCovariates, MtGenes, FROM_COUNTS};
use cluster::metadata::RnaMetadata;
use scio::manifest::{Entry, Ids, Input, InputFile, Manifest, Provenance};
use scio::stages::DumpLevel;
@@ -54,6 +55,24 @@ the defaults, the preset, the --params file (a TOML file with the sections [sctr
Numbers are read as R reads them; a fraction such as 1/15 is divided in double.
SCTransform: --sct-seed 1448145 --ncells 5000 --variable-features 3000
--clip-range lo,hi (default +-sqrt(N/30))
+ --vars-to-regress [,...] vars.to.regress (default: none): the
+ per-cell covariates SCTransform's second regression removes from scale.data
+ (ScaleData's RegressOutMatrix: lm(GENE ~ vars)'s QR, qr.resid per variable
+ feature, then the centring): percent.mt, nCount_RNA, nFeature_RNA, or any
+ numeric column of --metadata (read as R reads numbers). An unknown or
+ repeated name, a name R cannot use in a formula, or a missing, non-numeric or
+ non-finite value is an error
+ --percent-mt compute percent.mt without regressing it, as the workflow's
+ objects hold it (metadata.tsv; implied by --mt-genes and by regressing it)
+ --mt-genes percent.mt's mitochondrial features by id: one id per line
+ (column 1 of the counts' features.tsv; blank lines and lines starting with #
+ are skipped). Ids that no feature has are reported and skipped; a list that
+ matches none is an error. Without it: the workflow's \"(?i)^mt-\" on Seurat's
+ row names (features.tsv's column 2 made unique, _ and | replaced by -).
+ percent.mt is PercentageFeatureSet(): their counts over nCount_RNA, times
+ 100. Regressing percent.mt when no feature matches the pattern is an error
+ that names --mt-genes; otherwise the column is written as computed (zeros
+ included, with a warning)
RunPCA: --npcs 50 --pca-seed 42 --weight-by-var true --pca-guard none|true|N
FindNeighbors: --dims 1:10 --k 20 --trees 50 --metric euclidean|cosine|manhattan
--prune 1/15 --search-k -1
@@ -62,19 +81,24 @@ Numbers are read as R reads them; a fraction such as 1/15 is divided in double.
Scores: --stats silhouette,purity (default) | silhouette | purity | none
--purity-k 50 --purity-weighted true
The scores use the neighbour search's dims (1:30 with the preset).
- Other code paths are refused: --vars-to-regress, --vst-flavor other than v2, --sct-method
- other than glmGamPoi_offset, --do-scale true, --nn-method rann|hnsw, --l2-norm true,
- --metric hamming, --algorithm 4 (Leiden).
+ The TOML file's [sctransform] takes vars_to_regress = [\"percent.mt\", ...], percent_mt = true
+ and mt_genes = \"\" (a relative path is read from the TOML file's directory).
+ Other code paths are refused: --vst-flavor other than v2, --sct-method other than
+ glmGamPoi_offset, --do-scale true, --nn-method rann|hnsw, --l2-norm true, --metric hamming,
+ --algorithm 4 (Leiden). --vars-to-regress, --mt-genes and --percent-mt act where SCTransform
+ runs: --counts here, or scrust sctransform (whose cell_metadata.tsv carries percent.mt to the
+ staged starts).
Outputs (--out, which must not hold a previous run):
seurat_clusters.tsv, seurat_clusters_levels.txt the labels, as scrust doubletfinder reads them
clusters.tsv, _levels.txt one column per resolution (SCT_snn_res.0.8)
cluster_ids.txt, nclusters.txt as the workflow's write_cluster_metadata
optimizer_ids.tsv each resolution's optimizer result
- metadata.tsv barcode, nCount_RNA, nFeature_RNA, each res. column, seurat_clusters,
- silhouette_width, silhouette_other (the closest other cluster),
- neighborhood_purity, purity_maximum (the cluster with the largest share),
- then the columns of --metadata (a TSV with a barcode column), by barcode
+ metadata.tsv barcode, nCount_RNA, nFeature_RNA, percent.mt (when asked for), each res.
+ column, seurat_clusters, silhouette_width, silhouette_other (the closest
+ other cluster), neighborhood_purity, purity_maximum (the cluster with the
+ largest share), then the columns of --metadata (a TSV with a barcode column),
+ by barcode
pca/ embeddings.tsv, loadings.tsv, stdev.tsv, random_seed.txt (scrust pca's)
neighbors/ knn_index.tsv, knn_distance.tsv, nn.mtx.gz, snn.mtx.gz (scrust neighbors'),
and annoy.ann with --annoy yes
@@ -83,8 +107,10 @@ Outputs (--out, which must not hold a previous run):
the stage dumps of the instrumented R runs, for scrust validate cluster
(--purity-lists: purity's neighbour lists among them; auto: at level full)
summary.json result: FindClusters' (the network, every start, the best start, what
- FindClusters printed, the singletons, the levels), each stage's, R's digests
- of .Random.seed after SCTransform and RunPCA and of scale.data, the scores
+ FindClusters printed, the singletons, the levels), each stage's (SCTransform's
+ with the regression and percent.mt's definition, features and ids not found,
+ when asked for), R's digests of .Random.seed after SCTransform and RunPCA
+ and of scale.data, the scores
(purity: the radius and the certificate, every flagged pair); run:
parameters, timings and peak memory per stage, the environment fingerprint;
files: the manifest, every file's role, scale, shape, identifiers, size and
@@ -151,6 +177,7 @@ pub fn params_from_args(args: &Args) -> Result {
Some(p) => Some(std::fs::read_to_string(p).map_err(|e| format!("--params {p}: {e}"))?),
None => None,
};
+ let toml_dir = args.get("params").map(|p| Path::new(p).parent().unwrap_or(Path::new("")).to_path_buf());
let mut flags: Vec<(String, String)> = Vec::new();
for name in PARAM_FLAGS {
if let Some(v) = args.get(name) {
@@ -162,7 +189,44 @@ pub fn params_from_args(args: &Args) -> Result {
flags.push((name.to_string(), String::new()));
}
}
- chain_params::build(args.get("preset"), toml.as_deref(), &flags)
+ chain_params::build_in(args.get("preset"), toml.as_deref(), toml_dir.as_deref(), &flags)
+}
+
+/// Whether a covariate of `vars.to.regress` is a column of `--metadata` (M15b): any name but
+/// percent.mt, nCount_RNA and nFeature_RNA.
+pub fn metadata_regressed(params: &ChainParams) -> bool {
+ params.sct.vars_to_regress.iter().any(|v| !FROM_COUNTS.contains(&v.as_str()))
+}
+
+/// What the chain needs besides the counts for `percent.mt` and `vars.to.regress` (M15b), read
+/// here so that the chain reads no file: `--mt-genes`' ids, with the file's digest, and, when a
+/// covariate is one of `--metadata`'s columns, the table's columns for `barcodes` (each cell's
+/// text). Returns them and the inputs read, for the provenance.
+pub fn read_covariates(params: &ChainParams, metadata: Option<&str>, barcodes: &[String]) -> Result<(CellCovariates, Vec), String> {
+ let mut cov = CellCovariates::default();
+ let mut inputs = Vec::new();
+ if let Some(f) = ¶ms.mt_genes {
+ let p = Path::new(f);
+ let text = std::fs::read_to_string(p).map_err(|e| format!("--mt-genes {f}: {e}"))?;
+ let input = Input::digest("mt-genes", p.parent().unwrap_or(Path::new("")), &[p]).map_err(|e| format!("--mt-genes {f}: {e}"))?;
+ cov.mt_genes = Some(MtGenes::from_file_text(&text, f, &input.files[0].sha256));
+ inputs.push(input);
+ }
+ if metadata_regressed(params) {
+ let m = metadata.ok_or_else(|| {
+ let cols: Vec<&str> = params.sct.vars_to_regress.iter().map(String::as_str).filter(|v| !FROM_COUNTS.contains(v)).collect();
+ format!("--vars-to-regress {}: not percent.mt, nCount_RNA or nFeature_RNA, so a column of --metadata, but no --metadata table is given", cols.join(","))
+ })?;
+ cov.metadata = Some(cluster::metadata::extra_columns(Path::new(m), barcodes, &[])?);
+ inputs.push(Input::digest("metadata", Path::new(m).parent().unwrap_or(Path::new("")), &[Path::new(m)]).map_err(|e| e.to_string())?);
+ }
+ Ok((cov, inputs))
+}
+
+/// The options left out of the normalised matrices' comment lines' command (M15b): `--metadata`
+/// changes values when its columns are regressed, so it stays in the command then.
+pub fn output_only(params: &ChainParams) -> Vec<&'static str> {
+ OUTPUT_ONLY.iter().copied().filter(|&o| !(o == "metadata" && metadata_regressed(params))).collect()
}
/// The parameters as `summary.json` records them (`run.parameters`).
@@ -175,6 +239,15 @@ pub fn params_json(p: &ChainParams) -> Json {
if let Json::Object(m) = &mut pca {
m.push(("guard_npcs".into(), p.pca_guard.map(|v| Json::Int(v as i64)).unwrap_or(Json::Null)));
}
+ // percent.mt (M15b): only when asked for, so that a run without it records what earlier runs did
+ if let Json::Object(m) = &mut sct {
+ if p.percent_mt {
+ m.push(("percent_mt".into(), Json::Bool(true)));
+ }
+ if let Some(f) = &p.mt_genes {
+ m.push(("mt_genes".into(), Json::Str(f.clone())));
+ }
+ }
Json::obj(vec![
("preset", p.preset.clone().map(Json::Str).unwrap_or(Json::Null)),
("sctransform", sct),
@@ -265,6 +338,9 @@ pub struct Record {
pub metadata: Option,
/// Notes on the scores (`run.stats.note`), such as scores asked for that a route cannot make.
pub stats_note: Vec,
+ /// Warnings about `percent.mt` and the regression (`run.notes`, written only when there are
+ /// some; M15b).
+ pub notes: Vec,
}
/// The input counts of a run from a 10x directory, as the manifest records them: with `export`,
@@ -308,7 +384,7 @@ pub struct Done {
/// counts and calls this; `scrust doubletfinder --recluster` hands over its singlets from memory
/// (M15). `phases` holds the caller's marks so far (`load`); `guard_context` is the PCA guard's
/// (`doubletfinder.R` calls it with "doubletfinder").
-pub fn run_counts(counts: scio::Counts, out: &Path, s: &Settings, mut rec: Record, phases: Phases, guard_context: Option<&'static str>) -> Result {
+pub fn run_counts(counts: scio::Counts, out: &Path, s: &Settings, mut rec: Record, phases: Phases, guard_context: Option<&'static str>, cov: &CellCovariates) -> Result {
if let Some(e) = rec.counts_entries.first_mut() {
*e = e.clone().shape(&[counts.n_features(), counts.n_cells()]).nnz(counts.matrix.nnz());
}
@@ -328,7 +404,11 @@ pub fn run_counts(counts: scio::Counts, out: &Path, s: &Settings, mut rec: Recor
w = w.with_dumps(level);
}
let opts = Options { guard_context, ..s.options() };
- let c = chain::cluster_counts(Cow::Owned(counts), &s.params, s.threads, opts, &mut w).map_err(|e| e.to_string())?;
+ let c = chain::cluster_counts_with(Cow::Owned(counts), &s.params, cov, s.threads, opts, &mut w).map_err(|e| e.to_string())?;
+ for n in &c.notes {
+ eprintln!("scrust cluster: {n}");
+ }
+ rec.notes.extend(c.notes.iter().cloned());
w.write_clustered(&c).map_err(|e| e.to_string())?;
// the stages are written: only the clustering and the scores go on
let r = c.chain;
@@ -376,7 +456,10 @@ pub fn main(argv: &[String]) -> Result<(), String> {
if export && start != "counts" {
return Err("--export needs --counts: the export copies the input counts (counts/) and makes the corrected counts from vst's residuals of every model gene, which only a run from the counts has (scrust sctransform keeps only the variable features' clipped residuals); run scrust cluster --counts --export, or scrust sctransform --corrected-counts for the SCT part alone".into());
}
- let command = scio::manifest::canonical_command("cluster", argv, &OUTPUT_ONLY, &switches);
+ if start != "counts" && params.needs_covariates() {
+ return Err("--vars-to-regress, --mt-genes and --percent-mt act where SCTransform runs: give them to scrust cluster --counts, or to scrust sctransform, whose cell_metadata.tsv carries percent.mt on to scrust pca, scrust neighbors and the staged starts (the regression is in its scale_data.npy)".into());
+ }
+ let command = scio::manifest::canonical_command("cluster", argv, &output_only(¶ms), &switches);
if out.join("summary.json").exists() || out.join("clusters.tsv").exists() {
return Err(format!("{}: holds a previous run; choose another --out", out.display()));
}
@@ -393,6 +476,7 @@ pub fn main(argv: &[String]) -> Result<(), String> {
export_s: 0.0,
metadata: args.get("metadata").map(str::to_string),
stats_note: Vec::new(),
+ notes: Vec::new(),
};
let params = &settings.params;
@@ -406,8 +490,11 @@ pub fn main(argv: &[String]) -> Result<(), String> {
rec.export_s = export_s;
rec.inputs.push(("counts", Json::Str(dir.display().to_string())));
let counts = scio::Counts::read(&dir).map_err(|e| e.to_string())?;
+ // percent.mt's ids and --metadata's regressed columns (M15b), before the chain
+ let (cov, more) = read_covariates(params, args.get("metadata"), &counts.barcodes)?;
+ rec.provenance_inputs.extend(more);
phases.mark("load");
- run_counts(counts, &out, &settings, rec, phases, None)?;
+ run_counts(counts, &out, &settings, rec, phases, None, &cov)?;
return Ok(());
}
"sct" => {
@@ -536,11 +623,17 @@ pub fn finish_run(out: &Path, start: &str, s: &Settings, rec: Record, mut w: Wri
}
if let Some(m) = &rec.metadata {
let mut taken: Vec<&str> = vec!["barcode", "nCount_RNA", "nFeature_RNA", "seurat_clusters", "silhouette_width", "silhouette_other", "neighborhood_purity", "purity_maximum", "nCount_SCT", "nFeature_SCT"];
+ if w.rna.as_ref().is_some_and(|x| x.percent_mt.is_some()) {
+ taken.push(cluster::covariates::PERCENT_MT);
+ }
let cols: Vec = r.clusters.resolutions.iter().map(|x| x.column.name.clone()).collect();
taken.extend(cols.iter().map(String::as_str));
w.extra = Some(cluster::metadata::extra_columns(Path::new(m), &w.barcodes, &taken)?);
inputs.push(("metadata", Json::Str(m.to_string())));
- provenance_inputs.push(Input::digest("metadata", Path::new(m).parent().unwrap_or(Path::new("")), &[Path::new(m)]).map_err(|e| e.to_string())?);
+ // read before the chain when its columns are regressed (M15b): digested once
+ if !provenance_inputs.iter().any(|i| i.option == "metadata") {
+ provenance_inputs.push(Input::digest("metadata", Path::new(m).parent().unwrap_or(Path::new("")), &[Path::new(m)]).map_err(|e| e.to_string())?);
+ }
}
w.finish_labels(&r.clusters, r.silhouette.as_ref(), r.purity.as_ref()).map_err(|e| e.to_string())?;
w.finish_dumps().map_err(|e| e.to_string())?;
@@ -613,7 +706,8 @@ pub fn finish_run(out: &Path, start: &str, s: &Settings, rec: Record, mut w: Wri
let fingerprint = Json::parse(&crate::fingerprint::json()).unwrap_or(Json::Null);
let t = &r.timings;
let result = w.result_json(&r.clusters);
- let summary = Json::obj(vec![
+ let notes = rec.notes;
+ let mut summary = Json::obj(vec![
("tool", Json::Str("scrust cluster".into())),
("reference", Json::Str(format!("{}; {}; {}; {}; bluster 1.20.0 approxSilhouette and neighborPurity (BiocNeighbors 2.4.0, knncolle's KMKNN: searched exhaustively with its arithmetic, with a certificate)", sctransform::REFERENCE, pca::REFERENCE, neighbors::REFERENCE, cluster::REFERENCE))),
("scrust_version", Json::Str(version.into())),
@@ -658,6 +752,14 @@ pub fn finish_run(out: &Path, start: &str, s: &Settings, rec: Record, mut w: Wri
),
("files", files_json),
]);
+ // M15b: the warnings about percent.mt and the regression, only when there are some
+ if !notes.is_empty() {
+ if let Json::Object(m) = &mut summary {
+ if let Some((_, Json::Object(run))) = m.iter_mut().find(|(k, _)| k == "run") {
+ run.push(("notes".into(), Json::strs(¬es)));
+ }
+ }
+ }
write(&out.join("summary.json"), &scio::json::to_file_text(&summary))?;
eprint!("scrust cluster: {} cells; {}", r.n_cells, cluster::output::describe(&r.clusters));
if let Some(p) = r.purity.as_ref().filter(|p| p.computed) {
diff --git a/crates/scrust/src/cmd_doubletfinder.rs b/crates/scrust/src/cmd_doubletfinder.rs
index 81ed233..9819ef8 100644
--- a/crates/scrust/src/cmd_doubletfinder.rs
+++ b/crates/scrust/src/cmd_doubletfinder.rs
@@ -56,8 +56,9 @@ Usage: scrust doubletfinder --counts <10x dir> [--clusters [--cluster-leve
[--pk auto|] [--threads N]
[--cluster-preset workflow] [--cluster-params ]
[--cluster-stats none|silhouette,purity|silhouette|purity]
+ [--cluster-metadata ]
[--recluster [--recluster-preset workflow] [--recluster-params ]
- [--recluster-export]]
+ [--recluster-export] [--recluster-metadata ]]
[--dump-stages none|light|standard|full] [--from-stages ]
DoubletFinder 2.0.6 as the workflow calls it (docs/PLAN.md B1), every stage computed by Rust:
@@ -103,6 +104,14 @@ homotypic adjustment. The counts are read once for both; only the labels are kep
[sctransform], [pca], [neighbors], [cluster], [stats])
--cluster-stats the scores: none (default), silhouette,purity, silhouette or purity
(the file's [stats] compute, when given and this is not)
+ --cluster-metadata scrust cluster's --metadata: a table with a barcode column whose
+ columns clusters/metadata.tsv carries, and which the parameter file's
+ vars_to_regress may name
+ The parameter file's [sctransform] takes SCTransform's vars.to.regress and percent.mt as
+ scrust cluster's does: vars_to_regress = [\"percent.mt\", \"nCount_RNA\", ...] (none by
+ default), percent_mt = true, mt_genes = \"\" (ids, read from the file's directory when
+ relative); see scrust cluster --help. DoubletFinder's own SCTransform runs never regress, as
+ DoubletFinder's R code calls SCTransform.
Writes clusters/: seurat_clusters.tsv and seurat_clusters_levels.txt (the layout --clusters
reads), the other label files and metadata.tsv (with the scores when asked), and its own
summary.json (the clustering's numbers and manifest), as scrust cluster --counts writes
@@ -120,6 +129,7 @@ from the timings and the command line in its summary.json.
--recluster-params a parameter file, as scrust cluster --params reads it
--recluster-export also the export, as scrust cluster --export writes it (counts/: a
copy of singlets/; sct/: SCTransform's normalised data; README.txt)
+ --recluster-metadata scrust cluster's --metadata for the singlets (by barcode), as above
Outputs: cells.tsv (barcode, pANN and classification of every cell), sweep_stats.tsv (pN, pK,
BCreal), bcmvn.tsv (find.pK's table), summary.json (\"result\": pK and its label as R writes it,
@@ -138,8 +148,9 @@ as stored, in input order, and the input's feature lines. The counts are read ag
const SWITCHES: [&str; 2] = ["recluster", "recluster-export"];
/// The clustering's parameters from `---preset` (default: the file's `preset`, else
-/// `workflow`) and `---params`, with `stats` (a `--stats` value) applied last. Returns the
-/// parameters, the preset applied and the file.
+/// `workflow`) and `---params`, with `stats` (a `--stats` value) applied last; a relative
+/// `mt_genes` in the file is read from its directory (M15b). Returns the parameters, the preset
+/// applied and the file.
fn chain_params_of(args: &Args, prefix: &str, stats: Option<&str>) -> Result<(ChainParams, String, Option), String> {
let file = args.get(&format!("{prefix}-params")).map(str::to_string);
let toml = match &file {
@@ -152,7 +163,8 @@ fn chain_params_of(args: &Args, prefix: &str, stats: Option<&str>) -> Result<(Ch
};
let preset = args.get(&format!("{prefix}-preset")).map(str::to_string).or(file_preset).unwrap_or_else(|| "workflow".into());
let flags: Vec<(String, String)> = stats.map(|s| vec![("stats".to_string(), s.to_string())]).unwrap_or_default();
- let p = chain_params::build(Some(&preset), toml.as_deref(), &flags).map_err(|e| format!("--{prefix}-preset/--{prefix}-params: {e}"))?;
+ let dir = file.as_deref().map(|f| Path::new(f).parent().unwrap_or(Path::new("")).to_path_buf());
+ let p = chain_params::build_in(Some(&preset), toml.as_deref(), dir.as_deref(), &flags).map_err(|e| format!("--{prefix}-preset/--{prefix}-params: {e}"))?;
Ok((p, preset, file))
}
@@ -164,8 +176,10 @@ fn file_sets_stats(args: &Args, prefix: &str) -> Result {
}
/// The `scrust cluster` command whose values a nested clustering reproduces (its manifest's
-/// `provenance.command`): `--counts --preset
[--params ] [--stats ]
+/// [--metadata ] [--export]`; `--metadata` stays only when its columns are regressed (M15b),
+/// as in `scrust cluster`'s own command.
+fn equivalent_command(counts: &Path, cp: &ChainParams, preset: &str, params: Option<&str>, stats: Option<&str>, metadata: Option<&str>, export: bool) -> String {
let mut a: Vec = vec!["--counts".into(), counts.display().to_string(), "--preset".into(), preset.into()];
if let Some(p) = params {
a.extend(["--params".into(), p.into()]);
@@ -173,12 +187,15 @@ fn equivalent_command(counts: &Path, preset: &str, params: Option<&str>, stats:
if let Some(s) = stats {
a.extend(["--stats".into(), s.into()]);
}
+ if let Some(m) = metadata {
+ a.extend(["--metadata".into(), m.into()]);
+ }
if export {
a.push("--export".into());
}
let mut switches: Vec<&str> = chain_params::PARAM_SWITCHES.to_vec();
switches.extend(["keep-stages", "export"]);
- scio::manifest::canonical_command("cluster", &a, &cmd_cluster::OUTPUT_ONLY, &switches)
+ scio::manifest::canonical_command("cluster", &a, &cmd_cluster::output_only(cp), &switches)
}
/// Marks each stage of an in-process clustering on the command's clock.
@@ -214,7 +231,8 @@ pub fn main(argv: &[String]) -> Result<(), String> {
let args = Args::parse_with_flags(argv, &SWITCHES)?;
args.only(&[
"counts", "clusters", "cluster-levels", "from-stages", "out", "threads", "pcs", "pn", "nexp-rate", "pk", "seed", "dump-stages",
- "cluster-preset", "cluster-params", "cluster-stats", "recluster", "recluster-preset", "recluster-params", "recluster-export",
+ "cluster-preset", "cluster-params", "cluster-stats", "cluster-metadata", "recluster", "recluster-preset", "recluster-params", "recluster-export",
+ "recluster-metadata",
])?;
let phases = RefCell::new(Phases::new());
let start_time = cli::utc_now();
@@ -259,7 +277,7 @@ pub fn main(argv: &[String]) -> Result<(), String> {
// clustering on the fly (C3h): only without --clusters
let on_the_fly = clusters_path.is_none();
if !on_the_fly {
- if let Some(o) = ["cluster-preset", "cluster-params", "cluster-stats"].into_iter().find(|o| args.get(o).is_some()) {
+ if let Some(o) = ["cluster-preset", "cluster-params", "cluster-stats", "cluster-metadata"].into_iter().find(|o| args.get(o).is_some()) {
return Err(format!("--{o}: clustering on the fly is for runs without --clusters"));
}
} else {
@@ -272,7 +290,7 @@ pub fn main(argv: &[String]) -> Result<(), String> {
}
let recluster = args.flag("recluster");
if !recluster {
- if let Some(o) = ["recluster-preset", "recluster-params", "recluster-export"].into_iter().find(|o| args.get(o).is_some()) {
+ if let Some(o) = ["recluster-preset", "recluster-params", "recluster-export", "recluster-metadata"].into_iter().find(|o| args.get(o).is_some()) {
return Err(format!("--{o} goes with --recluster"));
}
}
@@ -302,6 +320,8 @@ pub fn main(argv: &[String]) -> Result<(), String> {
// the input: the counts, and the labels given or computed
let mut hook_result: Option = None;
+ // what clustering on the fly read for percent.mt and vars.to.regress (M15b), for its provenance
+ let mut hook_inputs: Vec = Vec::new();
let (input, levels_described, matrix) = match &clusters_path {
Some(cp) => {
let (input, levels) = read_input(&counts, cp, args.get("cluster-levels").map(Path::new)).map_err(|e| e.to_string())?;
@@ -315,7 +335,13 @@ pub fn main(argv: &[String]) -> Result<(), String> {
// the chain borrows the counts, which DoubletFinder reads next; it keeps the labels
// (and the scores when asked) and frees each stage once the next has what it needs
let mut marks = Marks { phases: &phases, prefix: "clustering: " };
- let clustered = chain::cluster_counts(Cow::Borrowed(&c), hp, threads, Options::default(), &mut marks).map_err(|e| format!("clustering on the fly: {e}"))?;
+ // percent.mt's ids and --cluster-metadata's regressed columns (M15b)
+ let (cov, more) = cmd_cluster::read_covariates(hp, args.get("cluster-metadata"), &c.barcodes).map_err(|e| format!("clustering on the fly: {e}"))?;
+ hook_inputs = more;
+ let clustered = chain::cluster_counts_with(Cow::Borrowed(&c), hp, &cov, threads, Options::default(), &mut marks).map_err(|e| format!("clustering on the fly: {e}"))?;
+ for n in &clustered.notes {
+ eprintln!("scrust doubletfinder: clustering on the fly: {n}");
+ }
let f = clustered.labels();
let scio::Counts { matrix, barcodes, feature_lines } = c;
let input = Input { barcodes, clusters: f.label_strings(), cluster_levels: f.levels.clone(), n_genes: feature_lines.len() };
@@ -337,16 +363,19 @@ pub fn main(argv: &[String]) -> Result<(), String> {
if let (Some(c), Some((hp, preset, file, stats))) = (hook_result.take(), &hook) {
let dir = out.join(CLUSTERS);
let s = Settings { params: hp.clone(), threads, keep: false, export: false, dumps: None, purity_lists: false, annoy: false };
+ let mut provenance_inputs = vec![counts_prov.get_or_insert(counts_digest()?).clone()];
+ provenance_inputs.append(&mut hook_inputs);
let rec = Record {
command_line: cli::command_line("doubletfinder", argv),
- command: equivalent_command(&counts, preset, file.as_deref(), stats.as_deref(), false),
+ command: equivalent_command(&counts, hp, preset, file.as_deref(), stats.as_deref(), args.get("cluster-metadata"), false),
start_time: start_time.clone(),
inputs: vec![("counts", Json::Str(counts.display().to_string()))],
- provenance_inputs: vec![counts_prov.get_or_insert(counts_digest()?).clone()],
+ provenance_inputs,
counts_entries: Vec::new(),
export_s: 0.0,
- metadata: None,
+ metadata: args.get("cluster-metadata").map(str::to_string),
stats_note: Vec::new(),
+ notes: c.notes.clone(),
};
phases.borrow_mut().mark("clustering: digest");
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
@@ -425,20 +454,25 @@ pub fn main(argv: &[String]) -> Result<(), String> {
(ProvInput { option: "counts".into(), path: sdir.display().to_string(), files }, Vec::new(), 0.0)
};
let s = Settings { params: rp.clone(), threads, keep: false, export: *export, dumps: None, purity_lists: false, annoy: false };
+ // percent.mt's ids and --recluster-metadata's regressed columns, for the singlets (M15b)
+ let (cov, more) = cmd_cluster::read_covariates(rp, args.get("recluster-metadata"), &singlets.barcodes).map_err(|e| format!("re-clustering the singlets: {e}"))?;
+ let mut provenance_inputs = vec![input];
+ provenance_inputs.extend(more);
let rec = Record {
command_line: cli::command_line("doubletfinder", argv),
- command: equivalent_command(&sdir, preset, file.as_deref(), None, *export),
+ command: equivalent_command(&sdir, rp, preset, file.as_deref(), None, args.get("recluster-metadata"), *export),
start_time: cli::utc_now(),
inputs: vec![("counts", Json::Str(sdir.display().to_string()))],
- provenance_inputs: vec![input],
+ provenance_inputs,
counts_entries: entries,
export_s,
- metadata: None,
+ metadata: args.get("recluster-metadata").map(str::to_string),
stats_note: Vec::new(),
+ notes: Vec::new(),
};
let mut p = Phases::new();
p.mark("load");
- let d = cmd_cluster::run_counts(singlets, &rdir, &s, rec, p, Some("doubletfinder")).map_err(|e| format!("re-clustering the singlets: {e}"))?;
+ let d = cmd_cluster::run_counts(singlets, &rdir, &s, rec, p, Some("doubletfinder"), &cov).map_err(|e| format!("re-clustering the singlets: {e}"))?;
// the re-clustering's own phases, on this command's clock
let offset = d.started.saturating_duration_since(phases.started()).as_secs_f64();
for (name, t, rss) in &d.phases {
@@ -468,26 +502,29 @@ pub fn main(argv: &[String]) -> Result<(), String> {
("pK", pk_text),
];
if let Some((hp, preset, file, stats)) = &hook {
- parameters.push((
- "clustering",
- Json::obj(vec![
- ("preset", Json::Str(preset.clone())),
- ("params_file", file.clone().map(Json::Str).unwrap_or(Json::Null)),
- ("stats", stats.clone().map(Json::Str).unwrap_or(Json::Null)),
- ("parameters", cmd_cluster::params_json(hp)),
- ]),
- ));
+ let mut items = vec![
+ ("preset", Json::Str(preset.clone())),
+ ("params_file", file.clone().map(Json::Str).unwrap_or(Json::Null)),
+ ("stats", stats.clone().map(Json::Str).unwrap_or(Json::Null)),
+ ("parameters", cmd_cluster::params_json(hp)),
+ ];
+ // M15b: only when given, so that runs without it record what earlier runs did
+ if let Some(m) = args.get("cluster-metadata") {
+ items.push(("metadata", Json::Str(m.into())));
+ }
+ parameters.push(("clustering", Json::obj(items)));
}
if let Some((rp, preset, file, export)) = &re {
- parameters.push((
- "recluster",
- Json::obj(vec![
- ("preset", Json::Str(preset.clone())),
- ("params_file", file.clone().map(Json::Str).unwrap_or(Json::Null)),
- ("export", Json::Bool(*export)),
- ("parameters", cmd_cluster::params_json(rp)),
- ]),
- ));
+ let mut items = vec![
+ ("preset", Json::Str(preset.clone())),
+ ("params_file", file.clone().map(Json::Str).unwrap_or(Json::Null)),
+ ("export", Json::Bool(*export)),
+ ("parameters", cmd_cluster::params_json(rp)),
+ ];
+ if let Some(m) = args.get("recluster-metadata") {
+ items.push(("metadata", Json::Str(m.into())));
+ }
+ parameters.push(("recluster", Json::obj(items)));
}
let parameters = Json::obj(parameters);
let mut reproduces = vec![doubletfinder::REFERENCE, sctransform::REFERENCE, pca::REFERENCE];
@@ -552,7 +589,12 @@ pub fn main(argv: &[String]) -> Result<(), String> {
inputs.push(ProvInput::digest("cluster-levels", l.parent().unwrap_or(Path::new("")), &[l.as_path()]).map_err(|e| e.to_string())?);
}
}
- for (option, file) in [("cluster-params", args.get("cluster-params")), ("recluster-params", args.get("recluster-params"))] {
+ for (option, file) in [
+ ("cluster-params", args.get("cluster-params")),
+ ("recluster-params", args.get("recluster-params")),
+ ("cluster-metadata", args.get("cluster-metadata")),
+ ("recluster-metadata", args.get("recluster-metadata")),
+ ] {
if let Some(f) = file {
let p = Path::new(f);
inputs.push(ProvInput::digest(option, p.parent().unwrap_or(Path::new("")), &[p]).map_err(|e| e.to_string())?);
diff --git a/crates/scrust/src/cmd_neighbors.rs b/crates/scrust/src/cmd_neighbors.rs
index 44a4480..b3f2f8e 100644
--- a/crates/scrust/src/cmd_neighbors.rs
+++ b/crates/scrust/src/cmd_neighbors.rs
@@ -170,7 +170,7 @@ pub fn main(argv: &[String]) -> Result<(), String> {
m.push(Manifest::summary_entry());
m.entries.extend(neighbors::output::manifest_entries("", r.n, Some((r.nn.nnz(), r.snn.nnz())), write_annoy, None));
if out.join(cluster::metadata::FILE).is_file() {
- m.push(crate::cmd_sctransform::rna_entry(cluster::metadata::FILE, r.n));
+ m.push(crate::cmd_sctransform::rna_entry_of(&out, cluster::metadata::FILE, r.n));
}
m.fill_shapes(&out).map_err(|e| e.to_string())?;
let files = cli::finish_manifest(&out, &mut m, threads)?;
diff --git a/crates/scrust/src/cmd_pca.rs b/crates/scrust/src/cmd_pca.rs
index ec0b2c9..1a6be20 100644
--- a/crates/scrust/src/cmd_pca.rs
+++ b/crates/scrust/src/cmd_pca.rs
@@ -95,7 +95,7 @@ pub fn main(argv: &[String]) -> Result<(), String> {
m.push(Manifest::summary_entry());
m.entries.extend(pca::output::manifest_entries(""));
if out.join(cluster::metadata::FILE).is_file() {
- m.push(crate::cmd_sctransform::rna_entry(cluster::metadata::FILE, nc));
+ m.push(crate::cmd_sctransform::rna_entry_of(&out, cluster::metadata::FILE, nc));
}
m.fill_shapes(&out).map_err(|e| e.to_string())?;
let files = cli::finish_manifest(&out, &mut m, threads)?;
diff --git a/crates/scrust/src/cmd_sctransform.rs b/crates/scrust/src/cmd_sctransform.rs
index 92e96dd..6fce18f 100644
--- a/crates/scrust/src/cmd_sctransform.rs
+++ b/crates/scrust/src/cmd_sctransform.rs
@@ -1,20 +1,33 @@
//! `scrust sctransform`: SCTransform v2 as Seurat 5.5.1's `SCTransform()` runs it with its
//! defaults (docs/PLAN.md B3a, milestone M4), on a 10x counts directory; with
//! `--corrected-counts`, also the SCT assay's corrected counts and their `log1p` (C3f, M13): the
-//! SCT part of `scrust cluster --export`.
+//! SCT part of `scrust cluster --export`. With `--vars-to-regress` (M15b), SCTransform's second
+//! regression of `scale.data`, and with it, `--mt-genes` or `--percent-mt`, the workflow's
+//! `percent.mt` in `cell_metadata.tsv`.
use crate::cli::{self, Args, Phases};
+use cluster::chain_params::ChainParams;
use rcompat::RRng;
use scio::manifest::{Entry, Ids, Input, Manifest, Provenance};
use scio::{tenx, Json};
use std::path::Path;
-/// The manifest's entry for `cell_metadata.tsv` (the counts' per-cell columns, M11), at `path`.
-pub fn rna_entry(path: &str, ncells: usize) -> Entry {
- Entry::new(path, "rna_cell_metadata", "none", "tsv", "the counts' per-cell columns, as CreateSeuratObject computes them: barcode, nCount_RNA, nFeature_RNA")
- .header(true)
- .shape(&[ncells, 3])
- .rows(Ids::named("cells", path, "barcode"))
+/// The manifest's entry for `cell_metadata.tsv` (the counts' per-cell columns, M11), at `path`,
+/// with `ncols` columns: 3, or 4 with `percent.mt` (M15b).
+pub fn rna_entry(path: &str, ncells: usize, ncols: usize) -> Entry {
+ let what = if ncols == 4 {
+ "the counts' per-cell columns, as CreateSeuratObject computes them, and percent.mt (PercentageFeatureSet of the mitochondrial features, as the workflow's scripts compute it before SCTransform; summary.json's result.percent_mt says which): barcode, nCount_RNA, nFeature_RNA, percent.mt"
+ } else {
+ "the counts' per-cell columns, as CreateSeuratObject computes them: barcode, nCount_RNA, nFeature_RNA"
+ };
+ Entry::new(path, "rna_cell_metadata", "none", "tsv", what).header(true).shape(&[ncells, ncols]).rows(Ids::named("cells", path, "barcode"))
+}
+
+/// [`rna_entry`] for a `cell_metadata.tsv` carried forward into `dir` (`scrust pca`, `scrust
+/// neighbors`), its columns read from its header.
+pub fn rna_entry_of(dir: &Path, path: &str, ncells: usize) -> Entry {
+ let ncols = std::fs::read_to_string(dir.join(path)).ok().and_then(|t| t.lines().next().map(|h| h.split('\t').count())).unwrap_or(3);
+ rna_entry(path, ncells, ncols)
}
/// What README.txt says first about the SCT part (`scrust sctransform --corrected-counts`, and
@@ -30,6 +43,8 @@ pub fn readme_intro() -> Vec {
pub const USAGE: &str = "\
Usage: scrust sctransform --counts <10x dir> --out [--threads N] [--seed 1448145]
[--variable-features 3000] [--ncells 5000] [--corrected-counts]
+ [--vars-to-regress [,...]] [--percent-mt]
+ [--mt-genes ] [--metadata ]
[--from-stages --context ]
SCTransform v2 as Seurat 5.5.1's SCTransform() runs it with its defaults: sctransform 0.4.3's
@@ -47,6 +62,22 @@ and scale.data, computed as R computes them (bit for bit under the same OpenBLAS
--corrected-counts also the corrected counts of sctransform's correct() (Seurat's SCT
counts layer, do.correct.umi = TRUE) and their log1p (its data
layer): the SCT part of scrust cluster --export, never in 10x layout
+ --vars-to-regress vars.to.regress (default: none): the per-cell covariates the second
+ regression removes from scale.data before it is centred (ScaleData's
+ RegressOutMatrix, lm's LINPACK QR through OpenBLAS): percent.mt,
+ nCount_RNA, nFeature_RNA, or numeric columns of --metadata (read as
+ R reads numbers), comma-separated, in the formula's order
+ --percent-mt compute percent.mt (PercentageFeatureSet) without regressing it:
+ cell_metadata.tsv's 4th column (implied by --mt-genes and by
+ regressing it); scrust pca, neighbors and cluster carry it
+ --mt-genes percent.mt's mitochondrial features by id (column 1 of features.tsv):
+ one id per line, blank lines and lines starting with # skipped; ids
+ not found are reported and skipped, none found is an error. Without
+ it: the workflow's \"(?i)^mt-\" on Seurat's row names (column 2 made
+ unique, _ and | replaced by -). Regressing percent.mt when no feature
+ matches is an error that names --mt-genes
+ --metadata a table with a barcode column (else the first), whose numeric columns
+ --vars-to-regress may name
--from-stages with --context: run on the SCT input of one DoubletFinder context
--context (sweep_pN or final) of an instrumented R run, built from the
counts and the run's draws (S1): the real cells, then the doublets
@@ -62,8 +93,11 @@ Outputs:
variable_features.tsv id and name of the variable features, highest residual variance first
scale_data.npy scale.data: variable features x cells, float64, column-major (R's
layout; NumPy reads it with its shape)
- cell_metadata.tsv barcode, nCount_RNA, nFeature_RNA (CreateSeuratObject's columns)
- summary.json parameters, sizes, min_variance, bandwidth, timings, peak memory,
+ cell_metadata.tsv barcode, nCount_RNA, nFeature_RNA (CreateSeuratObject's columns), and
+ percent.mt when asked for
+ summary.json parameters, sizes, min_variance, bandwidth (with the regression and
+ percent.mt's definition, features and ids not found, when asked for),
+ timings, peak memory,
and the manifest (files): every file's role, scale, shape and
checksum, and how the output was made (docs/output_manifest.md)
With --corrected-counts, also (none of them raw counts, none under a 10x name):
@@ -79,6 +113,22 @@ Doubles are written with 17 significant digits.
/// normalised matrices' comment lines give, so that the files do not depend on them.
const OUTPUT_ONLY: [&str; 2] = ["out", "threads"];
+/// The parameters as `summary.json` and the manifest record them: SCTransform's (with
+/// `vars_to_regress` when set), and `percent_mt` and `mt_genes` when given (M15b), so that a run
+/// without them records what earlier runs did.
+fn params_json(cp: &ChainParams) -> Json {
+ let mut j = sctransform::output::params_json(&cp.sct);
+ if let Json::Object(m) = &mut j {
+ if cp.percent_mt {
+ m.push(("percent_mt".into(), Json::Bool(true)));
+ }
+ if let Some(f) = &cp.mt_genes {
+ m.push(("mt_genes".into(), Json::Str(f.clone())));
+ }
+ }
+ j
+}
+
fn write(path: &Path, text: &str) -> Result<(), String> {
std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
@@ -86,12 +136,22 @@ fn write(path: &Path, text: &str) -> Result<(), String> {
pub fn main(argv: &[String]) -> Result<(), String> {
let mut phases = Phases::new();
let start_time = cli::utc_now();
- let args = Args::parse_with_flags(argv, &["corrected-counts"])?;
- args.only(&["counts", "out", "threads", "seed", "variable-features", "ncells", "from-stages", "context", "corrected-counts"])?;
+ let args = Args::parse_with_flags(argv, &["corrected-counts", "percent-mt"])?;
+ args.only(&["counts", "out", "threads", "seed", "variable-features", "ncells", "from-stages", "context", "corrected-counts", "vars-to-regress", "percent-mt", "mt-genes", "metadata"])?;
let correct = args.flag("corrected-counts");
if correct && args.get("from-stages").is_some() {
return Err("--corrected-counts: from the counts only, not with --from-stages".into());
}
+ // vars.to.regress and percent.mt (M15b), through the chain's parameters and rules
+ let mut flags: Vec<(String, String)> = Vec::new();
+ for name in ["vars-to-regress", "mt-genes"] {
+ if let Some(v) = args.get(name) {
+ flags.push((name.to_string(), v.to_string()));
+ }
+ }
+ if args.flag("percent-mt") {
+ flags.push(("percent-mt".to_string(), String::new()));
+ }
let counts_dir = args.path("counts")?;
let out = args.path("out")?;
let threads = cli::threads(&args)?;
@@ -100,6 +160,18 @@ pub fn main(argv: &[String]) -> Result<(), String> {
params.variable_features_n = Some(args.number("variable-features", 3000usize)?);
params.ncells = args.number("ncells", 5000usize)?;
params.check()?;
+ let cp = {
+ let mut c = cluster::chain_params::build(None, None, &flags)?;
+ c.sct = sctransform::SctParams { vars_to_regress: c.sct.vars_to_regress.clone(), ..params.clone() };
+ c
+ };
+ params = cp.sct.clone();
+ if cp.needs_covariates() && args.get("from-stages").is_some() {
+ return Err("--vars-to-regress, --mt-genes and --percent-mt: from the counts only, not with --from-stages".into());
+ }
+ if args.get("metadata").is_some() && !crate::cmd_cluster::metadata_regressed(&cp) {
+ return Err("--metadata: scrust sctransform reads it only for the columns --vars-to-regress names (scrust cluster carries a table's columns into metadata.tsv)".into());
+ }
if out.join("summary.json").exists() || out.join("gene_attr.tsv").exists() {
return Err(format!("{}: holds a previous run; choose another --out", out.display()));
}
@@ -130,10 +202,28 @@ pub fn main(argv: &[String]) -> Result<(), String> {
};
phases.mark("load");
+ // percent.mt and the covariates (M15b): computed from the counts before SCTransform, as the
+ // workflow's scripts do, and handed to it in memory
+ let mut rna = cluster::metadata::RnaMetadata::of(&counts);
+ let mut percent_mt = None;
+ let mut regression = None;
+ if cp.needs_covariates() {
+ let (cov, more) = crate::cmd_cluster::read_covariates(&cp, args.get("metadata"), &barcodes)?;
+ inputs.extend(more);
+ let lines = tenx::read_lines(&tenx::find(&counts_dir, "features.tsv").map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
+ let c = scio::Counts::new(counts, barcodes.clone(), lines).map_err(|e| e.to_string())?;
+ let (pm, reg, notes) = cluster::chain::covariates_for(&c, &cp, &cov, &mut rna).map_err(|e| e.to_string())?;
+ for n in ¬es {
+ eprintln!("scrust sctransform: {n}");
+ }
+ counts = c.matrix;
+ percent_mt = pm.map(|p| (p, notes));
+ regression = reg;
+ }
// SCTransform seeds R's generator (set.seed(seed.use)) before it draws anything
let mut rng = RRng::new(params.seed_use.unwrap_or(1448145));
let started = sctransform::start(&counts, ¶ms, &mut rng).map_err(|e| e.to_string())?;
- let sct = sctransform::finish_with(started, ¶ms, &mut rng, false, correct, threads).map_err(|e| e.to_string())?;
+ let sct = sctransform::finish_full(started, ¶ms, &mut rng, false, correct, regression, threads).map_err(|e| e.to_string())?;
phases.mark("sctransform");
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
@@ -142,9 +232,9 @@ pub fn main(argv: &[String]) -> Result<(), String> {
// the counts' per-cell metadata (CreateSeuratObject's nCount_RNA and nFeature_RNA), which
// `scrust pca` and `scrust neighbors` carry forward for `scrust cluster` (M11)
if context.is_none() {
- cluster::metadata::RnaMetadata::of(&counts).write(&out.join(cluster::metadata::FILE), &barcodes).map_err(|e| e.to_string())?;
+ rna.write(&out.join(cluster::metadata::FILE), &barcodes).map_err(|e| e.to_string())?;
}
- let command = scio::manifest::canonical_command("sctransform", argv, &OUTPUT_ONLY, &["corrected-counts"]);
+ let command = scio::manifest::canonical_command("sctransform", argv, &OUTPUT_ONLY, &["corrected-counts", "percent-mt"]);
if let Some(c) = &sct.corrected {
let names: Vec = sct.setup.genes.iter().map(|&g| features[g].name.clone()).collect();
let (cc, dc) = sctransform::output::corrected_comments(&command, &cli::input_checksums(&inputs), c);
@@ -162,14 +252,14 @@ pub fn main(argv: &[String]) -> Result<(), String> {
command,
inputs,
reproduces: vec![sctransform::REFERENCE.into()],
- parameters: sctransform::output::params_json(¶ms),
+ parameters: params_json(&cp),
seeds: Json::obj(vec![("SCTransform seed.use", params.seed_use.map(|v| Json::Int(v as i64)).unwrap_or(Json::Null))]),
},
);
m.push(Manifest::summary_entry());
m.entries.extend(sctransform::output::manifest_entries("", counts.ncol, s.genes.len(), s.genes_step1.len(), sct.residuals.top_features.len(), sct.corrected.as_ref()));
if context.is_none() {
- m.push(rna_entry(cluster::metadata::FILE, counts.ncol));
+ m.push(rna_entry(cluster::metadata::FILE, counts.ncol, rna.n_columns()));
}
if sct.corrected.is_some() {
m.push(Entry::new("README.txt", "readme", "none", "text", "this file: what each file holds and how to load it"));
@@ -181,12 +271,17 @@ pub fn main(argv: &[String]) -> Result<(), String> {
let fingerprint = Json::parse(&crate::fingerprint::json()).unwrap_or(Json::Null);
let s = &sct.setup;
let nr = sct.residuals.top_features.len();
- let summary = Json::obj(vec![
+ let mut result = sctransform::output::result_json(&sct, counts.nrow);
+ // percent.mt's record (M15b), as scrust cluster's result.sctransform holds it
+ if let (Json::Object(m), Some((p, _))) = (&mut result, &percent_mt) {
+ m.push(("percent_mt".into(), p.record_json()));
+ }
+ let mut summary = Json::obj(vec![
("tool", Json::Str("scrust sctransform".into())),
("reference", Json::Str(sctransform::REFERENCE.into())),
("scrust_version", Json::Str(env!("CARGO_PKG_VERSION").into())),
- ("parameters", sctransform::output::params_json(¶ms)),
- ("result", sctransform::output::result_json(&sct, counts.nrow)),
+ ("parameters", params_json(&cp)),
+ ("result", result),
(
"run",
Json::obj(vec![
@@ -205,6 +300,21 @@ pub fn main(argv: &[String]) -> Result<(), String> {
),
("files", files),
]);
+ // the warnings about percent.mt and the regression (M15b), only when there are some
+ let mut notes: Vec = percent_mt.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
+ if let Some(r) = &sct.regression {
+ let (rank, p) = r.rank();
+ if rank < p && notes.iter().all(|n| !n.starts_with("vars.to.regress")) {
+ notes.push(format!("vars.to.regress: the model matrix has rank {rank} of {p}"));
+ }
+ }
+ if !notes.is_empty() {
+ if let Json::Object(m) = &mut summary {
+ if let Some((_, Json::Object(run))) = m.iter_mut().find(|(k, _)| k == "run") {
+ run.push(("notes".into(), Json::strs(¬es)));
+ }
+ }
+ }
write(&out.join("summary.json"), &scio::json::to_file_text(&summary))?;
eprintln!(
"scrust sctransform: {} cells, {} of {} genes kept, {} variable features; {:.1} s, {} threads",
diff --git a/crates/scrust/tests/cli.rs b/crates/scrust/tests/cli.rs
index 15dfbe1..db01b9c 100644
--- a/crates/scrust/tests/cli.rs
+++ b/crates/scrust/tests/cli.rs
@@ -525,7 +525,9 @@ fn cluster_parameters_and_refusals() {
};
refused(&["--nn-method", "rann"], "only Annoy");
refused(&["--l2-norm", "true"], "l2.norm");
- refused(&["--vars-to-regress", "percent.mt"], "vars.to.regress");
+ // vars.to.regress is ported (M15b); percent.mt by the workflow's pattern on the test data, which
+ // has no mitochondrial gene, is refused with its remedy
+ refused(&["--vars-to-regress", "percent.mt"], "--mt-genes");
refused(&["--algorithm", "4"], "Leiden");
refused(&["--preset", "fast"], "unknown preset");
refused(&["--pca", "x"], "give one starting point");
diff --git a/crates/scrust/tests/m15b.rs b/crates/scrust/tests/m15b.rs
new file mode 100644
index 0000000..ac8c1c4
--- /dev/null
+++ b/crates/scrust/tests/m15b.rs
@@ -0,0 +1,473 @@
+//! Milestone M15b (docs/PLAN.md C3, "vars.to.regress and percent.mt"): SCTransform's
+//! `vars.to.regress` and the workflow's `percent.mt`, end to end.
+//!
+//! - **Against R** (the fixtures' kernel only): `scrust cluster --counts` with the cases of
+//! validation/m15b_cases.tsv on two tier-T objects (a v5 object and the emptyDrops object's v3
+//! path) gives the labels and levels, the silhouette widths, the purities, `percent.mt`, the
+//! regressed column's bits, `scale.data` (R's digest) and the regression's rank and pivot of R's
+//! runs (validation/R/reference_clustering.R, portable profile; tests/fixtures/clustering/m15b/).
+//! On the test data, which has no mitochondrial gene, R's `percent.mt` by the pattern is 0 in
+//! every cell: R regresses it through `dqrdc2`'s rank-deficient path (rank 1), and scrust gives
+//! the same all-zero column through a list of features without counts.
+//! - **The routes** (any kernel): `scrust sctransform` with the options, then `scrust pca`,
+//! `scrust neighbors` and the staged starts, write the files `scrust cluster --counts` writes
+//! with them, `percent.mt` carried in `cell_metadata.tsv`.
+//! - **The in-memory rule:** the entry point called with the covariates in memory, its result
+//! written by the library's writer, gives the command's files.
+//! - **In process:** `scrust doubletfinder` with the options in its parameter files (and
+//! `--recluster-metadata`) gives the two-command route's files, and DoubletFinder's own
+//! SCTransform does not regress.
+//! - **The defaults:** without the options, nothing new is written; and the refusals.
+
+use cluster::chain::{self, Options};
+use cluster::chain_output::Writer;
+use cluster::covariates::{CellCovariates, MtGenes};
+use scio::Json;
+use std::borrow::Cow;
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+
+fn scrust_in(dir: &Path, args: &[&str]) -> Output {
+ Command::new(env!("CARGO_BIN_EXE_scrust")).current_dir(dir).args(args).output().expect("failed to run the scrust binary")
+}
+
+fn ok(dir: &Path, args: &[&str]) -> Output {
+ let o = scrust_in(dir, args);
+ assert!(o.status.success(), "{args:?}: {}", String::from_utf8_lossy(&o.stderr));
+ o
+}
+
+fn fixtures() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures")
+}
+
+/// The committed counts of a tier-T object.
+fn input(object: &str) -> PathBuf {
+ let df = fixtures().join("doubletfinder").join(object).join("input");
+ if df.join("matrix.mtx.gz").is_file() {
+ df
+ } else {
+ fixtures().join("clustering").join(object).join("input")
+ }
+}
+
+fn m15b(object: &str) -> PathBuf {
+ fixtures().join("clustering/m15b").join(object)
+}
+
+fn tmp(name: &str) -> PathBuf {
+ let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("m15b").join(name);
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+fn read_json(p: &Path) -> Json {
+ Json::parse(&std::fs::read_to_string(p).unwrap()).unwrap()
+}
+
+fn table(text: &str) -> (Vec, Vec>) {
+ let mut lines = text.lines();
+ let header = lines.next().unwrap().split('\t').map(String::from).collect();
+ (header, lines.map(|l| l.split('\t').map(String::from).collect()).collect())
+}
+
+fn column(t: &(Vec, Vec>), name: &str) -> Option> {
+ let k = t.0.iter().position(|h| h == name)?;
+ Some(t.1.iter().map(|r| r[k].clone()).collect())
+}
+
+/// Every file under `dir`, by relative path.
+fn tree(dir: &Path) -> BTreeMap {
+ let mut out = BTreeMap::new();
+ let mut todo = vec![dir.to_path_buf()];
+ while let Some(d) = todo.pop() {
+ for e in std::fs::read_dir(&d).unwrap() {
+ let p = e.unwrap().path();
+ if p.is_dir() {
+ todo.push(p);
+ } else {
+ out.insert(p.strip_prefix(dir).unwrap().display().to_string(), p);
+ }
+ }
+ }
+ out
+}
+
+/// The members of `summary.json` that record how a run went, not what it computed.
+const VOLATILE: [&str; 17] = [
+ "start_time", "elapsed_s", "phases", "peak_rss_kib", "printed_elapsed", "sctransform_s", "pca_s", "neighbors_s", "cluster_s", "silhouette_s", "purity_s", "network_s", "resolutions_s",
+ "optimizer_s", "groupsingletons_s", "export_counts_copy_s", "manifest_s",
+];
+
+fn settled(j: &Json, path: &str) -> Json {
+ match j {
+ Json::Object(m) => Json::Object(
+ m.iter()
+ .filter(|(k, _)| !VOLATILE.contains(&k.as_str()) && format!("{path}.{k}") != ".files.provenance.command_line")
+ .map(|(k, v)| (k.clone(), settled(v, &format!("{path}.{k}"))))
+ .collect(),
+ ),
+ Json::List(v) => Json::List(v.iter().map(|x| settled(x, path)).collect()),
+ Json::Vector(v) => Json::Vector(v.iter().map(|x| settled(x, path)).collect()),
+ other => other.clone(),
+ }
+}
+
+/// `summary.json` without the manifest's entries (`files.entries`) and the files written
+/// (`run.files`) under `dirs` (each ending in `/`).
+fn without_entries(j: &Json, dirs: &[&str]) -> Json {
+ let Json::Object(top) = j else { panic!("not an object") };
+ let under = |p: Option<&str>| p.is_some_and(|p| dirs.iter().any(|d| p.starts_with(d)));
+ let filtered = |s: &Json, key: &str| -> Json {
+ let Json::Object(m) = s else { panic!("not an object") };
+ Json::Object(
+ m.iter()
+ .map(|(k, v)| {
+ let keep = |xs: &Vec| -> Vec { xs.iter().filter(|x| !under(x.as_str().or_else(|| x.get("path").and_then(|p| p.as_str())))).cloned().collect() };
+ match v {
+ Json::List(xs) if k == key => (k.clone(), Json::List(keep(xs))),
+ Json::Vector(xs) if k == key => (k.clone(), Json::Vector(keep(xs))),
+ _ => (k.clone(), v.clone()),
+ }
+ })
+ .collect(),
+ )
+ };
+ Json::Object(
+ top.iter()
+ .map(|(k, v)| match k.as_str() {
+ "files" => (k.clone(), filtered(v, "entries")),
+ "run" => (k.clone(), filtered(v, "files")),
+ _ => (k.clone(), v.clone()),
+ })
+ .collect(),
+ )
+}
+
+/// The same files under `a` and `b`, byte for byte, but `summary.json`, compared as JSON without
+/// the timings and the command line (unless listed in `skip_summary`).
+fn assert_same_tree(a: &Path, b: &Path, skip_a: &[&str], skip_b: &[&str], skip_summary: &[&str]) {
+ let keep = |rel: &String, skip: &[&str]| !skip.iter().any(|s| rel == s || (s.ends_with('/') && rel.starts_with(s)));
+ let ta: BTreeMap = tree(a).into_iter().filter(|(k, _)| keep(k, skip_a)).collect();
+ let tb: BTreeMap = tree(b).into_iter().filter(|(k, _)| keep(k, skip_b)).collect();
+ assert_eq!(ta.keys().collect::>(), tb.keys().collect::>(), "{} and {} hold different files", a.display(), b.display());
+ for (rel, pa) in &ta {
+ let pb = &tb[rel];
+ if rel.ends_with("summary.json") {
+ if !skip_summary.contains(&rel.as_str()) {
+ assert_eq!(settled(&read_json(pa), ""), settled(&read_json(pb), ""), "{rel} differs beyond the timings and the command line");
+ }
+ } else {
+ assert!(std::fs::read(pa).unwrap() == std::fs::read(pb).unwrap(), "{rel} differs");
+ }
+ }
+}
+
+/// A case's options for scrust (the R run's, with an all-zero list where R's pattern finds no
+/// feature: validation/m15b_cases.tsv's rust_mt_genes).
+fn case_args(object: &str, case: &str) -> Vec {
+ let i = m15b(object).join("inputs");
+ let p = |f: &str| i.join(f).display().to_string();
+ let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>();
+ match case {
+ "pm" => v(&["--vars-to-regress", "percent.mt", "--mt-genes", &p("zero_genes.txt")]),
+ "ids" => v(&["--vars-to-regress", "percent.mt", "--mt-genes", &p("mt_genes.txt")]),
+ "ids_ncount" => v(&["--vars-to-regress", "percent.mt,nCount_RNA", "--mt-genes", &p("mt_genes.txt")]),
+ "meta" => v(&["--vars-to-regress", "score", "--metadata", &p("metadata.tsv")]),
+ _ => unreachable!(),
+ }
+}
+
+/// R's runs with vars.to.regress (portable profile): the labels, levels, scores, percent.mt, the
+/// regressed column's bits, scale.data's digest and the regression's rank and pivot.
+#[test]
+fn the_regression_against_r() {
+ for object in ["soupx_tenx_test", "filtered_seurat_emptydrops_test"] {
+ for case in ["pm", "ids", "ids_ncount", "meta"] {
+ let r = m15b(object).join(case);
+ rcompat::blas::require_fixture_kernel(&r, "vars.to.regress against R");
+ let d = tmp(&format!("r_{object}_{case}"));
+ let c = input(object).display().to_string();
+ let mut a: Vec = ["cluster", "--counts", &c, "--preset", "workflow", "--out", "run", "--threads", "3"].iter().map(|x| x.to_string()).collect();
+ a.extend(case_args(object, case));
+ ok(&d, &a.iter().map(String::as_str).collect::>());
+ let run = d.join("run");
+ let what = format!("{object} {case}");
+ let rm = table(&String::from_utf8(scio::gz::gunzip(&std::fs::read(r.join("metadata.tsv.gz")).unwrap()).unwrap()).unwrap());
+ let cm = table(&std::fs::read_to_string(run.join("metadata.tsv")).unwrap());
+ for col in ["nCount_RNA", "nFeature_RNA", "percent.mt", "SCT_snn_res.0.8", "seurat_clusters", "silhouette_width", "neighborhood_purity"] {
+ match column(&rm, col) {
+ Some(want) => assert_eq!(column(&cm, col).as_ref(), Some(&want), "{what}: metadata.tsv {col}"),
+ None => assert!(col != "percent.mt" || case == "meta", "{what}: R's run has no {col}"),
+ }
+ }
+ if case == "meta" {
+ // R regressed the doubles read.delim() parsed; scrust carries the table's text and
+ // parses it as R does
+ let (want, got) = (column(&rm, "score").unwrap(), column(&cm, "score").unwrap());
+ for (w, g) in want.iter().zip(&got) {
+ assert_eq!(scio::parse17(w).unwrap().to_bits(), rcompat::as_numeric(g).to_bits(), "{what}: score {g}");
+ }
+ }
+ for f in ["seurat_clusters_levels.txt", "SCT_snn_res.0.8_levels.txt"] {
+ assert_eq!(std::fs::read(r.join(f)).unwrap(), std::fs::read(run.join(f)).unwrap(), "{what}: {f}");
+ }
+ let (rs, cs) = (read_json(&r.join("summary.json")), read_json(&run.join("summary.json")));
+ let (rr, cr) = (rs.get("result").unwrap(), cs.get("result").unwrap());
+ assert_eq!(rr.get("scale_data_sha256"), cr.get("scale_data_sha256"), "{what}: scale.data (R's digest)");
+ let (rg, cg) = (rr.get("regression").unwrap(), cr.get("sctransform").and_then(|s| s.get("regression")).unwrap());
+ assert_eq!(rg.get("rank").and_then(Json::as_f64), cg.get("rank").and_then(Json::as_f64), "{what}: rank");
+ let ints = |j: Option<&Json>| match j {
+ Some(Json::Vector(v) | Json::List(v)) => v.iter().filter_map(Json::as_f64).collect::>(),
+ _ => Vec::new(),
+ };
+ assert_eq!(ints(rg.get("pivot")), ints(cg.get("pivot")), "{what}: pivot");
+ if case == "pm" {
+ // percent.mt 0 in every cell: lm()'s QR drops it (rank 1), as R's does
+ assert_eq!(cg.get("rank").and_then(Json::as_f64), Some(1.0), "{what}: rank-deficient");
+ }
+ }
+ }
+}
+
+/// `scrust sctransform` with the options, then the staged commands, write what `scrust cluster
+/// --counts` writes with them.
+#[test]
+fn the_routes_with_the_regression() {
+ let object = "soupx_tenx_test";
+ let c = input(object).display().to_string();
+ let i = m15b(object).join("inputs");
+ let (mt, md) = (i.join("mt_genes.txt").display().to_string(), i.join("metadata.tsv").display().to_string());
+ for (name, sct_opts, cluster_opts) in [
+ ("pm_ncount", vec!["--vars-to-regress", "percent.mt,nCount_RNA", "--mt-genes", mt.as_str()], vec![]),
+ ("score", vec!["--vars-to-regress", "score", "--percent-mt", "--metadata", md.as_str()], vec!["--metadata", md.as_str()]),
+ ] {
+ let d = tmp(&format!("routes_{name}"));
+ let mut one: Vec<&str> = vec!["cluster", "--counts", &c, "--preset", "workflow", "--out", "one", "--keep-stages", "--threads", "2"];
+ one.extend(&sct_opts);
+ one.extend(&cluster_opts);
+ if name == "score" {
+ // --metadata once: for the regression and for metadata.tsv
+ let k = one.iter().rposition(|a| *a == "--metadata").unwrap();
+ one.drain(k..k + 2);
+ }
+ ok(&d, &one);
+ let mut s: Vec<&str> = vec!["sctransform", "--counts", &c, "--out", "sct", "--seed", "12345", "--threads", "2"];
+ s.extend(&sct_opts);
+ ok(&d, &s);
+ ok(&d, &["pca", "--sct", "sct", "--out", "pca", "--seed", "12345"]);
+ ok(&d, &["neighbors", "--pca", "pca", "--out", "nn", "--dims", "1:30"]);
+ for f in ["sct", "pca", "nn"] {
+ let t = std::fs::read_to_string(d.join(f).join("cell_metadata.tsv")).unwrap();
+ assert!(t.starts_with("barcode\tnCount_RNA\tnFeature_RNA\tpercent.mt\n"), "{name}: {f}/cell_metadata.tsv carries percent.mt");
+ }
+ let mut a: Vec<&str> = vec!["cluster", "--sct", "sct", "--preset", "workflow", "--out", "from_sct", "--keep-stages"];
+ a.extend(&cluster_opts);
+ ok(&d, &a);
+ let mut a: Vec<&str> = vec!["cluster", "--snn", "nn", "--pca", "pca", "--preset", "workflow", "--out", "from_snn"];
+ a.extend(&cluster_opts);
+ ok(&d, &a);
+ let meta = std::fs::read_to_string(d.join("one/metadata.tsv")).unwrap();
+ assert!(meta.starts_with("barcode\tnCount_RNA\tnFeature_RNA\tpercent.mt\tSCT_snn_res.0.8"), "{name}: {}", &meta[..80]);
+ let skip_neighbors = ["summary.json", "stages/", "sct/"];
+ for (other, skip) in [("from_sct", &["summary.json", "stages/"][..]), ("from_snn", &skip_neighbors[..])] {
+ let want: BTreeMap = tree(&d.join("one")).into_iter().filter(|(k, _)| !skip.iter().any(|s| k == s || (s.ends_with('/') && k.starts_with(s)))).collect();
+ let got = tree(&d.join(other));
+ for (k, p) in &want {
+ assert!(got.get(k).map(|q| std::fs::read(q).unwrap()) == Some(std::fs::read(p).unwrap()), "{name}: {other}: {k} differs or is missing");
+ }
+ }
+ // SCTransform's result, its regression and percent.mt's record included, by every route
+ let sct_of = |p: &str| read_json(&d.join(p).join("summary.json")).get("result").and_then(|r| r.get("sctransform")).cloned();
+ let s1 = sct_of("one").unwrap();
+ assert!(s1.get("regression").is_some() && s1.get("percent_mt").is_some(), "{name}");
+ assert_eq!(read_json(&d.join("sct/summary.json")).get("result").cloned(), Some(s1.clone()), "{name}: scrust sctransform's result");
+ assert_eq!(sct_of("from_sct"), Some(s1), "{name}: --sct copies it");
+ }
+}
+
+/// The in-memory rule (A3) with the covariates handed over in memory: the entry point's result,
+/// written by the library's writer, is `scrust cluster --counts`' output.
+#[test]
+fn the_entry_point_regresses_in_memory() {
+ let object = "filtered_seurat_emptydrops_test";
+ let inp = input(object);
+ let i = m15b(object).join("inputs");
+ let d = tmp("in_memory");
+ let (c, mt, md) = (inp.display().to_string(), i.join("mt_genes.txt").display().to_string(), i.join("metadata.tsv").display().to_string());
+ ok(&d, &["cluster", "--counts", &c, "--preset", "workflow", "--export", "--vars-to-regress", "percent.mt,score", "--mt-genes", &mt, "--metadata", &md, "--out", "command", "--threads", "2"]);
+ let cmd_dir = d.join("command");
+ let summary = read_json(&cmd_dir.join("summary.json"));
+ let prov = summary.get("files").and_then(|f| f.get("provenance")).unwrap();
+ // the command reproduces the values: --metadata stays when its columns are regressed
+ let command = prov.get("command").and_then(Json::as_str).unwrap().to_string();
+ assert!(command.contains("--vars-to-regress percent.mt,score") && command.contains("--metadata ") && command.contains("--mt-genes "), "{command}");
+ let options: Vec = match prov.get("inputs") {
+ Some(Json::List(v)) => v.iter().filter_map(|x| x.get("option").and_then(Json::as_str).map(String::from)).collect(),
+ _ => panic!("no inputs"),
+ };
+ assert_eq!(options, ["counts", "mt-genes", "metadata"], "each input once, digested");
+ // in this process: the covariates in memory
+ let params = cluster::chain_params::build(Some("workflow"), None, &[("vars-to-regress".into(), "percent.mt,score".into()), ("mt-genes".into(), mt.clone())]).unwrap();
+ let counts = scio::Counts::read(&inp).unwrap();
+ let sha = scio::sha256::file(Path::new(&mt)).unwrap().1;
+ let cov = CellCovariates {
+ mt_genes: Some(MtGenes::from_file_text(&std::fs::read_to_string(&mt).unwrap(), &mt, &sha)),
+ metadata: Some(cluster::metadata::extra_columns(Path::new(&md), &counts.barcodes, &[]).unwrap()),
+ };
+ let opts = Options { correct: true, keep_reductions: true, keep_sct: true, ..Options::default() };
+ let r = chain::cluster_counts_with(Cow::Owned(counts), ¶ms, &cov, 2, opts, &mut chain::NoObserver).unwrap();
+ assert!(r.notes.iter().any(|n| n.contains("not among the counts' features")), "{:?}", r.notes);
+ let lib_dir = d.join("library");
+ std::fs::create_dir_all(&lib_dir).unwrap();
+ let mut w = Writer::new(&lib_dir, r.cells.clone(), 2);
+ w.write_stages = false;
+ w.export = true;
+ w.command = command;
+ let Some(Json::List(inputs)) = prov.get("inputs") else { panic!() };
+ w.input_checksums = inputs
+ .iter()
+ .flat_map(|i| {
+ let path = PathBuf::from(i.get("path").and_then(Json::as_str).unwrap());
+ let files = match i.get("files") {
+ Some(Json::List(f)) => f.clone(),
+ _ => Vec::new(),
+ };
+ files.into_iter().map(move |f| (f.get("sha256").and_then(Json::as_str).unwrap().to_string(), path.join(f.get("name").and_then(Json::as_str).unwrap()).display().to_string()))
+ })
+ .collect();
+ w.extra = Some(cluster::metadata::extra_columns(Path::new(&md), &r.cells, &["percent.mt"]).unwrap());
+ w.write_clustered(&r).unwrap();
+ w.finish_labels(&r.chain.clusters, r.chain.silhouette.as_ref(), r.chain.purity.as_ref()).unwrap();
+ for (rel, p) in &tree(&lib_dir) {
+ assert!(std::fs::read(p).unwrap() == std::fs::read(cmd_dir.join(rel)).unwrap(), "{rel} differs");
+ }
+ let as_text = |j: &Json| Json::parse(&scio::json::to_file_text(j)).unwrap();
+ assert_eq!(&as_text(&cluster::chain_output::clustered_result_json(&r)), summary.get("result").unwrap(), "summary.json's result");
+}
+
+/// `scrust doubletfinder` with the options in its parameter files: clustering on the fly is
+/// `scrust cluster --counts` with them, the re-clustering the two-command route's, DoubletFinder's
+/// own files those of a run without them.
+#[test]
+fn doubletfinder_in_process_with_the_regression() {
+ let object = "soupx_tenx_test";
+ let inp = input(object).display().to_string();
+ let clusters = input(object).join("seurat_clusters.tsv").display().to_string();
+ let i = m15b(object).join("inputs");
+ let d = tmp("doubletfinder");
+ // parameter files next to the id list, which they name by a relative path
+ std::fs::copy(i.join("mt_genes.txt"), d.join("mt_genes.txt")).unwrap();
+ std::fs::copy(i.join("metadata.tsv"), d.join("metadata.tsv")).unwrap();
+ std::fs::write(d.join("hook.toml"), "[sctransform]\nvars_to_regress = [\"percent.mt\", \"nCount_RNA\"]\nmt_genes = \"mt_genes.txt\"\n").unwrap();
+ std::fs::write(d.join("re.toml"), "[sctransform]\nvars_to_regress = [\"percent.mt\", \"score\"]\nmt_genes = \"mt_genes.txt\"\n").unwrap();
+ for sub in ["hook", "alone", "one", "two", "plain"] {
+ std::fs::create_dir_all(d.join(sub)).unwrap();
+ }
+ let up = |f: &str| format!("../{f}");
+ // clustering on the fly against scrust cluster --counts with the same file
+ ok(&d.join("hook"), &["doubletfinder", "--counts", &inp, "--out", "run", "--cluster-params", &up("hook.toml"), "--cluster-stats", "silhouette,purity", "--threads", "2"]);
+ ok(&d.join("alone"), &["cluster", "--counts", &inp, "--preset", "workflow", "--params", &up("hook.toml"), "--stats", "silhouette,purity", "--out", "run/clusters", "--threads", "2"]);
+ let hook_meta = std::fs::read_to_string(d.join("hook/run/clusters/metadata.tsv")).unwrap();
+ assert!(hook_meta.starts_with("barcode\tnCount_RNA\tnFeature_RNA\tpercent.mt\t"), "{}", &hook_meta[..60]);
+ assert_same_tree(&d.join("hook/run/clusters"), &d.join("alone/run/clusters"), &[], &["pca/", "neighbors/"], &["summary.json"]);
+ let theirs = without_entries(&read_json(&d.join("alone/run/clusters/summary.json")), &["pca/", "neighbors/"]);
+ assert_eq!(settled(&read_json(&d.join("hook/run/clusters/summary.json")), ""), settled(&theirs, ""), "clusters/summary.json");
+ // DoubletFinder's own SCTransform does not regress: its files are a run given the hook's labels
+ let labels = d.join("hook/run/clusters/seurat_clusters.tsv").display().to_string();
+ ok(&d.join("plain"), &["doubletfinder", "--counts", &inp, "--clusters", &labels, "--out", "run", "--threads", "2"]);
+ for f in ["cells.tsv", "sweep_stats.tsv", "bcmvn.tsv", "singlets/matrix.mtx.gz"] {
+ assert!(std::fs::read(d.join("hook/run").join(f)).unwrap() == std::fs::read(d.join("plain/run").join(f)).unwrap(), "{f}");
+ }
+ // the re-clustering in process, a --metadata column regressed, against the two commands
+ ok(&d.join("one"), &["doubletfinder", "--counts", &inp, "--clusters", &clusters, "--out", "run", "--recluster", "--recluster-params", &up("re.toml"), "--recluster-metadata", &up("metadata.tsv"), "--threads", "2"]);
+ ok(&d.join("two"), &["doubletfinder", "--counts", &inp, "--clusters", &clusters, "--out", "run", "--threads", "3"]);
+ ok(&d.join("two"), &["cluster", "--counts", "run/singlets", "--preset", "workflow", "--params", &up("re.toml"), "--metadata", &up("metadata.tsv"), "--out", "run/singlets_clusters", "--threads", "2"]);
+ assert_same_tree(&d.join("one/run/singlets_clusters"), &d.join("two/run/singlets_clusters"), &[], &[], &[]);
+ assert_same_tree(&d.join("one/run"), &d.join("two/run"), &["singlets_clusters/"], &["singlets_clusters/"], &["summary.json"]);
+ let s = read_json(&d.join("one/run/singlets_clusters/summary.json"));
+ let cmd = s.get("files").and_then(|f| f.get("provenance")).and_then(|p| p.get("command")).and_then(Json::as_str).unwrap().to_string();
+ assert_eq!(cmd, "scrust cluster --counts run/singlets --preset workflow --params ../re.toml --metadata ../metadata.tsv", "the command whose values it reproduces");
+ let meta = std::fs::read_to_string(d.join("one/run/singlets_clusters/metadata.tsv")).unwrap();
+ assert!(meta.starts_with("barcode\tnCount_RNA\tnFeature_RNA\tpercent.mt\t") && meta.lines().next().unwrap().ends_with("\tscore\tlabel"), "{}", meta.lines().next().unwrap());
+ for dir in ["hook/run", "one/run"] {
+ let v = scrust_in(&d, &["validate", "manifest", "--dir", dir]);
+ assert!(v.status.success(), "{dir}: {}", String::from_utf8_lossy(&v.stderr));
+ }
+}
+
+/// Without the new options nothing new is written; with --percent-mt alone only percent.mt is
+/// added; and what is refused.
+#[test]
+fn the_defaults_and_the_refusals() {
+ let object = "soupx_tenx_test";
+ let c = input(object).display().to_string();
+ let i = m15b(object).join("inputs");
+ let d = tmp("defaults");
+ ok(&d, &["cluster", "--counts", &c, "--preset", "workflow", "--out", "plain", "--threads", "2"]);
+ ok(&d, &["cluster", "--counts", &c, "--preset", "workflow", "--out", "empty", "--vars-to-regress", "", "--threads", "2"]);
+ let o = ok(&d, &["cluster", "--counts", &c, "--preset", "workflow", "--out", "pm", "--percent-mt", "--threads", "2"]);
+ assert!(String::from_utf8_lossy(&o.stderr).contains("percent.mt is 0 in every cell; give the mitochondrial genes' ids with --mt-genes"));
+ let plain = read_json(&d.join("plain/summary.json"));
+ let text = std::fs::read_to_string(d.join("plain/summary.json")).unwrap();
+ for key in ["\"regression\"", "\"percent_mt\"", "\"notes\"", "\"vars_to_regress\"", "\"mt_genes\""] {
+ assert!(!text.contains(key), "a run without the options records {key}");
+ }
+ assert!(std::fs::read_to_string(d.join("plain/metadata.tsv")).unwrap().starts_with("barcode\tnCount_RNA\tnFeature_RNA\tSCT_snn_res.0.8\t"));
+ // an empty list is no regression: the same files, and the same result
+ assert_same_tree(&d.join("plain"), &d.join("empty"), &[], &[], &["summary.json"]);
+ assert_eq!(plain.get("result"), read_json(&d.join("empty/summary.json")).get("result"));
+ // percent.mt alone: the scale.data and every file but metadata.tsv (its column) are the same
+ assert_same_tree(&d.join("plain"), &d.join("pm"), &["metadata.tsv", "summary.json"], &["metadata.tsv", "summary.json"], &[]);
+ let pm = read_json(&d.join("pm/summary.json"));
+ assert_eq!(plain.get("result").and_then(|r| r.get("scale_data_sha256")), pm.get("result").and_then(|r| r.get("scale_data_sha256")));
+ let rec = pm.get("result").and_then(|r| r.get("sctransform")).and_then(|s| s.get("percent_mt")).unwrap();
+ assert_eq!(rec.get("definition").and_then(Json::as_str), Some("pattern"));
+ assert_eq!(rec.get("n_features").and_then(Json::as_f64), Some(0.0));
+ let t = table(&std::fs::read_to_string(d.join("pm/metadata.tsv")).unwrap());
+ assert!(column(&t, "percent.mt").unwrap().iter().all(|v| v == "0"), "zeros, as computed");
+ // refusals
+ let md = i.join("metadata.tsv").display().to_string();
+ let mt = i.join("mt_genes.txt").display().to_string();
+ let bad_md = d.join("bad.tsv");
+ std::fs::write(&bad_md, "barcode\tgappy\n").unwrap();
+ let feature = scio::tenx::read_features(&input(object)).unwrap().into_iter().map(|f| f.name).find(|n| cluster::covariates::is_syntactic(n)).unwrap();
+ let nope = d.join("nope.txt");
+ std::fs::write(&nope, "NOT_HERE\n").unwrap();
+ let refused = |args: &[&str], needle: &str| {
+ let o = scrust_in(&d, args);
+ assert!(!o.status.success(), "{args:?} accepted");
+ let e = String::from_utf8_lossy(&o.stderr);
+ assert!(e.contains(needle), "{args:?}: {e}");
+ };
+ let cl = |extra: &[&str]| -> Vec {
+ let mut a: Vec = ["cluster", "--counts", &c, "--preset", "workflow", "--out", "refused"].iter().map(|x| x.to_string()).collect();
+ a.extend(extra.iter().map(|x| x.to_string()));
+ a
+ };
+ fn as_str(v: &[String]) -> Vec<&str> {
+ v.iter().map(String::as_str).collect()
+ }
+ refused(&as_str(&cl(&["--vars-to-regress", "percent.mt"])), "--mt-genes");
+ refused(&as_str(&cl(&["--vars-to-regress", "nCount_RNA,nCount_RNA"])), "given twice");
+ refused(&as_str(&cl(&["--vars-to-regress", "my-col"])), "not a syntactic name");
+ refused(&as_str(&cl(&["--vars-to-regress", "GENE"])), "response");
+ refused(&as_str(&cl(&["--vars-to-regress", &feature])), "no --metadata table");
+ refused(&as_str(&cl(&["--vars-to-regress", "score"])), "no --metadata table is given");
+ refused(&as_str(&cl(&["--vars-to-regress", "label", "--metadata", &md])), "non-numeric");
+ refused(&as_str(&cl(&["--vars-to-regress", "nope", "--metadata", &md])), "not percent.mt, nCount_RNA, nFeature_RNA or a column of --metadata");
+ refused(&as_str(&cl(&["--vars-to-regress", "gappy", "--metadata", bad_md.to_str().unwrap()])), "missing");
+ refused(&as_str(&cl(&["--percent-mt", "--mt-genes", nope.to_str().unwrap()])), "none of its 1 id(s)");
+ refused(&["sctransform", "--counts", &c, "--out", "refused_sct", "--metadata", &md], "reads it only for the columns --vars-to-regress names");
+ refused(&["cluster", "--sct", "x", "--out", "refused_sct2", "--vars-to-regress", "nCount_RNA"], "act where SCTransform runs");
+ refused(&["cluster", "--snn", "x", "--out", "refused_snn", "--mt-genes", &mt], "act where SCTransform runs");
+ refused(&["doubletfinder", "--counts", &c, "--clusters", "x.tsv", "--out", "refused_df", "--cluster-metadata", &md], "clustering on the fly is for runs without --clusters");
+ refused(&["doubletfinder", "--counts", &c, "--out", "refused_df2", "--recluster-metadata", &md], "goes with --recluster");
+ // a column named like a feature, from the table: Seurat would add the feature's residuals too
+ let named = d.join("named.tsv");
+ let bc = scio::tenx::read_barcodes(&input(object)).unwrap();
+ std::fs::write(&named, format!("barcode\t{feature}\n{}", bc.iter().enumerate().map(|(k, b)| format!("{b}\t{k}\n")).collect::())).unwrap();
+ refused(&as_str(&cl(&["--vars-to-regress", &feature, "--metadata", named.to_str().unwrap()])), "also a feature's name");
+}
diff --git a/crates/sctransform/src/lib.rs b/crates/sctransform/src/lib.rs
index d439601..0c6ed4d 100644
--- a/crates/sctransform/src/lib.rs
+++ b/crates/sctransform/src/lib.rs
@@ -17,7 +17,10 @@
//! - [`residuals`] (S2d): clipped Pearson residuals, residual variance, the variable features and
//! `scale.data`;
//! - [`correct`] (K10, milestone M13): `correct()`'s corrected counts, made in S2d's pass when
-//! asked for, their `log1p`, `nCount_SCT` and `nFeature_SCT`.
+//! asked for, their `log1p`, `nCount_SCT` and `nFeature_SCT`;
+//! - [`regress`] (milestone M15b): `vars.to.regress`, the second regression of `scale.data`'s
+//! clipped rows on per-cell covariates (`ScaleData`'s `RegressOutMatrix`, through R's LINPACK
+//! QR, `rcompat::linpack`), before they are centred.
//!
//! Shared by DoubletFinder (7 calls per object) and the clustering crate (M11).
@@ -29,6 +32,7 @@ pub mod output;
pub mod params;
pub mod record;
pub mod reg;
+pub mod regress;
pub mod residuals;
pub mod setup;
pub mod vst;
@@ -38,9 +42,10 @@ pub use matrix::GeneRows;
pub use params::{MinVariance, SctParams};
pub use reg::{regularize, Reg, RegInput};
pub use correct::Corrected;
-pub use residuals::{residuals, residuals_corrected, ResidualInput, Residuals};
+pub use regress::Regression;
+pub use residuals::{residuals, residuals_corrected, residuals_with, ResidualInput, Residuals};
pub use setup::{setup, CellAttr, Setup};
-pub use vst::{finish, finish_with, sctransform, start, Sct, Started};
+pub use vst::{finish, finish_full, finish_with, sctransform, start, Sct, Started};
use std::fmt;
diff --git a/crates/sctransform/src/output.rs b/crates/sctransform/src/output.rs
index dd4d751..6bfa7a8 100644
--- a/crates/sctransform/src/output.rs
+++ b/crates/sctransform/src/output.rs
@@ -82,7 +82,7 @@ pub fn write_outputs(dir: &Path, barcodes: &[String], genes: &[Gene], sct: &Sct)
/// The parameters as `summary.json` records them.
pub fn params_json(params: &SctParams) -> Json {
- Json::obj(vec![
+ let mut v = vec![
("seed_use", Json::Int(params.seed_use.unwrap_or(0) as i64)),
("ncells", Json::Int(params.ncells as i64)),
("variable_features_n", Json::Int(params.variable_features_n.unwrap_or(0) as i64)),
@@ -90,6 +90,25 @@ pub fn params_json(params: &SctParams) -> Json {
("bin_size", Json::Int(params.bin_size as i64)),
("min_cells", Json::Int(params.min_cells as i64)),
("bw_adjust", Json::Num(params.bw_adjust)),
+ ];
+ // M15b: only when set, so that a run without it records what earlier runs recorded
+ if !params.vars_to_regress.is_empty() {
+ v.push(("vars_to_regress", Json::strs(¶ms.vars_to_regress)));
+ }
+ Json::obj(v)
+}
+
+/// `result`'s record of `vars.to.regress`' regression (M15b): the covariates in the formula's
+/// order, and the QR `lm()` made of the model matrix (the intercept and the covariates): its rank,
+/// the columns' order after `dqrdc2`'s pivoting (1-based) and its tolerance.
+pub fn regression_json(r: &crate::Regression) -> Json {
+ Json::obj(vec![
+ ("vars_to_regress", Json::strs(&r.names)),
+ ("model", Json::Str("linear: lm(GENE ~ vars)$qr once, qr.resid() per row (Seurat's RegressOutMatrix)".into())),
+ ("n_columns", Json::Int(r.qr.p as i64)),
+ ("rank", Json::Int(r.qr.rank as i64)),
+ ("pivot", Json::Vector(r.qr.pivot.iter().map(|&v| Json::Int(v as i64)).collect())),
+ ("tol", Json::Num(r.qr.tol)),
])
}
@@ -120,6 +139,10 @@ pub fn result_json(sct: &Sct, n_features: usize) -> Json {
if let (Json::Object(m), Some(c)) = (&mut out, &sct.corrected) {
m.push(("corrected".into(), corrected_json(c)));
}
+ // vars.to.regress (M15b), when regressed
+ if let (Json::Object(m), Some(r)) = (&mut out, &sct.regression) {
+ m.push(("regression".into(), regression_json(r)));
+ }
out
}
diff --git a/crates/sctransform/src/params.rs b/crates/sctransform/src/params.rs
index 1a9f294..9c35d6f 100644
--- a/crates/sctransform/src/params.rs
+++ b/crates/sctransform/src/params.rs
@@ -5,8 +5,9 @@
//! Only the defaults are validated against R (milestone M4). Other values are accepted where the
//! code path is the same one with a different number (cells and genes for the fits, bin size,
//! clipping, bandwidth adjustment, number of variable features, seed); options that would take R
-//! down another path (other methods, batch variables, `do.scale`, extra regressors) are rejected
-//! by [`SctParams::check`].
+//! down another path (other methods, batch variables, `do.scale`) are rejected by
+//! [`SctParams::check`]. `vars.to.regress` (milestone M15b) is ported: the regression of
+//! `scale.data` on per-cell covariates ([`crate::regress`]).
/// How `min_variance` is set (`vst(min_variance = )`).
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -36,6 +37,11 @@ pub struct SctParams {
pub clip_range: Option<(f64, f64)>,
/// `return.only.var.genes`: `scale.data` holds the variable features only.
pub return_only_var_genes: bool,
+ /// `vars.to.regress` (milestone M15b): the per-cell covariates `ScaleData` regresses
+ /// `scale.data`'s clipped rows on, in the formula's order; empty for none (Seurat's default,
+ /// and the workflow's since its commit 8d34de1). Their values reach `vst`'s caller in memory
+ /// ([`crate::Regression`]).
+ pub vars_to_regress: Vec,
// --- vst (sctransform, vst.flavor = "v2") ---
/// `n_genes`: genes used to fit the models (density-weighted sample when more qualify).
@@ -69,6 +75,7 @@ impl Default for SctParams {
do_center: true,
clip_range: None,
return_only_var_genes: true,
+ vars_to_regress: Vec::new(),
n_genes: Some(2000),
bin_size: 500,
min_cells: 5,
diff --git a/crates/sctransform/src/regress.rs b/crates/sctransform/src/regress.rs
new file mode 100644
index 0000000..88f516d
--- /dev/null
+++ b/crates/sctransform/src/regress.rs
@@ -0,0 +1,109 @@
+//! SCTransform's second regression, `vars.to.regress` (milestone M15b; docs/PLAN.md C3).
+//!
+//! Seurat 5.5.1's `SCTransform.default` clips the variable features' residuals to `clip.range`,
+//! then calls `ScaleData(scale.data, vars.to.regress, latent.data, model.use = "linear",
+//! use.umi = FALSE, do.scale, do.center, scale.max = Inf, block.size = 750)`. With
+//! `vars.to.regress` set, `ScaleData.default` takes the covariates for the cells
+//! (`latent.data[colnames(object), , drop = FALSE]`, the meta.data columns `SCTransform.Seurat`
+//! passed, in `vars.to.regress`' order) and, with the sequential `future` plan, calls
+//! `RegressOutMatrix()` once on every row:
+//!
+//! ```text
+//! fmla <- as.formula(paste("GENE ~", paste(vars.to.regress, collapse = "+")))
+//! qr <- lm(fmla, data = cbind(latent.data, GENE = data.expr[1, ]), qr = TRUE)$qr
+//! for each row x: data.resid[x, ] <- qr.resid(qr = qr, y = data.expr[x, ])
+//! ```
+//!
+//! then centres each row (`FastRowScale`: `mat - rowMeans2(mat, na.rm = TRUE)`, in blocks of 750
+//! rows, which changes nothing since rows are independent) and sets `NA` (and NaN) values to 0.
+//! The variable features, the residual statistics and `correct()`'s corrected counts are vst's
+//! and do not change; only `scale.data` does. In the v5 path (`SCTransform.StdAssay`),
+//! `FetchResiduals()` afterwards returns the existing `scale.data` rows for the variable features
+//! (none needs computing), so the regressed values stay.
+//!
+//! [`Regression`] is the QR, made once ([`rcompat::linpack::lm_qr`] of the intercept and the
+//! covariates); [`Regression::regress_rows`] applies `qr.resid` to every row, the threads sharing
+//! the rows (each row's arithmetic is the same whatever the thread count).
+
+use rcompat::linpack::{lm_qr, model_matrix, Qr, QrResid};
+
+/// The regression of `scale.data`'s rows on per-cell covariates.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Regression {
+ /// `vars.to.regress`, in the formula's order.
+ pub names: Vec,
+ /// `lm(GENE ~ , qr = TRUE)$qr`: the intercept, then the covariates.
+ pub qr: Qr,
+}
+
+impl Regression {
+ /// The QR of the model matrix for `covariates` (one value per cell each, in the cells' order,
+ /// named `names`). Stops as R does on a non-finite value ("NA/NaN/Inf in 'x'").
+ pub fn new(names: Vec, covariates: &[Vec], ncells: usize) -> Result {
+ if names.len() != covariates.len() || names.is_empty() {
+ return Err("vars.to.regress: one covariate per name, at least one".into());
+ }
+ let cols: Vec<&[f64]> = covariates.iter().map(Vec::as_slice).collect();
+ if cols.iter().any(|c| c.len() != ncells) {
+ return Err("vars.to.regress: a covariate does not have one value per cell".into());
+ }
+ let x = model_matrix(&cols, ncells);
+ let qr = lm_qr(x, ncells, 1 + names.len()).map_err(|e| format!("vars.to.regress ({}): {e}", names.join(", ")))?;
+ Ok(Regression { names, qr })
+ }
+
+ /// The columns of the model matrix `dqrdc2` judged linearly independent (`qr$rank`) and the
+ /// number it has (`p`: the intercept and the covariates).
+ pub fn rank(&self) -> (usize, usize) {
+ (self.qr.rank, self.qr.p)
+ }
+
+ /// `RegressOutMatrix()` on `rows` (row-major, `ncells` per row), in place: each row becomes
+ /// `qr.resid(qr, y = row)`.
+ pub fn regress_rows(&self, rows: &mut [f64], ncells: usize, threads: usize) {
+ if ncells == 0 || rows.is_empty() {
+ return;
+ }
+ assert_eq!(ncells, self.qr.n, "regress_rows: the rows' cells are not the covariates'");
+ assert_eq!(rows.len() % ncells, 0, "regress_rows: not whole rows");
+ let nrow = rows.len() / ncells;
+ let r = QrResid::new(&self.qr);
+ let threads = threads.max(1).min(nrow);
+ let per = nrow.div_ceil(threads);
+ std::thread::scope(|scope| {
+ for chunk in rows.chunks_mut(per * ncells) {
+ let r = &r;
+ scope.spawn(move || {
+ let (mut qty, mut rsd) = (vec![0.0f64; ncells], vec![0.0f64; ncells]);
+ for row in chunk.chunks_mut(ncells) {
+ r.resid(row, &mut qty, &mut rsd);
+ row.copy_from_slice(&rsd);
+ }
+ });
+ }
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rows_regressed_alike_on_any_number_of_threads() {
+ let n = 37;
+ let v: Vec = (0..n).map(|i| ((i * 13) % 17) as f64 / 3.0).collect();
+ let w: Vec = (0..n).map(|i| (i as f64).sqrt()).collect();
+ let reg = Regression::new(vec!["v".into(), "w".into()], &[v, w], n).unwrap();
+ assert_eq!(reg.rank(), (3, 3));
+ let rows: Vec = (0..11 * n).map(|k| ((k * 7919) % 1009) as f64 / 100.0 - 5.0).collect();
+ let mut one = rows.clone();
+ reg.regress_rows(&mut one, n, 1);
+ for t in [2, 3, 4, 11, 64] {
+ let mut many = rows.clone();
+ reg.regress_rows(&mut many, n, t);
+ assert!(one.iter().zip(&many).all(|(a, b)| a.to_bits() == b.to_bits()), "{t} threads");
+ }
+ assert!(Regression::new(vec!["v".into()], &[vec![1.0, f64::NAN]], 2).unwrap_err().contains("NA/NaN/Inf"));
+ }
+}
diff --git a/crates/sctransform/src/residuals.rs b/crates/sctransform/src/residuals.rs
index d52b81f..309cfc2 100644
--- a/crates/sctransform/src/residuals.rs
+++ b/crates/sctransform/src/residuals.rs
@@ -11,7 +11,9 @@
//! 4. the variable features: `sort(residual_variance, decreasing = TRUE)` (stable; NA dropped),
//! the first `variable_features_n`;
//! 5. `scale.data`: their residuals clipped to `+-sqrt(ncells / 30)`, then centred by
-//! `ScaleData` (`FastRowScale`: `mat - rowMeans2(mat, na.rm = TRUE)`).
+//! `ScaleData` (`FastRowScale`: `mat - rowMeans2(mat, na.rm = TRUE)`). With `vars.to.regress`
+//! ([`residuals_with`], milestone M15b), `ScaleData` first regresses each clipped row on the
+//! covariates (`RegressOutMatrix`, [`crate::regress`]), centres the result, and sets `NA` to 0.
//!
//! With `correct` ([`residuals_corrected`], milestone M13), the same pass also makes the
//! corrected counts of sctransform 0.4.3's `correct()`, which `vst()` calls on these residuals
@@ -35,6 +37,7 @@
use crate::correct::Corrected;
use crate::matrix::GeneRows;
use crate::params::{MinVariance, SctParams};
+use crate::regress::Regression;
use crate::setup::bins;
use crate::SctError;
use rcompat::blas::tcrossprod_into;
@@ -474,19 +477,28 @@ impl<'s> Run<'_, 's> {
/// Stage S2d. `rows` are the kept genes' counts, `threads` the threads sharing each bin's genes.
pub fn residuals(rows: &GeneRows, input: &ResidualInput, params: &SctParams, keep_y: bool, threads: usize) -> Result {
- residuals_in_groups(rows, input, params, keep_y, threads, gene_group(rows.ncol), false).map(|r| r.0)
+ residuals_in_groups(rows, input, params, keep_y, threads, gene_group(rows.ncol), false, None).map(|r| r.0)
}
/// Stage S2d with `correct()` in the same pass (M13): the residuals as [`residuals`] makes them,
/// and the corrected counts of every kept gene and cell (`do.correct.umi = TRUE`).
pub fn residuals_corrected(rows: &GeneRows, input: &ResidualInput, params: &SctParams, keep_y: bool, threads: usize) -> Result<(Residuals, Corrected), SctError> {
- let (r, c) = residuals_in_groups(rows, input, params, keep_y, threads, gene_group(rows.ncol), true)?;
+ let (r, c) = residuals_in_groups(rows, input, params, keep_y, threads, gene_group(rows.ncol), true, None)?;
Ok((r, c.expect("corrected counts when correcting")))
}
-/// [`residuals`], the threads taking `group` genes at a time; with `correct`, `correct()` too.
+/// Stage S2d with `correct()` when asked, and with `regress` (`vars.to.regress`, M15b), the
+/// second regression of `scale.data`'s clipped rows before they are centred: every other result
+/// ([`Residuals::residual_variance`], the variable features, the corrected counts) is the same as
+/// without it.
+pub fn residuals_with(rows: &GeneRows, input: &ResidualInput, params: &SctParams, keep_y: bool, threads: usize, correct: bool, regress: Option<&Regression>) -> Result<(Residuals, Option), SctError> {
+ residuals_in_groups(rows, input, params, keep_y, threads, gene_group(rows.ncol), correct, regress)
+}
+
+/// [`residuals`], the threads taking `group` genes at a time; with `correct`, `correct()` too;
+/// with `regress`, `vars.to.regress`' regression.
#[allow(clippy::too_many_arguments)]
-fn residuals_in_groups(rows: &GeneRows, input: &ResidualInput, params: &SctParams, keep_y: bool, threads: usize, group: usize, correct: bool) -> Result<(Residuals, Option), SctError> {
+fn residuals_in_groups(rows: &GeneRows, input: &ResidualInput, params: &SctParams, keep_y: bool, threads: usize, group: usize, correct: bool, regress: Option<&Regression>) -> Result<(Residuals, Option), SctError> {
let ng = rows.nrow();
let nc = rows.ncol;
if input.model_pars_fit.len() != ng || input.log_umi.len() != nc {
@@ -582,22 +594,58 @@ fn residuals_in_groups(rows: &GeneRows, input: &ResidualInput, params: &SctParam
slab.truncate(top_features.len() * nc);
slab.shrink_to_fit();
let mut scale_data = slab;
- for k in 0..top_features.len() {
- let row = &mut scale_data[k * nc..(k + 1) * nc];
- for d in row.iter_mut() {
- let mut v = *d;
- if v < clip.0 {
- v = clip.0;
- }
- if v > clip.1 {
- v = clip.1;
+ match regress {
+ None => {
+ for k in 0..top_features.len() {
+ let row = &mut scale_data[k * nc..(k + 1) * nc];
+ for d in row.iter_mut() {
+ let mut v = *d;
+ if v < clip.0 {
+ v = clip.0;
+ }
+ if v > clip.1 {
+ v = clip.1;
+ }
+ *d = v;
+ }
+ if params.do_center {
+ let rm = mean2_na_rm(row);
+ for d in row.iter_mut() {
+ *d -= rm;
+ }
+ }
}
- *d = v;
}
- if params.do_center {
- let rm = mean2_na_rm(row);
- for d in row.iter_mut() {
- *d -= rm;
+ Some(reg) => {
+ // SCTransform.default clips; ScaleData regresses (RegressOutMatrix), centres
+ // (FastRowScale), then sets NA to 0
+ for d in scale_data.iter_mut() {
+ let mut v = *d;
+ if v < clip.0 {
+ v = clip.0;
+ }
+ if v > clip.1 {
+ v = clip.1;
+ }
+ *d = v;
+ }
+ if reg.qr.n != nc {
+ return Err(SctError::Input(format!("vars.to.regress: {} cells' covariates for {nc} cells", reg.qr.n)));
+ }
+ reg.regress_rows(&mut scale_data, nc, threads);
+ for k in 0..top_features.len() {
+ let row = &mut scale_data[k * nc..(k + 1) * nc];
+ if params.do_center {
+ let rm = mean2_na_rm(row);
+ for d in row.iter_mut() {
+ *d -= rm;
+ }
+ }
+ for d in row.iter_mut() {
+ if d.is_nan() {
+ *d = 0.0;
+ }
+ }
}
}
}
@@ -804,7 +852,7 @@ mod tests {
let got = if group == 0 {
residuals(&rows, &input, params, keep_y, threads).unwrap()
} else {
- residuals_in_groups(&rows, &input, params, keep_y, threads, group, false).unwrap().0
+ residuals_in_groups(&rows, &input, params, keep_y, threads, group, false, None).unwrap().0
};
let what = format!("{params:?}, {threads} threads, keep_y {keep_y}, group {group}");
assert!(same(&got.residual_mean, &want.residual_mean), "residual_mean: {what}");
@@ -880,7 +928,7 @@ mod tests {
assert!(want_c.nnz() > 100 && beyond > 0, "the case exercises corrected counts and residuals beyond the clip range");
let plain = residuals(&rows, &input, ¶ms, false, 1).unwrap();
for (threads, group) in [1, 2, 3, 7].into_iter().flat_map(|t| [1, 3, 8].map(|g| (t, g))) {
- let (r, c) = residuals_in_groups(&rows, &input, ¶ms, false, threads, group, true).unwrap();
+ let (r, c) = residuals_in_groups(&rows, &input, ¶ms, false, threads, group, true, None).unwrap();
let c = c.unwrap();
assert_eq!(c, want_c, "{nc} cells, {threads} threads, group {group}");
assert_eq!(c.median_log_umi.to_bits(), med.to_bits());
diff --git a/crates/sctransform/src/vst.rs b/crates/sctransform/src/vst.rs
index 0967719..7791127 100644
--- a/crates/sctransform/src/vst.rs
+++ b/crates/sctransform/src/vst.rs
@@ -12,7 +12,8 @@ use crate::fit::{fit, FitInput, Fits};
use crate::matrix::GeneRows;
use crate::params::SctParams;
use crate::reg::{mean_cell_sum, regularize, Reg, RegInput};
-use crate::residuals::{residuals, residuals_corrected, ResidualInput, Residuals};
+use crate::regress::Regression;
+use crate::residuals::{residuals_with, ResidualInput, Residuals};
use crate::setup::{setup, Setup};
use crate::SctError;
use rcompat::RRng;
@@ -28,6 +29,8 @@ pub struct Sct {
pub residuals: Residuals,
/// `correct()`'s corrected counts, when asked for ([`finish_with`]; M13)
pub corrected: Option,
+ /// `vars.to.regress`' regression of `scale.data`, when asked for ([`finish_full`]; M15b)
+ pub regression: Option,
/// `.Random.seed` when `vst` starts, after `SCTransform`'s `set.seed` calls (R's checkpoint
/// "vst_entry")
pub rng_entry: Vec,
@@ -76,7 +79,19 @@ pub fn finish(started: Started, params: &SctParams, rng: &mut RRng, keep_y: bool
/// from its residuals before clipping them (`do.correct.umi = TRUE`, Seurat's default; M13). They
/// change nothing else: `correct()` draws no random number and its result feeds no later stage.
pub fn finish_with(started: Started, params: &SctParams, rng: &mut RRng, keep_y: bool, correct: bool, threads: usize) -> Result {
+ finish_full(started, params, rng, keep_y, correct, None, threads)
+}
+
+/// [`finish_with`], and with `regress` SCTransform's second regression (`vars.to.regress`,
+/// milestone M15b): `scale.data`'s clipped rows regressed on the covariates before they are
+/// centred ([`crate::regress`]). It draws no random number and changes nothing but `scale.data`.
+pub fn finish_full(started: Started, params: &SctParams, rng: &mut RRng, keep_y: bool, correct: bool, regress: Option, threads: usize) -> Result {
let Started { setup, rows, rng_entry } = started;
+ if let Some(r) = ®ress {
+ if r.qr.n != setup.cell_attr.log_umi.len() {
+ return Err(SctError::Input(format!("vars.to.regress: covariates for {} cells, but the counts have {}", r.qr.n, setup.cell_attr.log_umi.len())));
+ }
+ }
let fits = fit(&rows, &FitInput::from_setup(&setup), params, rng, threads)?;
let mcs = mean_cell_sum(&rows);
let reg = regularize(
@@ -92,12 +107,7 @@ pub fn finish_with(started: Started, params: &SctParams, rng: &mut RRng, keep_y:
params,
)?;
let input = ResidualInput { model_pars_fit: ®.model_pars_fit, log_umi: &setup.cell_attr.log_umi };
- let (residuals, corrected) = if correct {
- let (r, c) = residuals_corrected(&rows, &input, params, keep_y, threads)?;
- (r, Some(c))
- } else {
- (residuals(&rows, &input, params, keep_y, threads)?, None)
- };
+ let (residuals, corrected) = residuals_with(&rows, &input, params, keep_y, threads, correct, regress.as_ref())?;
let rng_exit = rng.random_seed();
- Ok(Sct { setup, rows, fits, mean_cell_sum: mcs, reg, residuals, corrected, rng_entry, rng_exit })
+ Ok(Sct { setup, rows, fits, mean_cell_sum: mcs, reg, residuals, corrected, regression: regress, rng_entry, rng_exit })
}
diff --git a/crates/sctransform/tests/m15b_regress.rs b/crates/sctransform/tests/m15b_regress.rs
new file mode 100644
index 0000000..1004ad0
--- /dev/null
+++ b/crates/sctransform/tests/m15b_regress.rs
@@ -0,0 +1,131 @@
+//! Milestone M15b: SCTransform's `vars.to.regress` against R 4.5.3 and Seurat 5.5.1
+//! (validation/R/regress_vectors.R; fixtures tests/fixtures/rcompat/linpack_qr.tsv.gz and
+//! linpack_resid.tsv.gz, made under OpenBLAS's Haswell kernel):
+//!
+//! - `lm(GENE ~ , qr = TRUE)$qr` (LINPACK `dqrdc2` through `Cdqrls`, `tol = 1e-07`), as
+//! Seurat's `RegressOutMatrix()` takes it once: the compact QR, `qraux`, the pivot and the rank,
+//! bit for bit, on full-rank models, a zero column, a constant column, two collinear columns, a
+//! near-constant one (rank 1), square and wide models and an outlier;
+//! - `qr.resid(qr, y)` (`dqrrsd` -> `dqrsl`), which `RegressOutMatrix()` returns row by row (the
+//! R script checked that its rows equal `qr.resid()`'s), bit for bit;
+//! - [`sctransform::Regression`], which the chain uses, on the same rows, at several thread counts.
+//!
+//! `dqrdc2` and `dqrsl` call OpenBLAS's `dnrm2`, `dscal`, `ddot` and `daxpy`, whose results depend
+//! on the kernel: the tests run under the fixtures' kernel (`rcompat::blas::require_fixture_kernel`).
+
+use rcompat::linpack::{lm_qr, QrResid};
+use sctransform::Regression;
+use std::collections::HashMap;
+use std::path::PathBuf;
+
+fn fixture_path(name: &str) -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/rcompat").join(name)
+}
+
+fn fixture(name: &str) -> Vec> {
+ let path = fixture_path(name);
+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
+ let text = String::from_utf8(scio::gz::gunzip(&bytes).expect("gzip")).expect("utf-8");
+ text.lines().filter(|l| !l.starts_with('#') && !l.is_empty()).map(|l| l.split('\t').map(str::to_owned).collect()).collect()
+}
+
+fn f(s: &str) -> f64 {
+ f64::from_bits(u64::from_str_radix(s, 16).unwrap())
+}
+
+fn fl(s: &str) -> Vec {
+ if s == "-" {
+ return Vec::new();
+ }
+ s.split(',').map(f).collect()
+}
+
+fn same(a: &[f64], b: &[f64]) -> Option {
+ assert_eq!(a.len(), b.len());
+ a.iter().zip(b).position(|(x, y)| x.to_bits() != y.to_bits())
+}
+
+struct Case {
+ n: usize,
+ p: usize,
+ vars: Vec,
+ x: Vec,
+ qr: Vec,
+ qraux: Vec,
+ pivot: Vec,
+ rank: usize,
+}
+
+fn cases() -> Vec<(String, Case)> {
+ fixture("linpack_qr.tsv.gz")
+ .into_iter()
+ .map(|r| {
+ let c = Case {
+ n: r[1].parse().unwrap(),
+ p: r[2].parse().unwrap(),
+ vars: r[3].split(',').map(str::to_owned).collect(),
+ x: fl(&r[4]),
+ qr: fl(&r[5]),
+ qraux: fl(&r[6]),
+ pivot: r[7].split(',').map(|v| v.parse().unwrap()).collect(),
+ rank: r[8].parse().unwrap(),
+ };
+ (r[0].clone(), c)
+ })
+ .collect()
+}
+
+fn kernel() {
+ rcompat::blas::require_fixture_kernel(&fixture_path("linpack_qr.tsv.gz"), "linpack_qr.tsv.gz");
+}
+
+#[test]
+fn lm_qr_as_r_makes_it() {
+ kernel();
+ let cs = cases();
+ assert_eq!(cs.len(), 14);
+ let mut deficient = 0;
+ for (name, c) in &cs {
+ let qr = lm_qr(c.x.clone(), c.n, c.p).unwrap();
+ assert_eq!((qr.rank, &qr.pivot), (c.rank, &c.pivot), "{name}: rank and pivot");
+ assert_eq!(same(&qr.qraux, &c.qraux), None, "{name}: qraux");
+ assert_eq!(same(&qr.qr, &c.qr), None, "{name}: qr");
+ if qr.rank < qr.p {
+ deficient += 1;
+ }
+ }
+ // the zero, constant, collinear, near-constant and wide models
+ assert_eq!(deficient, 5);
+}
+
+#[test]
+fn qr_resid_and_regress_out_matrix_as_r() {
+ kernel();
+ let cs: HashMap = cases().into_iter().collect();
+ let rows = fixture("linpack_resid.tsv.gz");
+ assert_eq!(rows.len(), 3 * cs.len());
+ let mut by_case: HashMap<&str, Vec<(Vec, Vec)>> = HashMap::new();
+ for r in &rows {
+ let c = &cs[&r[0]];
+ let qr = lm_qr(c.x.clone(), c.n, c.p).unwrap();
+ let res = QrResid::new(&qr);
+ let (y, want) = (fl(&r[2]), fl(&r[3]));
+ let (mut qty, mut rsd) = (vec![0.0; c.n], vec![0.0; c.n]);
+ res.resid(&y, &mut qty, &mut rsd);
+ assert_eq!(same(&rsd, &want), None, "{} row {}", r[0], r[1]);
+ by_case.entry(&r[0]).or_default().push((y, want));
+ }
+ // the chain's Regression on the same rows: the covariates are x's columns after the intercept
+ for (name, rows) in by_case {
+ let c = &cs[name];
+ let covs: Vec> = (1..c.p).map(|j| c.x[j * c.n..(j + 1) * c.n].to_vec()).collect();
+ let reg = Regression::new(c.vars.clone(), &covs, c.n).unwrap();
+ let ys: Vec = rows.iter().flat_map(|(y, _)| y.clone()).collect();
+ let want: Vec = rows.iter().flat_map(|(_, w)| w.clone()).collect();
+ for threads in [1, 2, 3] {
+ let mut got = ys.clone();
+ reg.regress_rows(&mut got, c.n, threads);
+ assert_eq!(same(&got, &want), None, "{name}: RegressOutMatrix, {threads} threads");
+ }
+ }
+}
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 0ecf4e6..c2480d3 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -91,7 +91,7 @@ Each tool's real inputs and outputs are sparse matrices and small per-cell table
| CellBender | raw matrix | cell probabilities, ambient profile, **denoised matrix** |
| decontX | filtered matrix, cluster labels, raw matrix (background) | contamination per cell, **decontaminated matrix** |
| DoubletFinder | counts matrix, cluster labels (for the homotypic adjustment), or none: it then clusters its input in process (C3h) | pANN, classification, pK, nExp, sweep table, **the singlets' matrix**; the labels it computed when given none (`clusters/`); with `--recluster`, the singlets' re-clustering, as `scrust cluster` writes it (`singlets_clusters/`); each a nested output (C3f, C3h) |
-| Clustering (Seurat chain) | counts matrix, parameters | cluster labels, silhouette width and neighbourhood purity per cell; optionally the intermediates (SCTransform, PCA, neighbour graph) for reuse, and an export of SCTransform's normalised data with the counts and metadata (C3f) |
+| Clustering (Seurat chain) | counts matrix, parameters; for SCTransform's `vars.to.regress` (M15b), a list of mitochondrial feature ids and a per-cell table, when the covariates need them (C3j) | cluster labels, silhouette width and neighbourhood purity per cell; `percent.mt` when asked for (C3j); optionally the intermediates (SCTransform, PCA, neighbour graph) for reuse, and an export of SCTransform's normalised data with the counts and metadata (C3f) |
| scDblFinder | counts matrix | score and class per cell, **the singlets' matrix** |
- **Every output of the original, and more.** A port keeps all of the original tool's outputs, such as DoubletFinder's per-barcode pANN and classification table and its sweep tables. The 10x count data below is written in addition to them, never instead. Ports expand the original tools' functionality and remove none of it.
@@ -171,7 +171,7 @@ Exact matching depends on copying R's behaviour in these places. Each is unit-te
- **Summation order:** follow R's loop order for distances and other reductions; parallelise only across independent units (cells).
- **Powers:** `x^2` is `x*x`. Every other power goes through glibc `pow`, which the Rust binary links at runtime.
- **FFT:** R's `fft` (Singleton's mixed-radix algorithm) is ported as-is wherever an R function uses it, e.g. `bkde` and `density`.
-- **BLAS and LAPACK:** R's matrix products go through OpenBLAS 0.3.34, built with `DYNAMIC_ARCH`, so the kernel (and its rounding) is chosen per CPU at runtime. Ports of BLAS-dependent code call that same conda OpenBLAS through FFI (`dgemm_`, `dgemv_`, `dgesdd_`), with the same routines and arguments R uses.
+- **BLAS and LAPACK:** R's matrix products go through OpenBLAS 0.3.34, built with `DYNAMIC_ARCH`, so the kernel (and its rounding) is chosen per CPU at runtime. Ports of BLAS-dependent code call that same conda OpenBLAS through FFI (`dgemm_`, `dgemv_`, `dgesdd_`), with the same routines and arguments R uses. So do R's own Fortran routines that call BLAS: LINPACK's QR (`dqrdc2`, `dqrsl`), which `lm()` and `qr.resid()` use, calls `dnrm2_`, `dscal_`, `ddot_` and `daxpy_` from the same library (`libR.so` takes them from `libblas.so.3`), and `rcompat::linpack` calls them too (M15b). OpenBLAS's level-1 kernels load unaligned and peel nothing for alignment, so their results depend on a vector's length and values, not on its address.
- **No FMA:** R and its packages are compiled with `-march=nocona -O2` and use no FMA. Rust never fuses operations implicitly, so plain `f64` code matches.
### A5b. Reproducibility across machines and clusters
@@ -193,7 +193,7 @@ Exact matching depends on copying R's behaviour in these places. Each is unit-te
- thread count and glibc version;
- library and package versions.
- The harness runs exact checks only when the BLAS-relevant fields match. Otherwise it switches to tolerance mode (the R-vs-R floor) and says so in the report. A different machine therefore produces neither false failures nor false "exact" claims. Since M11 both validators do this (`scio::grade`): exact when the two runs' recorded OpenBLAS kernels match; otherwise, and whenever a run records none, BLAS-free checks stay exact and BLAS-dependent ones are graded against `[.floor.kernel]` (`validation/tolerances.toml`). The tests that compare a BLAS-dependent result with a portable fixture first compare the kernel in use (`openblas_get_corename`) with the fixture's, and stop with both kernels named when they differ (`rcompat::blas::require_fixture_kernel`).
+ The harness runs exact checks only when the BLAS-relevant fields match. Otherwise it switches to tolerance mode (the R-vs-R floor) and says so in the report. A different machine therefore produces neither false failures nor false "exact" claims. Since M11 both validators do this (`scio::grade`): exact when the two runs' recorded OpenBLAS kernels match; otherwise, and whenever a run records none, BLAS-free checks stay exact and BLAS-dependent ones are graded against `[.floor.kernel]` (`validation/tolerances.toml`). The one exception (M15b): when both runs record the same non-empty `vars.to.regress`, `scrust validate cluster` grades against `[clustering.floor.kernel_regressed]`, R's own differences across kernels measured with the regression, which makes most of `scale.data` kernel-dependent (C3j, C5's K14); every other comparison keeps `[clustering.floor.kernel]`. The tests that compare a BLAS-dependent result with a portable fixture first compare the kernel in use (`openblas_get_corename`) with the fixture's, and stop with both kernels named when they differ (`rcompat::blas::require_fixture_kernel`).
4. **Teacher forcing keeps most tests machine-independent.** Each stage can take the reference's own intermediate as input. Stages without BLAS are then exact on any machine: RNG, sampling, filters, the glmGamPoi Newton fits and `nlminb`, regularisation, distances, ranks, pANN, BC and pK. For DoubletFinder, only S2b (glmGamPoi's Cox–Reid term, a `dgemv`, and `nlminb`, whose PORT routines call `ddot` and `dnrm2`), S2d and S3 depend on BLAS (M11 corrected this: the `nlminb` calls).
5. **Fixtures are recipes.** The manifest stores a sha256 for each portable fixture. Developers on another cluster regenerate the fixtures from the pinned env instead of copying gigabytes; matching checksums prove the environment is identical before any Rust test runs.
6. **Non-x86 machines (ARM, macOS):** stages that use BLAS or libm run in tolerance mode; BLAS-free stages stay exact.
@@ -610,6 +610,8 @@ obj <- add_silhouette_to_metadata(obj) # the workflow's own, through bluster
- each cell's purity is the weighted share of its own cluster among itself and those neighbours. Each cell weighs 1/(its cluster's size);
- **`write_cluster_metadata`:** writes the identities' levels into `