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 ] [--export]`. -fn equivalent_command(counts: &Path, preset: &str, params: Option<&str>, stats: Option<&str>, export: bool) -> String { +/// `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 `_cluster_ids.txt` and their count into `_nclusters.txt`, temporary files that drive the marker checkpoint. +**`percent.mt` and `vars.to.regress`** (researched for M15b; C3j). Every script computes `obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = "(?i)^mt-")` right before SCTransform, and until the pipeline's commit 8d34de1 (2026-10-30) passed `vars.to.regress = "percent.mt"` to SCTransform; the production run of 8 and 9 November ran without it, and keeps `percent.mt` as metadata. The pattern finds mitochondrial genes only where the annotation names them `mt-` (5 of the 30 production samples, all mouse, and the zebrafish's two mt rRNAs; 6 samples name them `ND1`, `COX1`, ..., the zebrafish among them). `PercentageFeatureSet()` uses the default assay: in the scripts that build their object (`tenx2seuratrds.R`, `emptydrops.R`, `soupx.R`, `decontx.R`, `cellbender2seurat.R`) that is RNA, so `percent.mt` is the RNA counts' share; `doubletfinder.R` and `scdblfinder.R` subset an input object whose default assay is SCT, so theirs is the SCT assay's corrected counts over `nCount_SCT` of the input's SCTransform (M15b found it on the 150 saved DoubletFinder objects); `posthocfilter_threshold.R` computes none and carries its input's. Their call comes before their own SCTransform, but their input is already transformed: the building scripts' SCTransform left SCT the default assay of the object they saved. **The user decided (2026-11-19)** that the workflow computes `percent.mt` on the RNA assay everywhere, with or without the regression, as scRust does; the objects saved before that keep the SCT assay's column. + **What the step leaves:** - in the metadata: `nCount_SCT`, `nFeature_SCT`, `SCT_snn_res.0.8`, `seurat_clusters`, `silhouette_width` and `neighborhood_purity`; - the SCT assay (the corrected counts, their log1p, the residuals and the model), the `pca` and `umap` reductions, and the `SCT_nn` and `SCT_snn` graphs. @@ -653,7 +655,8 @@ Consequences: **Commands.** The four staged subcommands that A7b asks for, each also a library call: ``` -scrust sctransform --counts <10x dir> --out [--seed 1448145] [--corrected-counts] ... (exists, M4) +scrust sctransform --counts <10x dir> --out [--seed 1448145] [--corrected-counts] + [--vars-to-regress ] [--percent-mt] [--mt-genes ] [--metadata ] (exists, M4; M15b) scrust pca --sct --out [--npcs 50] [--seed 42] (exists, M5) scrust neighbors --pca --out [--dims 1:10] [--k 20] [--trees 50] [--metric euclidean|cosine|manhattan] [--prune 1/15] [--search-k -1] @@ -670,7 +673,7 @@ The whole chain also runs in one process, for the workflow: ``` scrust cluster --counts <10x dir> --out [--preset workflow] [--params ] [--export] [--keep-stages] [--dump-stages none|light|standard|full] [--purity-lists auto|yes|no] - [--metadata ] [--threads N] + [--metadata ] [--vars-to-regress ] [--percent-mt] [--mt-genes ] [--threads N] ``` `scrust cluster` can start from any stage's output (`--sct`, `--pca`, `--snn`), so a sweep over k or the resolution reuses one SCTransform and PCA. The scores need the PCA, so starting from `--snn` they need `--pca` too. Each route writes the same files (M11): `scrust sctransform` writes the counts' per-cell columns (`cell_metadata.tsv`: `nCount_RNA`, `nFeature_RNA`), and `scrust pca` and `scrust neighbors` carry them forward. Every SCTransform, RunPCA and FindNeighbors parameter has a flag of its own (`--sct-seed`, `--ncells`, `--variable-features`, `--clip-range`, `--npcs`, `--pca-seed`, `--weight-by-var`, `--pca-guard`, `--dims`, `--k`, `--trees`, `--metric`, `--prune`, `--search-k`); `--seed` stays FindClusters' `random.seed`. `--dump-stages` writes the stage dumps of M8's instrumented runs, which `scrust validate cluster` compares. @@ -678,7 +681,7 @@ scrust cluster --counts <10x dir> --out [--preset workflow] [--params --out [--preset workflow] [--params `, and the scores through `--cluster-stats` (none by default; the file's `[stats]` when it has one). The preset defaults to `workflow` (or the file's), as the tool's other defaults are the workflow's. `--cluster-levels` and `--from-stages` need `--clusters`. +- **`vars.to.regress` and `percent.mt`** (M15b, C3j): both parameter files (`--cluster-params`, `--recluster-params`) take the `[sctransform]` keys, and `--cluster-metadata` and `--recluster-metadata` give each clustering a `--metadata` table; `clusters/` and `singlets_clusters/` then hold what `scrust cluster --counts` writes with the same options. - **`--clusters` stays,** for three reasons: the original tools take labels; users may have curated annotations; and in the workflow, SoupX and decontX share one base object's labels. With `--clusters`, every output stays as before, byte for byte. - **Memory:** only the labels (and the scores, when asked) are kept. The counts, read once, are borrowed by the chain and then taken by DoubletFinder. The chain runs before DoubletFinder's own work, and DoubletFinder's SCTransform on more cells (the doublets added) still sets the peak (M15 measured it). One thing had to be added (M15): glibc raises its mmap threshold each time a large block is freed, so after the chain's buffers were freed, DoubletFinder's medium-sized blocks came from the heap and stayed resident, raising its peak by up to 16% above M7's runs on small objects (on one, the process held 210 MB when DoubletFinder began, where the run given the labels held 56 MB). At the hand-off, after the chain, `scrust doubletfinder` therefore fixes the threshold at its default, 128 KiB, and returns the free pages (`scio::memory::settle`: glibc's `mallopt` and `malloc_trim`; A3's in-memory rule); runs given `--clusters` are untouched, memory included. - **Outputs:** `clusters/`, a nested `scrust cluster` output (C3f) with the labels it computed in `--clusters`' layout (`seurat_clusters.tsv`, `seurat_clusters_levels.txt`), FindClusters' other label files, `metadata.tsv` (with silhouette and purity if asked) and its own `summary.json` with the clustering's numbers, each as `scrust cluster --counts ` writes it; no `pca/`, `neighbors/` or `sct/`. The DoubletFinder run's `summary.json` says where it is (`result.clustering`: the directory, cells, clusters and levels). @@ -944,6 +949,26 @@ The `knn` crate doesn't replace Annoy: Annoy's search is approximate, and Seurat - the same `dgemm` calls as R, with the same bin shapes. The kernel's last bits can move a value across a .5 boundary, so exact checks use the reference's kernel; - vst's residuals as `correct()` reads them, floored at `min_variance` but not yet clipped; θ = ∞; `round` half to even; glibc's `exp` and `log1p`. +**C3j. `vars.to.regress` and `percent.mt` (M15b).** The user's request of 2026-11-19: "many researchers might want to regress percent.mt (or even some other features). And, the regular expression itself might not consistently recover mtDNA symbols if they are coded differently in an annotation. [...] Can we create an option for regressing on percent.mt, and an option to either use the current regex, or supply a list of mitochondrial gene ids? The behavior of not using vars.to.regress should be the default". Decided the same day: both the workflow (a separate session, branch `vars_to_regress_dev`) and scRust get the options, with the same names and rules; a list holds gene ids, matched against `features.tsv`'s column 1; the regression takes a list of variables. + +*The code path, as researched in the pinned env* (`validation/R/regress_vectors.R`: every function named here, installed, is `identical()` to the source tarball's; the code path's facts below): +1. **`SCTransform.Seurat`** takes `latent.data <- object[[vars.to.regress]]` (the meta.data columns of those names) and passes meta.data as `cell.attr`; `.StdAssay` (v5) wraps each counts layer in a v3 `Assay`, the emptyDrops objects reach `.Assay` directly, and `SCTransform.default` stops unless every name is a meta.data column. `vars.to.regress` does not reach `vst()` (its model stays `y ~ log_umi`): the fits, the residual statistics, the variable features and `correct()`'s corrected counts are those without it. +2. **The second regression.** `SCTransform.default` takes the variable features' residuals (`vst.out$y[top.features, ]`), clips them to `clip.range`, then calls `ScaleData(scale.data, vars.to.regress, latent.data, model.use = "linear", use.umi = FALSE, do.scale = FALSE, do.center = TRUE, scale.max = Inf, block.size = 750)`. With the sequential `future` plan, `ScaleData.default` calls `RegressOutMatrix()` once on all rows (rows of `scale.data` named like a variable would be added as covariates): `qr <- lm(GENE ~ v1 + v2 + ..., data = cbind(latent.data, GENE = row 1), qr = TRUE)$qr` once, then `qr.resid(qr, y = row)` for every row. Then `FastRowScale` centres each row (`rowMeans2(na.rm = TRUE)`; the blocks of 750 rows change nothing) and `NA` becomes 0. +3. **The QR** is LINPACK's `dqrdc2` as R modifies it (`lm.fit` → `Cdqrls` → `dqrls`, `tol = 1e-07`): Householder reflections with a limited column pivoting that moves a column whose norm falls below `tol` times its original norm to the right-hand edge, and the rank. `qr.resid()` returns `y` at rank 0, else `dqrrsd` → `dqrsl(job = 10)`: `Q'y`, its first `rank` entries zeroed, multiplied by `Q`. An all-zero covariate (`percent.mt` where no feature matches) is moved to the edge and leaves rank 1: the regression on the intercept alone; a constant or collinear covariate goes the same way. `Cdqrls` stops on a non-finite value; `lm()`'s `na.omit` drops a cell with a missing value, and `qr.resid()` then stops on the row count. +4. **BLAS.** `dqrdc2` and `dqrsl` are Fortran in `libR.so`, without FMA, and call OpenBLAS's `dnrm2`, `dscal`, `ddot` and `daxpy`, whose kernels sum in different orders and fuse multiply-adds: every row's `qr.resid` is kernel-dependent, so R's own runs differ across kernels in the last bits of most of `scale.data` (M15b measured it). +5. **The v5 path** keeps the regressed values: `.StdAssay`'s `FetchResiduals()` finds every variable feature in `scale.data` and computes none again (it reorders the rows to the assay's gene order). +6. **`PercentageFeatureSet()`** (Seurat 5.5.1): the features (given, or `grep(pattern, rownames)`), intersected with the layer's row names (repeats and unknown names drop), `colSums()` of their rows (Matrix's `Csparse_colsum`: double, stored order), divided by meta.data's `nCount_`, times 100. R's `grep(perl = FALSE)` is TRE, where `(?i)` makes `"(?i)^mt-"` match `m`/`M`, `t`/`T`, `-` at a name's start; the names are Seurat's: `Read10X()`'s `make.unique()` of column 2, then `CreateSeuratObject()`'s `_` and `|` to `-`, so `mt_Co1` matches as `mt-Co1`. + +*The port:* +- **`rcompat::linpack`:** `dqrdc2`, `dqrsl` (job 10, `QrResid`) and `lm_qr`, statement by statement, through OpenBLAS (`daxpy_` and `dscal_` join `ddot_` and `dnrm2_`); each Householder vector passed as a contiguous copy with `qraux(j)` in place of `x(j,j)`, as `dqrsl` swaps it in for the call. **`sctransform::regress`:** `Regression` (the QR, once) and `regress_rows` (threads share the rows); `residuals_with` and `finish_full` regress `scale.data`'s clipped rows before the centring, then set NaN to 0; `SctParams::vars_to_regress`. Without it the code path is the one before M15b, unchanged. +- **`scio::features`:** Seurat's row names (`make_unique`, R's `do_makeunique`), the pattern as TRE matches it, id lists, and `Counts::percent_feature_set`. **`cluster::covariates`:** `percent.mt`'s definition (`MtGenes`), its computation and record (`PercentMt`), the covariates' names and values; `chain::cluster_counts_with` takes them in memory (`CellCovariates`, A3), computes `percent.mt` before SCTransform and hands the QR to it. +- **The options (shared with the workflow):** `--vars-to-regress [,...]` (`[sctransform] vars_to_regress`), none by default: `percent.mt`, `nCount_RNA`, `nFeature_RNA`, or a numeric column of `--metadata`, read as R's `read.table()` reads numbers (`R_strtod`, `rcompat::as_numeric`); an unknown or repeated name, or a missing, non-numeric or non-finite value, is an error. `--mt-genes ` (`mt_genes`; relative to a parameter file's directory): one id per line, each line trimmed, blank lines and lines starting with `#` skipped, matched against column 1 (each feature once); ids not found are reported and skipped, none found is an error. Without it, the workflow's pattern on Seurat's row names. No feature matched and `percent.mt` regressed: an error naming `--mt-genes`; not regressed: zeros, with a warning. `percent.mt` is written (`cell_metadata.tsv` of `scrust sctransform`, `metadata.tsv` after `nFeature_RNA`) when asked for: by `--vars-to-regress percent.mt`, `--mt-genes` or `--percent-mt` (`percent_mt`). Without any, every output is byte for byte what it was. +- **Refused besides** (R would not regress the column as named): a name that is not syntactic in R (`make.names(x) != x`, reserved words included), `GENE` (the formula's response), a name that is also a feature's; the staged starts (`--sct`, `--pca`, `--snn`) given the options (the regression is SCTransform's; `percent.mt` reaches them in `cell_metadata.tsv`); `scrust sctransform --metadata` without a regressed column. +- **Records:** `run.parameters.sctransform` (`vars_to_regress`, `percent_mt`, `mt_genes`, only when set); `result.sctransform.regression` (the covariates, the QR's columns, rank, pivot and tolerance) and `result.sctransform.percent_mt` (the pattern, or the file and its SHA-256; the features matched, their number and the first 50; the ids not found, their number and the first 10; the cells at 0); `run.notes` (the warnings); the `--mt-genes` and regressed `--metadata` files digested in the provenance, and `--metadata` kept in the command when its columns are regressed. +- **`scrust doubletfinder`:** the parameter files of clustering on the fly and of the re-clustering take the `[sctransform]` keys, and `--cluster-metadata` and `--recluster-metadata` give `--metadata`. DoubletFinder's own SCTransform never regresses, as DoubletFinder's R code calls it. +- **Not as the workflow's saved objects:** `percent.mt` is always the RNA counts' share (the shared rule), where `doubletfinder.R` and `scdblfinder.R`, as they ran, computed the SCT assay's (C1). The user decided (2026-11-19) that the workflow computes it on the RNA assay everywhere, with or without the regression, so only the objects saved before that hold the SCT assay's. +- **Grading across kernels** (decided 2026-11-19): the regression makes R's own `scale.data` differ across kernels in most of its entries, beyond `[clustering.floor.kernel]`. A run that regressed is graded against `[clustering.floor.kernel_regressed]`, R against R across kernels with the regression, measured on M15b's cases (T, P and the two other objects) as M8 and M11 measured `[clustering.floor.kernel]`, and used only when both runs record the same non-empty `vars.to.regress`; `[clustering.floor.kernel]` and every unregressed grading stay as they were. Exactness against R's run of the same profile stays the main criterion (C5's K14). + ### C4. Validation data **Reference runs** (A4) use the workflow's calls and seed, in the pinned env: @@ -1042,12 +1067,13 @@ The `knn` crate doesn't replace Annoy: Annoy's search is approximate, and Seurat | K12 on the fly | `scrust doubletfinder` given no `--clusters`, on the 150 DoubletFinder inputs: the labels it computed against the inputs' `seurat_clusters`; the outputs against the saved outputs (M7's criteria) and against M7's Rust outputs; the numbers the inputs' workflow jobs logged; `clusters/` against `scrust cluster --counts `'s output | identical; files byte-identical apart from timings and the clustering's own outputs (`clusters/`, `result.clustering`); `clusters/` byte-identical to `scrust cluster`'s files, its `summary.json` apart from the timings, the command line and the entries of `pca/` and `neighbors/`, which it does not write | | K12 re-clustering | `scrust doubletfinder --recluster`: (a) against the two-command route (`scrust doubletfinder`, then `scrust cluster --counts /singlets`), with and without the export, on T and P in both profiles and on the 150 without the export; (b) the singlets' labels and levels, silhouette widths and purities (and `nCount_SCT`, `nFeature_SCT` with the export) against the saved DoubletFinder objects, and their jobs' logged numbers, on the 150 and T; (c) without the new options, M7's files on the 150 | (a) byte-identical apart from the timings and the command line in `summary.json`; (b) identical in the production profile; (c) byte-identical | | K13 markers (Seurat loader) | the workflow's marker steps on the loaded object, for every cluster: the combined table against the saved `_markergenes.csv` (T and P) | byte-identical | +| K14 `vars.to.regress` and `percent.mt` (M15b) | the chain with SCTransform's `vars.to.regress` from the counts, on M15b's 134 cases (C3j: T, P and two objects whose annotation names the mitochondrial genes otherwise; `percent.mt` by the pattern or by a list of ids, with `nCount_RNA`, a `--metadata` column), against R's runs of the same cases in both profiles: (a) R's run of the same profile, every check of K8's direct comparison plus `percent.mt`, the regression's covariates, rank and pivot, and `scale.data` value by value; (b) R's run of the other profile, the same checks; (c) without the regression, `percent.mt` against the saved objects; (d) without the options, M15's T and P runs; (e) `scrust doubletfinder`'s clusterings with the options against the commands run one after the other | (a) identical: the main criterion, production against production and portable against portable; (b) the BLAS-free checks exact, the BLAS-dependent ones within `[clustering.floor.kernel_regressed]`, R's own differences across kernels with the regression (M15b), used only when both runs record the same non-empty `vars.to.regress`; (c) identical, where the workflow computed it from the RNA counts (the saved DoubletFinder objects' is the SCT assay's, C1, which R's recomputation reproduces); (d) and (e) byte-identical | | Saved outputs (T, P, full panel) | `seurat_clusters` and its levels, `silhouette_width`, `neighborhood_purity` (from M12), `nCount_SCT` and `nFeature_SCT` (from M13), the logged numbers; `SCT_snn_res.0.8` for T and P | identical | | Parameter grid | every grid cell's labels against Seurat run directly | target identical; floor ARI ≥ 0.99, with every difference traced to a near-tie (A7b) | | Threads | the outputs at 1 and at many threads | byte-identical | | Performance | peak RSS and wall time against R's direct run of the chain without UMAP (with UMAP, for context), with purity's and the export's shares reported | lower memory and time; at most 10 GiB on the 79,409-cell objects | -K3–K7 and K9 use no BLAS, so under teacher forcing they are exact on any machine (A5b). K10's μ is a BLAS product, so its exact check needs the reference's kernel even when teacher-forced. +K3–K7 and K9 use no BLAS, so under teacher forcing they are exact on any machine (A5b). K10's μ is a BLAS product, so its exact check needs the reference's kernel even when teacher-forced. K14's regression goes through LINPACK's QR, whose BLAS calls make most of `scale.data` kernel-dependent, in R as in the port; that is why it has a floor of its own, and `[clustering.floor.kernel]` stays as M8 and M11 measured it. ### C6. Milestones @@ -1060,17 +1086,18 @@ K3–K7 and K9 use no BLAS, so under teacher forcing they are exact on any machi | M12 | Neighbourhood purity: `knn`'s exact search with knncolle's arithmetic (the 50th distance, the radius, the range query) and the certificate; `neighborPurity`'s weights and sums; purity in `scrust cluster` | K9 on T and P, teacher-forced and end to end; the saved purities identical on T and P in the production profile (the portable runs' differences graded by the floor, as M8 measured); time measured on the largest objects. **Decision point:** if the certificate flags any pair, port KMKNN (C3e) or agree with you how to treat the flagged cells. **Outcome:** it flags the median pair of every odd-sized object and nothing else; the user chose to keep the exhaustive result and report the flagged pairs, graded "flagged, reported" (C3e, C5) | | M13 | Corrected counts and the export:
- the port of `correct()`, the log1p, `nCount_SCT` and `nFeature_SCT`;
- `scrust sctransform --corrected-counts` and `scrust cluster --export`;
- the export's layout, comment lines and README;
- the manifest for every command, `scrust doubletfinder`'s included | K10 on T and P in both profiles; every file the manifest lists present and described; `Read10X` and `read_10x_mtx` fail on the export as designed; the export's memory and time measured | | M14 | Loaders: the R package (Seurat, SingleCellExperiment) and the Python package (AnnData), with their commands, in `loaders/`; their tests in hermetic envs (A2) | K11 and K13 on T and P; the R loader ready for M17's comparisons | -| M14b | User documentation of the tools' formats and of chaining them (the user's request of 2026-11-18: "documentation about the formats for exports for each tool, and how data loaders facilitate the chaining together of tools into workflows", with "a graphical schematic"):
- a page per command (`doubletfinder`, `sctransform`, `pca`, `neighbors`, `cluster`): its inputs, its outputs and their formats, and how to read each, with standard readers and with the loaders;
- a page on chaining: which outputs feed which tools (for example `scrust cluster`'s labels into `scrust doubletfinder --clusters`, or into R decontX's `z`), and where the loaders let R and Python steps join;
- a schematic, for example a Mermaid diagram in the markdown, which GitHub renders;
- the standing rule (A7's cycle, step 7): every later milestone or port that adds or changes a tool updates these pages and the schematic | every file, column and command the pages name checked against real outputs | +| M14b | User documentation of the tools' formats and of chaining them (the user's request of 2026-11-18: "documentation about the formats for exports for each tool, and how data loaders facilitate the chaining together of tools into workflows", with "a graphical schematic"):
- a page per command (`doubletfinder`, `sctransform`, `pca`, `neighbors`, `cluster`): its inputs, its outputs and their formats, and how to read each, with standard readers and with the loaders, the options and files M15 and M15b added included (`clusters/`, `singlets_clusters/`, `--vars-to-regress`, `--mt-genes`, `--percent-mt`, `percent.mt`);
- a page on chaining: which outputs feed which tools (for example `scrust cluster`'s labels into `scrust doubletfinder --clusters`, or into R decontX's `z`), and where the loaders let R and Python steps join;
- a schematic, for example a Mermaid diagram in the markdown, which GitHub renders;
- the standing rule (A7's cycle, step 7): every later milestone or port that adds or changes a tool updates these pages and the schematic | every file, column and command the pages name checked against real outputs | | M15 | Clustering on the fly: the chain as a library entry point in `cluster` (`cluster_counts`, A3's in-memory rule's pilot), for later ports too (C3h); `scrust cluster --counts` as read–call–write; `scrust doubletfinder` given no `--clusters` (`--cluster-preset`, `--cluster-params`, `--cluster-stats`); the singlets' re-clustering in process (`--recluster`, `--recluster-preset`, `--recluster-params`, `--recluster-export`; the user's request, 2026-11-18); the benchmark harness moved into `validation/benchmark/` | K12 on all 150 DoubletFinder inputs, and the re-clustering's checks (C5); the in-memory rule's test in cargo test; the memory peak measured against M7's runs and against the two-command route; the benchmark's rows (`docs/benchmarks.md`) | +| M15b | SCTransform's `vars.to.regress` and the workflow's `percent.mt` (the user's request of 2026-11-19; C3j):
- the code path researched in the pinned env (C3j);
- LINPACK's QR as R modifies it (`dqrdc2`, `dqrsl`) in `rcompat::linpack`, through the same OpenBLAS; Seurat's `RegressOutMatrix` and the centring after it in `sctransform`;
- `PercentageFeatureSet()`, the workflow's pattern and Seurat's row names in `scio::features`; the covariates handed to the chain in memory (`cluster::covariates`, A3);
- the options shared with the workflow (`--vars-to-regress`, `--mt-genes`, `--percent-mt`; `--metadata` as a covariate) in `scrust sctransform`, `scrust cluster` and both of `scrust doubletfinder`'s clusterings, none by default;
- `percent.mt` in the outputs, the records in `summary.json`, the loaders;
- new R reference runs of the chain with `vars.to.regress` (approved for M15b) | K14 (C5); without the options, every output byte-identical to M15's; `scrust doubletfinder`'s clusterings with the options equal to the commands run one after the other; the loaders carry `percent.mt`; the benchmark's rows | | M16 | The parameter grid (C4) | every grid cell identical, or A7b's floor met with every difference traced | | M17 | Full panel: the exports (sbatch arrays); the Rust runs with `--export`, on each job's CPU type; the comparison with the saved labels, silhouette widths, purities and logged numbers (the purities cover the pairs M12's certificate flags, so any such pair R's KMKNN dropped would show there); the R loader's comparison of the SCT layers, the PCA and the graphs | all 840 objects identical; a summary table and TSV | M9 and M10 come before M11 for the reason M3 came first in Step 1: the new code is checked on R's own inputs, on any machine, before it is chained after the stages that depend on BLAS. -**Order after M11:** M12, M13, M15 and M16 each need only M11. M14 needs M13, M14b needs M14, and M17 needs M11–M14. Apart from M13 coming before M14 and M14 before M14b, M12–M16 can be taken in any order. +**Order after M11:** M12, M13, M15 and M16 each need only M11. M14 needs M13, M14b needs M14, and M17 needs M11–M14. M15b needs M15 and M14 (its loaders carry `percent.mt`), and comes before M14b, which documents its options with the rest. Apart from M13 coming before M14, M14 before M14b and M15b before M14b, M12–M16 can be taken in any order. **What belongs in Step 2, and what can follow:** -- **In Step 2:** M8–M17, and M14b. Step 2 is complete when M11–M15 are met, with M16 and M17 as confirmation (Verification). +- **In Step 2:** M8–M17, M14b and M15b. Step 2 is complete when M11–M15 and M15b are met, with M16 and M17 as confirmation (Verification). - **Can follow, outside Step 2:** - a port of KMKNN for purity. It would decide the pairs M12's certificate flags exactly (the median pair of odd-sized objects, which M12 reports and M17's saved purities check), and make the search faster on very large objects. Nothing in Step 2 depends on it (M12's decision); - in decontX's port, its three sources of clusters (A7b): `--clusters`, clustering on the fly through C3h's entry point, and decontX's own clustering with the workflow's fallback when there are fewer than two clusters. Which is the default is decided in decontX's planning; @@ -1121,4 +1148,4 @@ M9 and M10 come before M11 for the reason M3 came first in Step 1: the new code - **Each milestone:** its "Done when" column. `cargo test` covers tier T on every change; sbatch validation runs produce tier-P and full-panel reports in `docs/validation/`. - **Step 1 complete:** M6 met (with M7 as the full-panel confirmation), and the benchmark table shows the memory and time gains over the direct R run. - **Part C:** check it against the sources (Seurat 5.5.1, SeuratObject 5.4.0, sctransform 0.4.3, RcppAnnoy 0.0.23, bluster 1.20.0, BiocNeighbors 2.4.0 and assorthead 1.4.0's knncolle), the workflow's scripts, and the production logs. -- **Step 2 complete:** M11–M15 met, with M16 (the parameter grid) and M17 (the full panel) as confirmation, and the benchmark showing the memory and time gains over the direct R run of the chain. +- **Step 2 complete:** M11–M15 and M15b met, with M16 (the parameter grid) and M17 (the full panel) as confirmation, and the benchmark showing the memory and time gains over the direct R run of the chain. diff --git a/docs/benchmarks.md b/docs/benchmarks.md index d8d53e3..5c1fe84 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -4,9 +4,9 @@ This page compares each Rust port with the workflow's R step it replaces. It rep It grows with the ports. Each new tool adds its rows, with the same method and columns, and the findings are updated (docs/PLAN.md, A7's cycle, step 6). -**Last updated:** 2026-11-18. The first benchmark covers DoubletFinder (Step 1) and the clustering chain (M11–M13). M15 added DoubletFinder clustering its own input, and its whole rule in one process. +**Last updated:** 2026-11-19. The first benchmark covers DoubletFinder (Step 1) and the clustering chain (M11–M13). M15 added DoubletFinder clustering its own input, and its whole rule in one process. M15b added the chain with SCTransform's `vars.to.regress`. -## Findings (2026-11-18) +## Findings (2026-11-19) - **CPU time:** at one thread, Rust uses 2.1–7.1× less CPU time than R: - the clustering chain: 2.6–7.1× without `--export`, 2.1–4.6× with it; @@ -29,19 +29,20 @@ It grows with the ports. Each new tool adds its rows, with the same method and c - The hand-off saves the second command's start and its reading of `singlets/`. That is under 2% of the rule, within the spread of DoubletFinder's own runs. - At 32 threads it finishes 3–12% sooner. - Against R's whole rule: 2.7–3.0× less CPU time, 9–38× less memory. +- **The chain with `vars.to.regress` (M15b):** against R's scripts as they ran with the regression, Rust takes 2.7–6.7× less CPU time at one thread (2.1–3.7× with `--export`), 8.8–44× less memory, and finishes 14–20× sooner at 32 threads. The regression costs Rust nothing measurable (0.98–1.01× on the same node) and raises R's peak by up to 12%. ## Method -- **R** runs copies of the workflow's own scripts, with phase-marker lines added and nothing else changed (checked byte for byte; sources at pipeline commit `ea053fa`). +- **R** runs copies of the workflow's own scripts, with phase-marker lines added and nothing else changed (checked byte for byte; sources at pipeline commit `ea053fa`; for M15b's rows, at `8d34de1^`, when they still regressed `percent.mt`). - It runs as the workflow's jobs do: 1 CPU, the six `*_NUM_THREADS` set to 1, the production R env, seed 12345, the production inputs. - Steps not yet ported are timed but left out of the comparison: SoupX, emptyDrops with `logNormCounts` and `as.Seurat`, and RunUMAP. Their cost is in the [last table](#workflow-steps-not-yet-ported). -- **Rust** runs `scrust` (binary built from `b6f6e4e`; M15's rows, `8ab8fc8` and `49e8be7`, [below](#doubletfinder-clustering-its-own-input-and-the-whole-rule-in-one-process-m15)) in the production profile, at `--threads 1` and `--threads 32`. +- **Rust** runs `scrust` (binary built from `b6f6e4e`; M15's rows, `8ab8fc8` and `49e8be7`, [below](#doubletfinder-clustering-its-own-input-and-the-whole-rule-in-one-process-m15); M15b's, `25fe846`, [below](#the-chain-with-sctransforms-varstoregress-m15b)) in the production profile, at `--threads 1` and `--threads 32`. - **Repeats and nodes:** each case runs 3 times, and the tables give the median. All runs are on Xeon Platinum 8480CL nodes of the `sapphire` partition. - Inputs are evicted from the page cache before each run, so every read is cold. - Most R runs shared a node with other benchmark runs, as the workflow's 1-CPU jobs do. Repeats vary by up to 25% in CPU time for R and 13% for Rust. - **Checks:** every run was checked before it was counted. - Every Rust output is byte-identical to the reference runs. - - Every R run reproduces the workflow's number of clusters, and its `.rds` is within 10 bytes of the workflow's saved one. + - Every R run reproduces the workflow's number of clusters, and its `.rds` is within 10 bytes of the workflow's saved one. M15b's R runs, which have no saved object, reproduce the clusters and cluster ids of M15b's R reference runs of the same chain. - **The harness** is in [`validation/benchmark/`](../validation/benchmark/README.md) (since M15): the sampler `procmon.py`, the R script copies, the jobs (`run_r.sbatch`, `run_rust.sbatch`, with the binary as `SCRUST_BIN`), and the analysis and report scripts. Moved from `data/benchmarks/scripts/` and run again over the first benchmark's runs, it gives the first tables, `checks.tsv` and `benchmark.md`'s tables byte for byte (the notes `report.py` appends are now the harness's README); the copy in `data/benchmarks/scripts/` is kept as it ran. - **Data** are in `data/benchmarks/`, which is not in git: - `benchmark.md`: the full tables, with ranges, the read and write parts and the 32-thread columns; @@ -146,6 +147,41 @@ Elapsed seconds at 1 / 32 threads: - **The whole rule in one process** takes the same CPU time as the two commands at one thread (0.98–1.04×), at the same peak, which DoubletFinder sets. The hand-off saves the second command's start and its reading of `singlets/`. The in-process re-clustering takes 0.93–0.98× the separate command's CPU time (the median of each object's three repeats). That is under 2% of the rule, less than the spread of DoubletFinder's own phases between the two routes within a repeat: they are the same code, and took 0.93–1.06× as long at one thread. At 32 threads, where reading is a larger share of the elapsed time, the one process finishes 3–12% sooner. - **Against R's whole rule,** the one process takes 2.7–3.0× less CPU time and 9–38× less memory at one thread, and finishes 15–20× sooner at 32 threads. +### The chain with SCTransform's `vars.to.regress` (M15b) + +The clustering chain with SCTransform's `vars.to.regress = "percent.mt"`, on the seven tier-P clustering objects, three repeats, as above. + +- **R** runs the same rules' scripts as they were before the pipeline's commit 8d34de1 (2026-10-30), which still passed `vars.to.regress = "percent.mt"` to SCTransform (`validation/benchmark/workflow_regress/`). They differ from the current scripts in that argument and a comment only, so against the clustering table's R runs they show what the regression costs R. Each run's clusters and cluster ids equal M15b's R reference run of the same chain. +- **Rust** runs `scrust cluster --counts --preset workflow --vars-to-regress percent.mt` (binary `scrust-25fe846`, M15b's validation binary), without and with `--export`. Where the workflow's pattern finds no mitochondrial feature (soupx_emptydrops_sscovelli, filtered_seurat_emptydrops_sscovelli, cellbender_fromraw_ghirsutum2), R regresses an all-zero `percent.mt`, which scrust refuses by default; scrust is given the same all-zero column through `--mt-genes` with features that have no counts, as in M15b's validation. Every run's files equal M15b's validation run of the same case, byte for byte. The same binary without the regression (`b`) is the like for like for what the regression costs Rust; its files equal M13's benchmark run's. + +At one thread (CPU seconds / peak GiB; the ratios to the chain without the regression to three decimals): + +| object | R with vars.to.regress: CPU s / peak GiB | R: ÷ without (CPU, peak) | Rust with: CPU s / wall s / peak GiB | Rust: ÷ without (CPU, peak) | with --export: CPU s / peak GiB | R ÷ Rust, with: CPU · peak | R ÷ Rust with --export: CPU · peak | +|---|---|---|---|---|---|---|---| +| soupx_tenx_SRR18256555 | 54.5 / 2.98 | 0.891, 0.977 | 11.2 / 11.4 / 0.154 | 1.040, 1.041 | 14.6 / 0.155 | 4.9× · 19× | 3.7× · 19× | +| soupx_tenx_10xmousebrain | 251 / 12.7 | 0.982, 1.049 | 37.7 / 37.9 / 1.45 | 1.059, 1.006 | 78.0 / 1.45 | 6.7× · 8.8× | 3.2× · 8.8× | +| filtered_seurat_tenx_10xmousebrain | 206 / 13.2 | 1.036, 1.054 | 38.2 / 38.5 / 1.45 | 1.022, 1.006 | 78.6 / 1.45 | 5.4× · 9.1× | 2.6× · 9.1× | +| soupx_emptydrops_4500871lane | 302 / 25.3 | 1.045, 1.057 | 80.1 / 80.6 / 1.49 | 0.992, 1.006 | 101 / 1.49 | 3.8× · 17× | 3.0× · 17× | +| soupx_emptydrops_sscovelli | 813 / 67.7 | 1.153, 1.087 | 301 / 303 / 3.15 | 1.120, 1.001 | 353 / 3.34 | 2.7× · 21× | 2.3× · 20× | +| filtered_seurat_emptydrops_sscovelli | 842 / 62.5 | 1.085, 1.068 | 268 / 269 / 3.15 | 0.994, 1.001 | 328 / 3.35 | 3.1× · 20× | 2.6× · 19× | +| cellbender_fromraw_ghirsutum2 | 835 / 118.1 | 1.056, 1.122 | 310 / 312 / 2.66 | 1.070, 1.002 | 398 / 3.06 | 2.7× · 44× | 2.1× · 39× | + +At 32 threads (Rust's columns; R runs on 1 CPU): + +| object | R with vars.to.regress: CPU s / peak GiB | R: ÷ without (CPU, peak) | Rust with: CPU s / wall s / peak GiB | Rust: ÷ without (CPU, peak) | with --export: CPU s / peak GiB | R ÷ Rust, with: CPU · peak | R ÷ Rust with --export: CPU · peak | +|---|---|---|---|---|---|---|---| +| soupx_tenx_SRR18256555 | 54.5 / 2.98 | 0.891, 0.977 | 11.4 / 2.89 / 0.186 | 1.033, 1.032 | 14.2 / 0.322 | 4.8× · 16× | 3.8× · 9.3× | +| soupx_tenx_10xmousebrain | 251 / 12.7 | 0.982, 1.049 | 41.3 / 13.1 / 1.45 | 1.094, 1.006 | 81.4 / 1.45 | 6.1× · 8.8× | 3.1× · 8.8× | +| filtered_seurat_tenx_10xmousebrain | 206 / 13.2 | 1.036, 1.054 | 42.6 / 13.5 / 1.45 | 1.077, 1.006 | 81.6 / 1.45 | 4.8× · 9.1× | 2.5× · 9.1× | +| soupx_emptydrops_4500871lane | 302 / 25.3 | 1.045, 1.057 | 97.5 / 21.2 / 1.49 | 1.060, 1.006 | 113 / 1.49 | 3.1× · 17× | 2.7× · 17× | +| soupx_emptydrops_sscovelli | 813 / 67.7 | 1.153, 1.087 | 336 / 55.8 / 3.20 | 1.043, 1.001 | 379 / 3.41 | 2.4× · 21× | 2.1× · 20× | +| filtered_seurat_emptydrops_sscovelli | 842 / 62.5 | 1.085, 1.068 | 311 / 52.0 / 3.20 | 1.010, 1.000 | 362 / 3.42 | 2.7× · 20× | 2.3× · 18× | +| cellbender_fromraw_ghirsutum2 | 835 / 118.1 | 1.056, 1.122 | 376 / 52.3 / 2.69 | 1.178, 1.003 | 445 / 3.11 | 2.2× · 44× | 1.9× · 38× | + +- **Against R with the regression,** at one thread Rust takes 2.7–6.7× less CPU time without `--export` and 2.1–3.7× less with it, and 8.8–44× less memory. At 32 threads it finishes 14–20× sooner without `--export` and 12–17× sooner with it (R's elapsed time against Rust's). +- **What the regression costs Rust: nothing measurable.** Run on the same node, the regressed chain took 0.98–1.01× the CPU time of the same binary's chain without it (seven pairs of repeats). The medians across nodes, 0.99–1.12× at one thread and 1.01–1.18× at 32 threads, reflect the nodes: repeats of one variant on different nodes differ by up to 15% (soupx_emptydrops_sscovelli's 1.12 comes from two repeats on a slower node, 301 s against 263 s for the third). The peak is the same (1.000–1.006×; 1.04× on the smallest object, 6 MB). The regression itself is one QR and a few passes over `scale.data`'s rows, against SCTransform's model fits. +- **What it costs R:** R's peak rises by up to 12% with the regression (cellbender_fromraw_ghirsutum2: 118 GiB against 105 GiB; 1.05–1.09× on the five medium and large objects; 0.98× on the smallest). R's CPU time moves by −11% to +15%, within its repeats' spread (up to 25%); its runs without the regression are the first benchmark's. + ### Workflow steps not yet ported R's CPU seconds for the steps inside the benchmarked scripts that no port covers yet (median of the same 3 runs). This is today's cost for the ports still to come; each port moves its rows into a table of its own above. diff --git a/docs/output_manifest.md b/docs/output_manifest.md index cb8f5f0..82d5901 100644 --- a/docs/output_manifest.md +++ b/docs/output_manifest.md @@ -36,8 +36,8 @@ The implementation is `crates/scio/src/manifest.rs`; `scrust validate manifest - |---|---|---| | `scrust_version` | string | scrust's version (`scrust --version`) | | `command_line` | array of strings | the command line as given: `"scrust"`, the subcommand, its arguments | -| `command` | string | the command as the normalised matrices' comment lines give it: the command line without the options that change no value of the normalised matrices (`--out`, `--threads`, and for `scrust cluster` also `--keep-stages`, `--dump-stages`, `--purity-lists`, `--annoy`, `--metadata`), so that those files do not depend on where or how fast the run went | -| `inputs` | array of objects | each input the command read: `option` (the option that named it, e.g. `counts`), `path` (as given), `files` (each file read: `name`, relative to `path`; `bytes`; `sha256`). `files` is empty only for `--from-stages` (a validation input) | +| `command` | string | the command as the normalised matrices' comment lines give it: the command line without the options that change no value of the normalised matrices (`--out`, `--threads`, and for `scrust cluster` also `--keep-stages`, `--dump-stages`, `--purity-lists`, `--annoy`, `--metadata`), so that those files do not depend on where or how fast the run went. `--metadata` stays when SCTransform's `vars.to.regress` names its columns (M15b), since they change `scale.data` | +| `inputs` | array of objects | each input the command read: `option` (the option that named it, e.g. `counts`), `path` (as given), `files` (each file read: `name`, relative to `path`; `bytes`; `sha256`). `files` is empty only for `--from-stages` (a validation input). From M15b also `mt-genes` (the list of mitochondrial feature ids `percent.mt` counts) and `metadata` read before the chain when its columns are regressed; each input appears once | | `reproduces` | array of strings | the original software the outputs reproduce: R packages, functions, versions | | `parameters` | object | the parameters of the run (the same object as `run.parameters` or `run`'s parameters) | | `seeds` | object | the random seeds the run reproduces, by where R sets them | @@ -139,8 +139,8 @@ The scale tells a loader which slot a matrix may go into. Only `raw_counts` is r | `raw_counts` | `counts/matrix.mtx(.gz)` (`cluster --export`: the input, copied byte for byte); `singlets/matrix.mtx.gz` (`doubletfinder`) | matrix_market, `raw_counts` | features (the features file, column 2); cells (the barcodes file) | | `raw_counts_cells` | `counts/barcodes.tsv(.gz)`, `singlets/barcodes.tsv.gz` | tsv without header | | | `raw_counts_features` | `counts/features.tsv(.gz)`, `singlets/features.tsv.gz`: id, name, type | tsv without header | | -| `rna_cell_metadata` | `cell_metadata.tsv` (`sctransform`, `pca`, `neighbors`): barcode, nCount_RNA, nFeature_RNA | tsv | cells (`barcode`) | -| `cell_metadata` | `metadata.tsv` (`cluster`): 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 | tsv | cells (`barcode`) | +| `rna_cell_metadata` | `cell_metadata.tsv` (`sctransform`, `pca`, `neighbors`): barcode, nCount_RNA, nFeature_RNA, and percent.mt when asked for (M15b: `--percent-mt`, `--mt-genes`, `--vars-to-regress percent.mt`; its shape then has 4 columns) | tsv | cells (`barcode`) | +| `cell_metadata` | `metadata.tsv` (`cluster`): barcode, nCount_RNA, nFeature_RNA, percent.mt (when asked for, M15b), nCount_SCT and nFeature_SCT (with `--export`), each `res.` column, seurat_clusters, silhouette_width, silhouette_other, neighborhood_purity, purity_maximum, then `--metadata`'s columns | tsv | cells (`barcode`) | | `cluster_labels` | `seurat_clusters.tsv`: barcode, seurat_clusters | tsv | cells (`barcode`) | | `cluster_levels` | `seurat_clusters_levels.txt`, `_levels.txt`: a factor's levels in order, one per line | tsv without header | | | `cluster_columns` | `clusters.tsv`: barcode, one column per resolution | tsv | cells (`barcode`) | @@ -194,4 +194,5 @@ The loaders, `loaders/R/scrustio` (Seurat, SingleCellExperiment) and `loaders/py - `sct_scale_data`'s rows are in `VariableFeatures()` order; Seurat keeps `scale.data`'s rows in the SCT assay's gene order (C3g), which `sct_features` gives. - Check `sha256` before reading, when the user asks for it (a file can be large). - A file of role `cluster_levels` holds the levels of the column it is named after (`_levels.txt`). Version 1 has no field that links a levels file to its column, so this is the one place the loaders read a file's name: to know which column a file found by its role belongs to, not to find it. Fields may be added within the version: a field naming the column (`levels_of`, say) would let a loader do without the name. +- `metadata.tsv`'s and `cell_metadata.tsv`'s `percent.mt` (M15b, when the output computed it) is a double column, `%.17g` text, `NaN` for a cell without counts: the loaders type it so, after `nFeature_RNA`, as the workflow's objects hold it. What defined it (the workflow's pattern, or a list of feature ids with the file's SHA-256), the features it counts and the ids not found are in `summary.json`'s `result.sctransform.percent_mt`, the regression of SCTransform's `vars.to.regress` in `result.sctransform.regression`; these are records, not files, so the schema does not change. - Seurat's SCT `data` layer holds the C library's `log1p` of the corrected counts (R's). The loaders read it from the `sct_data` file and check it against `log1p` of `sct_counts`; Python must use `math.log1p` for that check, since numpy's `np.log1p` can differ in the last bit (M14). diff --git a/docs/validation/clustering.md b/docs/validation/clustering.md index ed5afc5..8b801d4 100644 --- a/docs/validation/clustering.md +++ b/docs/validation/clustering.md @@ -1,4 +1,4 @@ -# Clustering in Rust (Step 2; milestones M11 to M15) +# Clustering in Rust (Step 2; milestones M11 to M15b) M11 runs the workflow's clustering chain end to end in Rust, from the counts to the labels and the silhouette widths (docs/PLAN.md C1, C3, C5, C6): SCTransform at seed 12345, the workflow's PCA guard, RunPCA with 50 PCs, FindNeighbors (Annoy, k = 20, dims 1:30), FindClusters (Louvain, resolution 0.8, seed 12345, singletons grouped) and bluster's `approxSilhouette`. It chains the `sctransform` and `pca` crates of Step 1 with M9's `neighbors` and M10's `cluster`, and adds the silhouette widths, `scrust cluster --counts` with its staged starts, parameters, preset and TOML file, and `scrust validate cluster` for the whole chain. It also adds kernel-gated grading (A5b mechanism 3) to both validators and a kernel check to the fixture tests. @@ -8,10 +8,32 @@ M13 adds the rest of the SCT assay, the corrected counts of sctransform's `corre M14 adds the loaders: an R package (Seurat, SingleCellExperiment) and a Python package (AnnData) that read any scrust output through its manifest and put each matrix only into a slot meant for its scale. Each loader's object is compared with the saved workflow object (K11), and the workflow's own marker steps run on the Seurat loader's object (K13). Its outcome comes after M15's ([M14 outcome](#m14-outcome)), its details after M13's ([M14: the loaders](#m14-the-loaders)). -M15 makes the chain one library entry point and runs it inside `scrust doubletfinder`: to cluster an input given no labels (K12, on all 150 DoubletFinder inputs) and, when asked, to re-cluster the singlets as the workflow's rule does before saving them, the singlets handed over in memory. Its outcome comes first ([M15 outcome](#m15-outcome)), its details last ([M15: clustering on the fly and the singlets' re-clustering](#m15-clustering-on-the-fly-and-the-singlets-re-clustering)). +M15 makes the chain one library entry point and runs it inside `scrust doubletfinder`: to cluster an input given no labels (K12, on all 150 DoubletFinder inputs) and, when asked, to re-cluster the singlets as the workflow's rule does before saving them, the singlets handed over in memory. Its outcome comes after M15b's ([M15 outcome](#m15-outcome)), its details after M14's ([M15: clustering on the fly and the singlets' re-clustering](#m15-clustering-on-the-fly-and-the-singlets-re-clustering)). + +M15b ports SCTransform's `vars.to.regress` and the workflow's `percent.mt`, at the user's request: 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 (K14). Its outcome comes first ([M15b outcome](#m15b-outcome)), its details last ([M15b: SCTransform's vars.to.regress and the workflow's percent.mt](#m15b-sctransforms-varstoregress-and-the-workflows-percentmt)). This is Step 2's main report, as [doubletfinder.md](doubletfinder.md) is Step 1's; M13 to M17 extend it. The milestones before it have their own: [clustering_m8.md](clustering_m8.md) (the R reference data and the R-vs-R floor), [clustering_m9.md](clustering_m9.md) (Annoy and the SNN graph), [clustering_m10.md](clustering_m10.md) (FindClusters). +## M15b outcome + +| Done when (plan C6's M15b row, and the brief) | Result | +|---|---| +| The code path researched in the pinned env | **Recorded** in [PLAN C3j](../PLAN.md#c3-rust-design): `vars.to.regress` reaches only `scale.data` (one `RegressOutMatrix()` call: `lm()`'s QR once, `qr.resid()` per row, then the centring); `vst()`, the variable features and the corrected counts are those without it; LINPACK's `dqrdc2` with R's limited pivoting at `tol = 1e-07` calls OpenBLAS. Every function on the path is `identical()` to its source tarball's (13; [`regress_vectors.R`](../../validation/R/regress_vectors.R)). | +| The port, as a library, the covariates in memory (A3) | **Built:** `rcompat::linpack` (`dqrdc2`, `dqrsl`, `lm_qr`, through the same OpenBLAS), `sctransform::regress`, `scio::features` (`PercentageFeatureSet()`, the pattern as TRE matches it, Seurat's row names), `cluster::covariates`; `chain::cluster_counts_with` takes the covariates in memory ([What M15b built](#what-m15b-built)). | +| The options, as shared with the workflow; none by default | **Built** in `scrust sctransform`, `scrust cluster --counts` (the staged starts refuse them) and both of `scrust doubletfinder`'s clusterings (the `[sctransform]` keys of their parameter files, `--cluster-metadata`, `--recluster-metadata`); DoubletFinder's own SCTransform does not regress. The records: `run.parameters.sctransform`, `result.sctransform.regression` and `.percent_mt`, `run.notes`, the input files' digests ([percent.mt and the options](#percentmt-and-the-options)). | +| K14 (a): exact against R's run of the same profile, every case (the main criterion) | **134 of 134 in the production profile and 134 of 134 in the portable one**, 889,756,126 values compared each, none differing: the labels and levels, both graphs, the PCA, `scale.data` value by value (130 cases) or its digest, the scores, `percent.mt`, the regression's covariates, rank and pivot. The 31 cases whose pattern finds nothing reproduce R's all-zero column (rank 1) through `--mt-genes`, and scrust refused the pattern in each, naming `--mt-genes` ([the main criterion](#against-rs-run-of-the-same-profile-the-main-criterion)). | +| K14 (b): across kernels | **134 of 134 in both directions,** BLAS-free checks identical, 815 BLAS-dependent checks per direction within `[clustering.floor.kernel_regressed]`, none beyond it ([Across kernels](#across-kernels)). | +| The floor (the coordinator's decision of 2026-11-19) | **`[clustering.floor.kernel_regressed]`,** R against R across kernels with the regression, measured on all 134 cases (T, P and the two other objects; R's portable runs of P added) with the grader's statistics, as M8 and M11 measured `[clustering.floor.kernel]`, which is unchanged; used only when both runs record the same non-empty `vars.to.regress` ([the measurement, and the two floors side by side](#the-r-vs-r-measurement-with-the-regression)). | +| K14 (c): `percent.mt` without the regression against the saved objects | **The 34 clustering objects identical** (277,413 cells). **The 150 DoubletFinder objects: 120 identical; the other 30 are the SCT assay's** (`doubletfinder.R` computes it on the default assay, SCT): R's recomputation on SCT reproduces all 150 saved columns, and its RNA-based value equals scrust's on all 30 (296,410 cells). scrust keeps the shared rule, the RNA counts, which the workflow adopts everywhere (the user's decision, 2026-11-19; the saved objects keep the SCT assay's column) ([percent.mt against the saved objects](#percentmt-against-the-saved-objects)). | +| K14 (d): without the options, M15's outputs | **120 of 120 routes byte-identical** to M15's final label on T and P in both profiles: DoubletFinder given the labels, the re-clustering in process and in two commands (with and without the export), clustering on the fly, `scrust cluster --counts` ([Without the options](#without-the-options)). | +| K14 (e): `scrust doubletfinder` with the options; the in-memory rule | **20 of 20:** in process equal to the commands run one after the other, clustering on the fly equal to `scrust cluster --counts` with the same file, DoubletFinder's own files equal to M15's; and in cargo test, the entry point given the covariates in memory writes the command's files ([scrust doubletfinder with the options](#scrust-doubletfinder-with-the-options)). | +| The loaders carry `percent.mt` | **Done:** a double column, exactly as written, in Seurat (after `nFeature_RNA`, as the workflow's objects hold it), SingleCellExperiment and AnnData; listed among what the loaders do not rebuild when the output did not compute it ([The loaders](#the-loaders)). | +| Benchmark (A7 step 6) | **New rows** on the seven tier-P clustering objects, three repeats at 1 and 32 threads, against R's scripts as they ran with the regression ([M15b benchmark](#m15b-benchmark); `docs/benchmarks.md`, findings and date updated): 2.7–6.7× less CPU time at one thread (2.1–3.7× with `--export`), 8.8–44× less memory, 14–20× sooner at 32 threads. The regression costs Rust nothing measurable (0.98–1.01× on the same node); it raises R's peak by up to 12%. | +| Plan corrections | A3, A5, A5b, C1, C3 (the refused list, the commands, the outputs, C3g, C3h, a new C3j), C5 (K14), C6 (M15b's row, the order, Step 2) ([M15b corrections](#m15b-corrections-to-the-plan)). | +| User documentation | **For M14b:** M14b has not landed on main; it will document M15b's options with M15's. The commands' `--help` and the README describe them. | +| Documentation | This report and [clustering_m15b.tsv](clustering_m15b.tsv); `[clustering.K14]` and `[clustering.floor.kernel_regressed]` in `validation/tolerances.toml`; M15b's section of `validation/manifest.toml`; `docs/output_manifest.md`; the README; the commands' `--help`; NOTICE; `docs/benchmarks.md`. | +| Tests | `cargo test --workspace`: 316 tests in 47 suites, debug and release, none failing, no warnings (commit `aed8f74`, job 62091694); the loaders' tests: R 87, Python 14, all passing (job 62091155) ([M15b tests](#m15b-tests)). | + ## M15 outcome | Done when (plan C6's M15 row, and the brief) | Result | @@ -1756,3 +1778,379 @@ bash validation/slurm/m15_manifest.sh m15- [,...]`** (`[sctransform] vars_to_regress`), none by default: `percent.mt`, `nCount_RNA`, `nFeature_RNA`, or a numeric column of `--metadata`, whose numbers are read as R's `read.table()` reads them (`R_strtod`). An unknown or repeated name, or a missing, non-numeric or non-finite value, is an error. +- **`percent.mt`** is `PercentageFeatureSet()`: the counts of the mitochondrial features summed per cell, divided by `nCount_RNA`, times 100, in R's order of operations. Its features are, by default, those the workflow's pattern `"(?i)^mt-"` finds among Seurat's row names (`features.tsv`'s column 2 made unique, `_` and `|` to `-`). **`--mt-genes `** lists their ids instead: one per line, each line trimmed, blank lines and `#` lines skipped, matched against column 1, each feature once; ids not found are reported and skipped, none found is an error. +- **No feature matched:** with `percent.mt` regressed, an error naming `--mt-genes`, since R would regress an all-zero column without a word; without, a column of zeros and a warning. +- **The column** is written only when asked for (`--vars-to-regress percent.mt`, `--mt-genes` or `--percent-mt`): in `metadata.tsv` after `nFeature_RNA`, and in `scrust sctransform`'s `cell_metadata.tsv`. Without any of them, every output is byte for byte what it was. +- **Records** (`summary.json`): `run.parameters.sctransform` (`vars_to_regress`, `percent_mt`, `mt_genes`, each only when set); `result.sctransform.regression` (the covariates, the model, the QR's columns, rank, pivot and tolerance); `result.sctransform.percent_mt` (the pattern, or the file and its SHA-256; the features matched, their number and the first 50; the ids not found, their number and the first 10; the cells at 0 and the cells without counts); `run.notes` (the warnings). The `--mt-genes` file and a regressed `--metadata` file are inputs, digested in the manifest's provenance. +- **`scrust doubletfinder`:** the parameter files of clustering on the fly and of the re-clustering take the `[sctransform]` keys, and `--cluster-metadata` and `--recluster-metadata` give each its `--metadata`; `clusters/` and `singlets_clusters/` then hold what `scrust cluster --counts` writes with the same options. DoubletFinder's own SCTransform never regresses, as DoubletFinder's R code calls it. + +### How the checks work + +- **The code path and the vectors** ([`validation/R/regress_vectors.R`](../../validation/R/regress_vectors.R), in the production R env, by sbatch; log `data/clustering/logs/m15b/regress_vectors.txt`): every function of the code path, installed, is `identical()` to the source tarball's; fourteen QR models from R's `lm()` (n from 2 to 613, p 2 or 3; rank-deficient: an all-zero, a constant, a nearly constant and a collinear covariate, and a wide matrix) with their `qr`, `qraux`, rank and pivot, and `qr.resid()` on rows of each; the pattern's matches on 22 names (case, the hyphen, look-alike characters, a name that only starts like it); Seurat's row names (`make.unique`, `_` and `|` to `-`); `PercentageFeatureSet()` on integer and real counts. All in the portable profile (`dqrdc2` and `dqrsl` call BLAS). The committed fixtures: `tests/fixtures/rcompat/linpack_*.tsv.gz`, `tests/fixtures/clustering/percent_mt/` and `tests/fixtures/clustering/m15b/`. +- **The cases** ([`validation/m15b_cases.tsv`](../../validation/m15b_cases.tsv), by [`m15b_cases.py`](../../validation/python/m15b_cases.py)), 134: + - the 27 tier-T objects (no mitochondrial gene by the pattern; a stand-in list, the ribosomal protein genes): `pm` (`percent.mt` by the pattern, all 0), `ids` (by a list of ids), `ids_ncount` (`percent.mt` and `nCount_RNA`), `meta` (a `--metadata` column, `score`, written with R's number formats and a leading `+`); + - the four mouse tier-P objects (13 mitochondrial genes named `mt-`), the same four cases; + - the three other tier-P objects, whose pattern finds nothing: `pm`, and `meta` on filtered_seurat_emptydrops_sscovelli; + - two objects whose annotation names them otherwise: the zebrafish (soupx_tenx_drerio: the pattern finds its two `mt-` rRNAs; the list names those and its 13 protein genes, `ND1`, `COX1`, ...) and the bearded dragon (soupx_tenx_pvitticeps: the pattern finds none; the list names its 13), each `pm`, `ids`, `ids_ncount`. Their lists hold repeated ids, ids with spaces around them, comment lines and two ids that are no feature's. +- **R's runs** ([`m15b_references.sbatch`](../../validation/slurm/m15b_references.sbatch); approved for M15b): `validation/R/reference_clustering.R` runs the chain as `lib/clustering.R` runs the workflow's, with `PercentageFeatureSet()` before SCTransform and `vars.to.regress` given, in both profiles, as direct runs at level full on tier T, standard elsewhere (both keep `scale.data`), and light on the three largest objects (`scale.data`'s digest only). 268 runs: each case in the production profile (SapphireRapids) and in the portable one (Haswell). +- **Scrust's runs** ([`m15b_cluster.sbatch`](../../validation/slurm/m15b_cluster.sbatch), label `m15b-25fe846`): `scrust cluster --counts --preset workflow` with the case's options, in both profiles, `--keep-stages` where R kept `scale.data`; `scrust validate cluster` against both R runs of the case. Where R's pattern finds no feature, scrust is given R's all-zero column through `--mt-genes` with features that have no counts, and the task checks that `--vars-to-regress percent.mt` by the pattern is refused, naming `--mt-genes`. [`m15b_revalidate.sbatch`](../../validation/slurm/m15b_revalidate.sbatch) validated the same runs again with the final binary's validator. +- **`scrust validate cluster`** compares, besides M11's checks (the labels and levels, every `res.` column, the PCA, the graphs, the silhouette widths, the purities, R's digests): `percent.mt` as text (from the counts: BLAS-free, so exact on any kernel), the regression's record (the covariates, rank, pivot and tolerance), `percent.mt`'s features (when both runs define it the same way), and `scale.data` value by value, rows matched by name, where R kept it. The grading is M11's: exact when both runs recorded the same OpenBLAS kernel, otherwise the BLAS-dependent checks against the floor. +- **`percent.mt` against the saved objects, without the regression:** [`m15b_saved.sbatch`](../../validation/slurm/m15b_saved.sbatch) exports the saved objects' `percent.mt` (`validation/R/export_percent_mt.R`, reading each `.rds` in a batch job): M8's 34 clustering objects and M7's 150 DoubletFinder objects. [`m15b_saved_rust.sbatch`](../../validation/slurm/m15b_saved_rust.sbatch) computes scrust's by the workflow's pattern (`scrust cluster --counts --percent-mt --stats none`; for the DoubletFinder objects, the singlets' re-clustering with `percent_mt = true`), and [`m15b_percent_mt.py`](../../validation/python/m15b_percent_mt.py) compares the columns as `%.17g` text, so bit for bit. [`m15b_percent_mt_sct.sbatch`](../../validation/slurm/m15b_percent_mt_sct.sbatch) computes `PercentageFeatureSet()` on each saved DoubletFinder input's SCT and RNA assays, at the singlets ([`percent_mt_sct.R`](../../validation/R/percent_mt_sct.R)). +- **The defaults:** [`m15b_unchanged.sbatch`](../../validation/slurm/m15b_unchanged.sbatch) compares the M15b binary's runs of M15's T and P check ([`m15_recluster.sbatch`](../../validation/slurm/m15_recluster.sbatch): DoubletFinder given the labels; the re-clustering in process with and without the export; the two-command route with and without it; clustering on the fly; `scrust cluster --counts`) with M15's final label's (`m15-a5de5e3`), route by route: every file byte for byte, `summary.json` as JSON without the timings, the command line and what records the node. +- **`scrust doubletfinder` with the options** ([`m15b_recluster.sbatch`](../../validation/slurm/m15b_recluster.sbatch), on the five T and five P DoubletFinder objects, both profiles): clustering on the fly with `percent.mt` and `nCount_RNA` regressed (`--cluster-params`; the mouse objects by the pattern, the others by a list), and the re-clustering with `percent.mt` and a `--metadata` column (`--recluster-params`, `--recluster-metadata`): in process against the commands run one after the other; DoubletFinder's own files against M15's run; the manifests. + +### M15b results + +Every case's four comparisons (scrust's run in each profile against R's run in each) are in [clustering_m15b.tsv](clustering_m15b.tsv), one row each: the grading, the floor, the checks by status, the values compared and differing, and both runs' CPU models (scrust's runs label `m15b-25fe846`, validated by `390342d`'s binary, label `m15b-390342d`). + +#### Against R's run of the same profile (the main criterion) + +**Exact on all 134 cases in both profiles:** scrust's production runs against R's production runs (OpenBLAS's SapphireRapids kernel) and scrust's portable runs against R's portable runs (Haswell), every check identical, in exact mode. + +| profile | cases (T · P · X) | pass | checks identical | differing or missing | reported (purity's flagged pairs) | values compared | values differing | +|---|---|---|---|---|---|---|---| +| production | 134 (108 · 20 · 6) | **134** | 6,183 | 0 | 44 | 889,756,126 | 0 | +| portable | 134 (108 · 20 · 6) | **134** | 6,187 | 0 | 40 | 889,756,130 | 0 | + +- **What is compared:** the labels and levels (`seurat_clusters`, `SCT_snn_res.0.8`, the identities) and FindClusters' result; both graphs (`SCT_nn`, `SCT_snn`, 30,395,764 stored entries of `SCT_snn` over the 134 cases); the PCA (embeddings, loadings, standard deviations, total variance); `scale.data` value by value in the 130 cases whose R runs kept it (804,975,008 values), its digest in the other four; the silhouette widths and the purities; the counts' columns; `percent.mt` as text in the 102 cases that write it; a regressed `--metadata` column, R's double against the candidate's text parsed as R parses it; the regression's covariates, columns, rank and pivot; R's digests of `.Random.seed` after SCTransform and RunPCA, of the corrected counts and of `scale.data`; the manifest. +- **Reported, not failed:** the purity certificate's flagged pairs, the median pair of each odd-sized object (M12's decision), 40 to 44 per profile. +- **The rank-deficient path:** the 31 `pm` cases whose pattern finds nothing (tier T, the three other tier-P objects and the bearded dragon) regress an all-zero column, rank 1, pivot `1,2`: scrust's runs, given that column through `--mt-genes` with features without counts, are R's bit for bit, and in each, scrust refused the pattern itself, naming `--mt-genes` (`refusal.txt`). +- **The CPU type:** tier P's and the other objects' 26 portable pairs ran on different CPU types (scrust on Xeon 8268 nodes, R on 8480CL), and are exact too, the regressed `scale.data` included. + +#### Across kernels + +**Within `[clustering.floor.kernel_regressed]` on all 134 cases, in both directions:** scrust's portable runs against R's production runs, and scrust's production runs against R's portable runs, in tolerance mode, the BLAS-free checks identical and the BLAS-dependent ones within the regressed floor, none beyond it. + +| scrust against R | cases | pass | checks identical | within the floor | differing | values compared | values differing | +|---|---|---|---|---|---|---|---| +| portable against production | 134 | **134** | 5,238 | 815 | 0 | 889,755,996 | 482,340,726 | +| production against portable | 134 | **134** | 5,234 | 815 | 0 | 889,755,992 | 482,340,726 | + +The checks within the floor, per direction: `scale.data` (130), the embeddings' dims 1:30 and 31:50, the loadings and the standard deviations (134 each), the silhouette widths (130), the purities (18) and the total variance (1). Since scrust's runs are R's of the same profile bit for bit, these are R's own differences across kernels, the ones the floor was measured from. The labels, the levels, both graphs, `percent.mt`, the counts' columns and the regression's rank and pivot are identical across kernels in every case. + +#### The R-vs-R measurement with the regression + +With `vars.to.regress`, R's own runs differ across kernels well beyond `[clustering.floor.kernel]`, which M8 and M11 measured without the regression. The regression's QR calls OpenBLAS's level-1 routines for every row, so `scale.data` differs in 27% to 72% of its entries between R's production and portable runs of the same case. Without the regression the figure is at most 0.72% (`S2d_scale_data`). The PCA and the scores after it move with it, and the labels do not: they are identical in every case. Even the all-zero `percent.mt` of the `pm` cases on tier T, which leaves the intercept alone (rank 1), makes 27% to 33% of `scale.data` differ: the intercept's own reflection and every row's products go through the same routines. + +| scale.data's entries differing across kernels | `pm` | `ids` | `ids_ncount` | `meta` | +|---|---|---|---|---| +| tier T (27 objects) | 27.0–33.4% | 42.2–65.2% | 50.7–71.5% | 44.9–58.2% | +| tier P (4 objects at level standard) | 44.4–61.1% | 44.4–61.1% | 58.9–65.7% | 49.7–54.2% | +| the zebrafish and the bearded dragon | 33.1–65.8% | 53.8–60.5% | 62.0–69.5% | – | + +The decision (2026-11-19): a floor of its own, `[clustering.floor.kernel_regressed]`, measured R against R as `[clustering.floor.kernel]` was, used only when both runs record the same non-empty `vars.to.regress`; `[clustering.floor.kernel]` and every unregressed grading stay as they are, and exactness against R's run of the same profile stays the main criterion. + +**How it was measured** ([`m15b_floor.py`](../../validation/python/m15b_floor.py); `data/clustering/m15b/floor/r_vs_r.tsv` and `summary.md`): + +- **The runs:** R's direct runs of all 134 cases in the production profile (OpenBLAS's SapphireRapids kernel, Xeon 8480CL) and in the portable one (Haswell): tier T's portable runs on Xeon 8268 nodes, the others' on 8480CL. Under one kernel the CPU type changes nothing: M8 found every file identical across the two CPU types without the regression, and this milestone found it with the regression too ([below](#against-rs-run-of-the-same-profile-the-main-criterion)). +- **The statistics** are the grader's: `scio::grade::stats`, ported line for line (bitwise differences; a column's sign flipped when its negation is closer in L1; max abs; max scaled, over the reference's largest absolute value; rows with a difference). On a tier-T case the port gives the validator's own figures to every printed digit. +- **The arrays** are those `scrust validate cluster` grades against the floor in these runs: `scale.data` value by value (rows matched by name), the embeddings' dims 1:30 and 31:50, the loadings, the standard deviations, the total variance, the silhouette widths and the purities. Each case is measured in both directions, either run as the reference, as a validation run may be graded against either. +- **The bounds:** each the maximum over the 134 cases, rounded up to two significant digits; `cells_differing` the total over the cases, so it bounds one case too, as in `[clustering.floor.kernel]`. +- **Identical across kernels in every case**, and so not listed (exact): the labels and levels, both graphs, the variable features, the corrected counts, `percent.mt` (102 cases write it) and the counts' columns, the regression's rank and pivot. + +**The two floors side by side** (the bounds in `validation/tolerances.toml`; T, P and X are the maxima on tier T, tier P and the two other objects): + +| array | statistic | `[clustering.floor.kernel]` (M8, M11; without the regression) | `[clustering.floor.kernel_regressed]` (M15b) | measured maximum with the regression (T · P · X) | the case that sets it | +|---|---|---|---|---|---| +| scale.data | max abs | 4.3e-14 | 5.6e-13 | 9.596e-15 · 5.578e-13 · 4.547e-13 | soupx_emptydrops_4500871lane `ids_ncount` | +| | max fraction differing | 0.0072 | 0.72 | 0.7145 · 0.6572 · 0.6953 | posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test `ids_ncount` | +| embeddings, dims 1:30 | max abs | 1.6e-10 | 6.2e-10 | 3.793e-11 · 6.181e-10 · 2.229e-10 | soupx_emptydrops_sscovelli `pm` | +| | max scaled | 2.4e-12 | 2.6e-12 | 2.542e-12 · 2.323e-12 · 8.556e-13 | decontx_raw_tenx_test `ids` | +| embeddings, dims 31:50 | max abs | 4.3e-6 | 5.5e-6 | 5.462e-6 · 5.128e-10 · 1.038e-10 | posthocfilt_threshold_scdblfinder_cellbender_fromraw_test `pm` | +| loadings | max abs | 1.2e-7 | 1.7e-7 | 1.666e-7 · 2.331e-12 · 1.14e-12 | posthocfilt_threshold_scdblfinder_cellbender_fromraw_test `pm` | +| | max scaled | 4.5e-7 | 6.0e-7 | 5.947e-7 · 4.424e-12 · 2.692e-12 | the same | +| standard deviations | max abs | 1.9e-13 | 2.7e-13 | 2.618e-13 · 1.013e-13 · 3.464e-14 | the same | +| | max scaled | 3.6e-14 | 5.0e-14 | 4.959e-14 · 5.493e-15 · 1.52e-15 | the same | +| total variance | max abs, max scaled | identical (not listed) | 1.2e-13, 2.2e-16 | 1.137e-13 · 0 · 0 (one case) | doubletfinder_soupx_tenx_test `meta` | +| silhouette widths | max abs | 3.3e-13 | 2.0e-12 | 6.409e-14 · 1.945e-12 · 6.581e-14 | soupx_emptydrops_sscovelli `pm` | +| purities | cells differing | 19 (10 objects) | 34 (18 cases, at most 2 in one) | 30 · 4 · 0 cells | the total over the cases | +| | max abs | 0.019 | 0.026 | 0.0258 · 0.005554 · 0 | doubletfinder_cellbender_fromraw_test `ids` | + +The bounds come from different tiers: the absolute bounds of `scale.data`, the first 30 embeddings and the silhouette widths from tier P's large objects, the relative ones and the trailing components from tier T's smallest objects, where the PCA's last components are least determined, as in `[clustering.floor.kernel]`. A cargo test (`crates/cluster/tests/m15b_floor.rs`) grades the measured maxima against both floors as built: within the regressed floor, beyond the unregressed one, and past each bound a difference. + +#### percent.mt against the saved objects + +Without the regression, scrust's `percent.mt` by the workflow's pattern against the saved objects' column, as `%.17g` text, so bit for bit ([`m15b_percent_mt.py`](../../validation/python/m15b_percent_mt.py), label `m15b-25fe846`; `data/clustering/m15b/saved_rust/m15b-25fe846/summary.tsv`): + +| saved objects | objects | cells | with mitochondrial features (by the pattern) | identical | +|---|---|---|---|---| +| M8's clustering objects (T and P) | 34 | 277,413 | 4 (13 features each; 53,368 cells; up to 94.4%) | **34 of 34** | +| M7's DoubletFinder objects (the singlets' re-clustering) | 150 | 2,217,328 | 30 (six samples, five inputs each: 13 features, or 2 for the zebrafish; 296,410 cells) | 120 of 150: the 120 without such features (every value 0); the 30 with them differ, as the workflow's script made them | + +**The 30 differences are the SCT assay's.** `doubletfinder.R` (and `scdblfinder.R`) call `PercentageFeatureSet(seurat_singlets, pattern = "(?i)^mt-")` without an assay on the singlets of an input whose default assay is SCT, so their `percent.mt` is the SCT assay's corrected counts over `nCount_SCT`, not the RNA counts over `nCount_RNA` as in the scripts that build their objects (PLAN C1). The call does come before the script's own `SCTransform()` (`doubletfinder.R` lines 62 and 63, `scdblfinder.R` 95 and 96), but on an input that is already transformed. The scripts that build the objects compute `percent.mt` on RNA and then call `SCTransform()` (`cellbender2seurat.R` lines 32 and 33, and likewise `soupx.R`, `decontx.R`, `emptydrops.R` and `tenx2seuratrds.R`), which leaves SCT the default assay of the object they save. The doublet scripts read that object and set no assay, and `subset()` carries its SCT assay and `nCount_SCT` into the singlets. [`percent_mt_sct.R`](../../validation/R/percent_mt_sct.R) checked it on every saved DoubletFinder input, in batch jobs that read the `.rds` files: + +| check (on the saved input object, at the saved object's singlets) | objects | result | +|---|---|---| +| the default assay | 150 | SCT in all 150 | +| `PercentageFeatureSet(assay = "SCT")` against the saved column | 150 | **identical in all 150**, the 30 included (2,217,328 cells) | +| `PercentageFeatureSet(assay = "RNA")` against the saved column | 150 | identical in the 120 without mitochondrial features; differs in all 30 with them (277,450 of 296,410 cells) | +| `PercentageFeatureSet(assay = "RNA")` against scrust's column (the 30 with mitochondrial features; job 62088185, `data/clustering/m15b/percent_mt_rna/`) | 30 | **identical in all 30** (296,410 cells): scrust's column is R's RNA-based one; the SCT-based one differs from it in the same 277,450 cells | + +The 30, object by object (`data/clustering/m15b/percent_mt_rna/.json`; six samples, each through the five DoubletFinder inputs; 13 features each, 2 for the zebrafish's, whose protein genes the pattern misses): + +| object (the saved DoubletFinder object's input) | singlets | features | cells whose saved value is not the RNA counts' share | SCT recomputation = saved | RNA recomputation = scrust's | +|---|---|---|---|---|---| +| cellbender_fromraw_10xmousebrain | 10,485 | 13 | 10,483 | yes | yes | +| cellbender_fromraw_4500871lane | 9,887 | 13 | 9,887 | yes | yes | +| cellbender_fromraw_563792olfmobaob | 9,490 | 13 | 9,488 | yes | yes | +| cellbender_fromraw_SRR18256506 | 5,311 | 13 | 5,008 | yes | yes | +| cellbender_fromraw_SRR18256555 | 9,140 | 13 | 9,036 | yes | yes | +| cellbender_fromraw_drerio | 9,734 | 2 | 9,378 | yes | yes | +| decontx_raw_emptydrops_10xmousebrain | 10,561 | 13 | 10,560 | yes | yes | +| decontx_raw_emptydrops_4500871lane | 23,192 | 13 | 8,521 | yes | yes | +| decontx_raw_emptydrops_563792olfmobaob | 11,055 | 13 | 11,055 | yes | yes | +| decontx_raw_emptydrops_SRR18256506 | 3,467 | 13 | 3,403 | yes | yes | +| decontx_raw_emptydrops_SRR18256555 | 3,348 | 13 | 3,343 | yes | yes | +| decontx_raw_emptydrops_drerio | 28,030 | 2 | 26,057 | yes | yes | +| decontx_raw_tenx_10xmousebrain | 10,159 | 13 | 10,159 | yes | yes | +| decontx_raw_tenx_4500871lane | 9,003 | 13 | 9,003 | yes | yes | +| decontx_raw_tenx_563792olfmobaob | 9,336 | 13 | 9,335 | yes | yes | +| decontx_raw_tenx_SRR18256506 | 3,078 | 13 | 3,003 | yes | yes | +| decontx_raw_tenx_SRR18256555 | 2,686 | 13 | 2,686 | yes | yes | +| decontx_raw_tenx_drerio | 7,158 | 2 | 6,632 | yes | yes | +| soupx_emptydrops_10xmousebrain | 10,565 | 13 | 10,564 | yes | yes | +| soupx_emptydrops_4500871lane | 23,239 | 13 | 22,788 | yes | yes | +| soupx_emptydrops_563792olfmobaob | 11,056 | 13 | 11,056 | yes | yes | +| soupx_emptydrops_SRR18256506 | 3,486 | 13 | 3,298 | yes | yes | +| soupx_emptydrops_SRR18256555 | 3,339 | 13 | 3,326 | yes | yes | +| soupx_emptydrops_drerio | 28,141 | 2 | 28,140 | yes | yes | +| soupx_tenx_10xmousebrain | 10,185 | 13 | 10,184 | yes | yes | +| soupx_tenx_4500871lane | 9,004 | 13 | 9,004 | yes | yes | +| soupx_tenx_563792olfmobaob | 9,340 | 13 | 9,337 | yes | yes | +| soupx_tenx_SRR18256506 | 3,083 | 13 | 2,877 | yes | yes | +| soupx_tenx_SRR18256555 | 2,688 | 13 | 2,675 | yes | yes | +| soupx_tenx_drerio | 7,164 | 2 | 7,164 | yes | yes | +| **30 objects** | **296,410** | | **277,450** | **30 of 30** | **30 of 30** | + +scrust keeps the shared rule, the RNA counts over `nCount_RNA` (the coordinator confirmed it, 2026-11-19): a regressed `percent.mt` is always the RNA-based value, in scrust and in the workflow's branch. **The user then decided (2026-11-19) that the workflow computes `percent.mt` on the RNA assay everywhere, with or without the regression**, so its DoubletFinder, scDblFinder and threshold-filter outputs will hold the RNA counts' share, as scrust's do; scrust needs no change. The saved objects, made before that, keep the SCT assay's column: the 30 differences above. In the workflow as it ran, `posthocfilter_threshold.R` carries the DoubletFinder objects' column on, `downsample_clusters.R` carries its input's column into its regression, and `posthocfilter_mad.R` recomputes it on RNA. + +#### Without the options + +The M15b binary's runs of M15's T and P check ([`m15_recluster.sbatch`](../../validation/slurm/m15_recluster.sbatch), label `m15b-25fe846`, both profiles) against M15's final label's (`m15-a5de5e3`), route by route ([`m15b_unchanged.sbatch`](../../validation/slurm/m15b_unchanged.sbatch), job 62087448): **120 of 120 routes identical** (ten objects, two profiles, six routes: DoubletFinder given the labels; the re-clustering in process with and without the export; the two-command route with and without it; clustering on the fly with both scores; `scrust cluster --counts`), every file byte for byte and every `summary.json` as JSON without the timings, the command line and what records the node. The comparison sets aside one more thing (`compare_runs.py --nested-summaries`): the size and digest that a parent's manifest records for a nested output's `summary.json`, a file that holds that run's timings and so differs between any two runs. The nested `summary.json` itself is compared as JSON like every summary. A first comparison without that option (job 62086331, kept as `data/clustering/m15b/unchanged/m15b-25fe846.without-nested-flag/`) reported 60 routes differing, in exactly those two members of 53 manifests and nothing else. + +#### scrust doubletfinder with the options + +[`m15b_recluster.sbatch`](../../validation/slurm/m15b_recluster.sbatch), label `m15b-25fe846` (array jobs 62087206 in the production profile, 62087207 in the portable one): **every check holds on all 20** (ten objects, two profiles). + +| check | files compared per run | result | +|---|---|---| +| `a_files`: `scrust doubletfinder --recluster` against `scrust doubletfinder`, then `scrust cluster --counts /singlets --params re.toml --metadata metadata.tsv` | 24 | identical, 20 of 20 | +| `a_recluster`: `singlets_clusters/`, every file | 17 | identical, 20 of 20 | +| `hook_alone`: clustering on the fly's `clusters/` against `scrust cluster --counts --params hook.toml --stats silhouette,purity` (its `pca/` and `neighbors/` aside) | 17 | identical, 20 of 20 | +| `df_unchanged`: DoubletFinder's own files against M15's in-process run | 6, and `result` without `result.recluster` | identical, 20 of 20 | +| `scrust validate manifest` on the four outputs | | 20 of 20 | + +The regressions they made: clustering on the fly regressed `percent.mt` and `nCount_RNA`, by the workflow's pattern on the three mouse objects (13 features) and by a list elsewhere (tier T's stand-in, 7 features; three features without counts on soupx_emptydrops_sscovelli and cellbender_fromraw_ghirsutum2, whose all-zero `percent.mt` the QR moves to the edge: rank 2 of 3); the re-clustering regressed `percent.mt` by the list and a `--metadata` column. + +#### The loaders + +`percent.mt` loads as a double, exactly as written (`load_seurat()`, `load_sce()`, `add_scrust()` and `load_anndata()`), from `scrust cluster --export` and from `scrust sctransform`'s `cell_metadata.tsv`. The Seurat loader puts it after `nFeature_RNA`, before the SCT assay's columns, where the workflow's objects hold it, since their scripts call `PercentageFeatureSet()` before SCTransform. The loaders' tests ([`m15b_tests.sbatch`](../../validation/slurm/m15b_tests.sbatch), job 62086880): R 87 (82 in M15), Python 14 (13), all passing. The first run (job 62086529) failed that column-order test: the loader had added `percent.mt` after the SCT assay's columns, and now adds it with the RNA assay. + +### M15b benchmark + +On the seven tier-P clustering objects, by `docs/benchmarks.md`'s method: three repeats, Xeon 8480CL nodes, cold reads, the production profile, 1 and 32 threads. R ran the workflow's scripts as they were before its commit 8d34de1, when they still regressed `percent.mt` (21 runs, each reproducing the clusters and cluster ids of M15b's R reference run). Rust ran `scrust cluster --counts --preset workflow --vars-to-regress percent.mt`, without and with `--export`, and the same binary without the regression (`b`). Every Rust run's files equal M15b's validation run of the case (126 runs, all the same). The full tables are in [docs/benchmarks.md](../benchmarks.md#the-chain-with-sctransforms-varstoregress-m15b). CPU seconds / peak GiB at one thread: + +| object | input cells | R with the regression | R ÷ without: CPU, peak | Rust with the regression | Rust ÷ without: CPU, peak | Rust with `--export` | R ÷ Rust: CPU · peak (with `--export`) | +|---|---|---|---|---|---|---|---| +| soupx_tenx_SRR18256555 | 3,108 | 54.5 / 2.98 | 0.891, 0.977 | 11.2 / 0.154 | 1.040, 1.041 | 14.6 / 0.155 | 4.9× · 19× (3.7× · 19×) | +| soupx_tenx_10xmousebrain | 11,831 | 251 / 12.7 | 0.982, 1.049 | 37.7 / 1.45 | 1.059, 1.006 | 78.0 / 1.45 | 6.7× · 8.8× (3.2× · 8.8×) | +| filtered_seurat_tenx_10xmousebrain | 11,831 | 206 / 13.2 | 1.036, 1.054 | 38.2 / 1.45 | 1.022, 1.006 | 78.6 / 1.45 | 5.4× · 9.1× (2.6× · 9.1×) | +| soupx_emptydrops_4500871lane | 26,598 | 302 / 25.3 | 1.045, 1.057 | 80.1 / 1.49 | 0.992, 1.006 | 101 / 1.49 | 3.8× · 17× (3.0× · 17×) | +| soupx_emptydrops_sscovelli | 79,409 | 813 / 67.7 | 1.153, 1.087 | 301 / 3.15 | 1.120, 1.001 | 353 / 3.34 | 2.7× · 21× (2.3× · 20×) | +| filtered_seurat_emptydrops_sscovelli | 79,409 | 842 / 62.5 | 1.085, 1.068 | 268 / 3.15 | 0.994, 1.001 | 328 / 3.35 | 3.1× · 20× (2.6× · 19×) | +| cellbender_fromraw_ghirsutum2 | 59,323 | 835 / 118.1 | 1.056, 1.122 | 310 / 2.66 | 1.070, 1.002 | 398 / 3.06 | 2.7× · 44× (2.1× · 39×) | + +- **Against R with the regression:** 2.7–6.7× less CPU time at one thread (2.1–3.7× with `--export`), 8.8–44× less memory, and 14–20× sooner at 32 threads (12–17× with `--export`). +- **The regression costs Rust nothing measurable:** run on the same node, the regressed chain took 0.98–1.01× the CPU time of the chain without it (seven pairs of repeats). The medians, 0.99–1.12×, mix nodes: soupx_emptydrops_sscovelli's 1.12 comes from two repeats on a slower node (301 s, against 263 s for its third repeat and 268 s without the regression on that node). The peak is the same (1.000–1.006×; 1.04× on the smallest object, 6 MB). +- **R's peak rises with it,** by up to 12% (cellbender_fromraw_ghirsutum2: 118 against 105 GiB). R's CPU time moves by −11% to +15%, within its repeats' spread; its runs without the regression are the first benchmark's. + +### M15b tests + +`cargo test --workspace` passes in debug and in release, 316 tests in 47 suites each (294 in 43 at M15), none failing or ignored, no compiler warnings (job 62091694, commit `aed8f74`, under env.sh's Haswell kernel on a Xeon 8268 node, [`m15b_cargo_tests.sbatch`](../../validation/slurm/m15b_cargo_tests.sbatch); also job 62091142, the same code before `tolerances.toml`'s K14 entry was committed). Twenty-two are new: + +- `rcompat` (`linpack`): the residuals of an exact fit and of noise; an all-zero column pivoted out (rank 1); `Cdqrls`' refusals (a non-finite value, no rows); +- `scio` (`features`): `make.unique()` as R's `do_makeunique`; Seurat's names and the pattern as TRE matches it; id lists (trimming, comments, repeats); `PercentageFeatureSet()`'s arithmetic; +- `sctransform` (`regress`, `tests/m15b_regress.rs`): `lm()`'s QR (`qr`, `qraux`, rank, pivot) and `qr.resid()` with `RegressOutMatrix()`'s rows bit for bit against R's 14 models, the five rank-deficient ones included (kernel-gated: the fixtures' kernel); +- `cluster` (`covariates`, `chain_params`, `tests/m15b_covariates.rs`, `tests/m15b_floor.rs`): the covariates' names and rules; the options and TOML keys; `make.unique()` and `PercentageFeatureSet()` against R's fixtures, on integer and real counts; when the regressed floor applies, and that it holds R's measured differences across kernels and no more; +- `scrust` (`tests/m15b.rs`): the cases of two tier-T objects against R's runs (the labels and levels, the scores, `percent.mt`, the regressed column's bits, `scale.data`'s digest, the regression's rank and pivot; kernel-gated); the staged routes write what `scrust cluster --counts` writes; the in-memory rule (the entry point given the covariates in memory writes the command's files); `scrust doubletfinder` with the options in process against the two commands, its own SCTransform unregressed; the defaults and the refusals. + +The loaders' tests ([`m15b_tests.sbatch`](../../validation/slurm/m15b_tests.sbatch), job 62091155, the binary of `390342d`): R 87 (82 in M15), Python 14 (13), all passing. The new ones load `percent.mt` from an export (regressed with `nCount_RNA`, by a list of ids) and from `scrust sctransform`'s output, as a double column exactly as written, in the Seurat object (after `nFeature_RNA`), the SingleCellExperiment, `add_scrust()` and AnnData. + +### M15b findings + +- **The saved DoubletFinder objects' `percent.mt` is the SCT assay's.** `doubletfinder.R` and `scdblfinder.R` call `PercentageFeatureSet()` on the singlets of an object whose default assay is SCT, so their column is the corrected counts' share, over `nCount_SCT`. The scripts that build their objects compute it from the RNA counts. R's recomputation on the SCT assay reproduces all 150 saved columns, and its RNA-based value equals scrust's on the 30 that have mitochondrial features (above). A `percent.mt` regressed downstream of those objects (`downsample_clusters.R` regresses its input's column) is therefore the SCT assay's unless it is recomputed. The shared rule makes a regressed `percent.mt` always the RNA counts' share, in scrust and in the workflow's branch, and the user decided (2026-11-19) that the workflow computes it on the RNA assay everywhere, with or without the regression; the saved objects keep the SCT assay's column. +- **The regression makes most of R's own `scale.data` kernel-dependent.** LINPACK's QR goes through OpenBLAS's level-1 routines for the QR itself and for every row's residuals, so 27% to 72% of `scale.data` differs between R's two profiles, against at most 0.72% without the regression. The labels, levels and graphs stay identical in all 134 cases. That is why the regression has a floor of its own. +- **An all-zero `percent.mt` is regressed without a word in R.** Where the workflow's pattern finds no feature (in most of the panel's species), R regresses a column of zeros: `dqrdc2` moves it to the edge and the regression is on the intercept alone (rank 1, or rank 2 with `nCount_RNA`). It still goes through BLAS: those runs' `scale.data` differs across kernels in 27% to 33% of its entries. scrust refuses that by the shared rule, naming `--mt-genes`; given R's column through features without counts, it reproduces R's results bit for bit. +- **Under one kernel the CPU type changes nothing, with the regression too.** scrust's portable runs (Xeon 8268) equal R's portable runs on tier P and the two other objects (Xeon 8480CL) bit for bit, the regressed `scale.data` included, as M8 found for the chain without it. + +### M15b corrections to the plan + +Corrected in [docs/PLAN.md](../PLAN.md) on this branch: + +- **A3:** the clustering chain's row: its inputs for `vars.to.regress` (a list of mitochondrial ids, a per-cell table) and `percent.mt` among its outputs. +- **A5:** R's Fortran routines that call BLAS (LINPACK's QR) go through the same OpenBLAS by FFI, `rcompat::linpack`. +- **A5b:** the one exception to kernel-gated grading's floor: `[clustering.floor.kernel_regressed]` when both runs record the same non-empty `vars.to.regress`. +- **C1:** `percent.mt` and `vars.to.regress` in the workflow's scripts, researched: the pattern, the commit that removed the regression, which species it finds, and the DoubletFinder and scDblFinder objects' SCT-based column. +- **C3:** `vars.to.regress` is no longer refused (the refused list); the commands' new options; `percent.mt` in `metadata.tsv`; C3g's loaders carry `percent.mt`; C3h's options for `scrust doubletfinder`'s two clusterings; a new section, C3j, with the code path as researched, the port, the shared options and rules, the refusals, the records and the grading decision. +- **C5:** a new row, K14, and the note on why it has a floor of its own. +- **C6:** a new row, M15b; the order (M15b after M15 and M14, before M14b); M15b in Step 2 and in its completion; M14b's row covers M15b's options. + +### M15b deviations and notes + +- **The floor, decided** (2026-11-19). R's own regressed runs differ across kernels beyond `[clustering.floor.kernel]`, so the portable profile's regressed runs could not be graded against it. The coordinator decided on a separate floor, measured R against R on T and P, used only when both runs record a non-empty `vars.to.regress`, with `[clustering.floor.kernel]` unchanged and exactness first. Measuring it on P took R's portable runs of tier P's 20 cases and the two other objects' 6, which the first round of R runs (both profiles on T, the production profile elsewhere) did not have: 26 more runs of the approved cases. +- **Two labels.** The validation runs are label `m15b-25fe846`. Their first validation graded one check wrongly: where R's pattern finds no feature and scrust is given features without counts, `percent.mt`'s features were compared by name (R's none, scrust's three) and failed 31 cases, although the columns, which are what matter, were identical. The validator now compares the features only when both runs define them the same way, and the column always. That change and the regressed floor (commit `390342d`) changed no output, so the runs were validated again by `390342d`'s binary, not run again (`m15b_revalidate.sbatch`, label `m15b-390342d`). The runs' and the validator's binaries record their versions in each report. +- **The defaults' comparison needed one more rule** (`compare_runs.py --nested-summaries`, [above](#without-the-options)); its first output is kept. +- **Every `scrust validate cluster` report names its floor** (a row of stage `environment`, and `floor` in the JSON), `[clustering.floor.kernel]` unless both runs regressed the same covariates. The grading of every unregressed comparison is unchanged. +- **The Seurat loader's column order.** The loaders' first test run failed one new check: the loader had added `percent.mt` after the SCT assay's columns. It now adds it with the RNA assay, where the workflow's objects hold it ([The loaders](#the-loaders)). +- **The benchmark's R side** runs the workflow's scripts as they were before its commit 8d34de1, which differ from the current ones in `vars.to.regress = "percent.mt"` and a comment only. Where the pattern finds nothing, those scripts regress R's all-zero column, and scrust's side gets the same column through `--mt-genes` ([M15b benchmark](#m15b-benchmark)). +- **User documentation.** M14b has not landed on main, so it will cover M15b's options with M15's (`--vars-to-regress`, `--mt-genes`, `--percent-mt`, the `[sctransform]` keys of `scrust doubletfinder`'s parameter files, `--cluster-metadata`, `--recluster-metadata`, `percent.mt`); the commands' `--help` and the README describe them. + +### Reproducing M15b + +From the repository's top directory, after `source env.sh` and `cargo build --release -p scrust`, with M8's exports of the 34 clustering objects, M7's DoubletFinder inputs and outputs, and M15's T and P runs (label `m15-a5de5e3`). Copy the binary so that later builds do not change it under the jobs: + +```bash +cp target/release/scrust data/benchmarks/bin/scrust-$(git rev-parse --short HEAD) +``` + +The code path and the vectors (the committed fixtures, in the portable profile), then the fixtures of the end-to-end tests from two cases' R runs: + +```bash +sbatch validation/slurm/m15b_vectors.sbatch +``` + +```bash +bash validation/slurm/fixtures_m15b.sh +``` + +The cases and their inputs (no R, no `.rds`), then R's runs of every case in both profiles (the four largest objects need more memory): + +```bash +PYTHONNOUSERSITE=1 .envs/loaders-py/bin/python -I validation/python/m15b_cases.py +``` + +```bash +sbatch --array=1-124,129-134 --mem=36G validation/slurm/m15b_references.sbatch production +``` + +```bash +sbatch --array=125-128 --mem=160G validation/slurm/m15b_references.sbatch production +``` + +```bash +sbatch --array=1-124,129-134 --mem=36G validation/slurm/m15b_references.sbatch portable +``` + +```bash +sbatch --array=125-128 --mem=160G validation/slurm/m15b_references.sbatch portable +``` + +The R-vs-R measurement behind `[clustering.floor.kernel_regressed]`: + +```bash +PYTHONNOUSERSITE=1 .envs/loaders-py/bin/python -I validation/python/m15b_floor.py --tsv data/clustering/m15b/floor/r_vs_r.tsv --summary data/clustering/m15b/floor/summary.md +``` + +Scrust's runs of every case in both profiles, each validated against both R runs, then validated again by a later binary's validator: + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-134 validation/slurm/m15b_cluster.sbatch m15b- production +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-134 --partition=shared validation/slurm/m15b_cluster.sbatch m15b- portable +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-134%20 validation/slurm/m15b_revalidate.sbatch m15b- m15b- +``` + +`percent.mt` against the saved objects (the exports read the `.rds` files in batch jobs), and how the saved DoubletFinder objects made theirs: + +```bash +sbatch --array=1-184%40 validation/slurm/m15b_saved.sbatch +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-184%40 validation/slurm/m15b_saved_rust.sbatch m15b- +``` + +```bash +PYTHONNOUSERSITE=1 .envs/loaders-py/bin/python -I validation/python/m15b_percent_mt.py report data/clustering/m15b/saved_rust/m15b- --tsv data/clustering/m15b/saved_rust/m15b-/summary.tsv +``` + +```bash +sbatch --array=1-150%40 validation/slurm/m15b_percent_mt_sct.sbatch +``` + +```bash +sbatch --array=1-20,46-50,126-130 validation/slurm/m15b_percent_mt_sct.sbatch percent_mt_rna m15b- +``` + +The defaults (M15's T and P check with the M15b binary, then route by route against M15's runs), and `scrust doubletfinder` with the options: + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-10 validation/slurm/m15_recluster.sbatch m15b- production +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-10 --partition=shared validation/slurm/m15_recluster.sbatch m15b- portable +``` + +```bash +sbatch validation/slurm/m15b_unchanged.sbatch m15b- +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-10 validation/slurm/m15b_recluster.sbatch m15b- production +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch --array=1-10 validation/slurm/m15b_recluster.sbatch m15b- portable +``` + +The tests, and the manifest's section: + +```bash +sbatch validation/slurm/m15b_cargo_tests.sbatch +``` + +```bash +SCRUST_BIN=data/benchmarks/bin/scrust- sbatch validation/slurm/m15b_tests.sbatch +``` + +```bash +PYTHONNOUSERSITE=1 .envs/loaders-py/bin/python -I validation/python/m15b_manifest.py --label m15b- --revalidate m15b- --cargo-job --tests-job --bin data/benchmarks/bin/scrust- +``` + +The benchmark: [docs/benchmarks.md](../benchmarks.md), "Updating this page" (tool `cluster_regress`, and `VARIANTS="b1 b32"` for the chain without the regression). diff --git a/docs/validation/clustering_m15b.tsv b/docs/validation/clustering_m15b.tsv new file mode 100644 index 0000000..df1ef8e --- /dev/null +++ b/docs/validation/clustering_m15b.tsv @@ -0,0 +1,537 @@ +object tier case vars_to_regress scrust_profile r_profile grading floor pass identical within_floor differing missing not_applicable reported values_compared values_differing scrust_cpu r_cpu failing +filtered_seurat_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 360471 0 8480+ 8480CL +filtered_seurat_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 360470 133800 8480+ 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 360470 133800 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 360471 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 357998 0 8480+ 8480CL +filtered_seurat_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 357997 191374 8480+ 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 357997 191374 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 357998 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 361825 0 8480+ 8480CL +filtered_seurat_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 361824 202036 8480+ 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 361824 202036 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 361825 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 361738 0 8480+ 8480CL +filtered_seurat_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 361737 187738 8480+ 8268 CPU @ 2.90GHz +filtered_seurat_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 361737 187738 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 361738 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 305550 0 8480+ 8480CL +filtered_seurat_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 305549 123435 8480+ 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 305549 123435 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 305550 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 307038 0 8480CL 8480CL +filtered_seurat_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 307037 153672 8480CL 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 307036 153672 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 307037 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 307082 0 8480CL 8480CL +filtered_seurat_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 307081 185289 8480CL 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 307081 185289 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 307082 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 305798 0 8480CL 8480CL +filtered_seurat_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 305797 154613 8480CL 8268 CPU @ 2.90GHz +filtered_seurat_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 305797 154613 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 305798 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 360111 0 8480CL 8480CL +soupx_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 360110 134345 8480CL 8268 CPU @ 2.90GHz +soupx_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 360110 134345 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 360111 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 354954 0 8480CL 8480CL +soupx_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 354953 163608 8480CL 8268 CPU @ 2.90GHz +soupx_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 354953 163608 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 354954 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 360301 0 8480CL 8480CL +soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 360300 182489 8480CL 8268 CPU @ 2.90GHz +soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 360300 182489 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 360301 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 357663 0 8480CL 8480CL +soupx_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 357662 197153 8480CL 8268 CPU @ 2.90GHz +soupx_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 357662 197153 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 357663 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 304667 0 8480CL 8480CL +soupx_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 304666 123737 8480CL 8268 CPU @ 2.90GHz +soupx_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 304666 123737 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 304667 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 305932 0 8480CL 8480CL +soupx_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 305931 179618 8480CL 8268 CPU @ 2.90GHz +soupx_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 305931 179618 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 305932 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 306196 0 8480CL 8480CL +soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 306195 198604 8480CL 8268 CPU @ 2.90GHz +soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 306194 198604 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 306195 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 304467 0 8480CL 8480CL +soupx_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 304466 155794 8480CL 8268 CPU @ 2.90GHz +soupx_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 304466 155794 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 304467 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 333110 0 8480CL 8480CL +decontx_raw_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 333109 129477 8480CL 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 333109 129477 8268 CPU @ 2.90GHz 8480CL +decontx_raw_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 333110 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 342281 0 8480CL 8480CL +decontx_raw_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 342280 164816 8480CL 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 342280 164816 8268 CPU @ 2.90GHz 8480CL +decontx_raw_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 342281 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 342704 0 8480CL 8480CL +decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 342703 189096 8480CL 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 342703 189096 8268 CPU @ 2.90GHz 8480CL +decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 342704 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 333218 0 8480CL 8480CL +decontx_raw_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 333217 189411 8480CL 8268 CPU @ 2.90GHz +decontx_raw_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 333217 189411 8268 CPU @ 2.90GHz 8480CL +decontx_raw_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 333218 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 291880 0 8480CL 8480CL +decontx_raw_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 291879 116749 8480CL 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 291879 116749 8268 CPU @ 2.90GHz 8480CL +decontx_raw_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 291880 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 295206 0 8480CL 8480CL +decontx_raw_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 295205 152110 8480CL 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 295205 152110 8268 CPU @ 2.90GHz 8480CL +decontx_raw_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 295206 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 295926 0 8480CL 8480CL +decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 295925 184693 8480CL 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 295925 184693 8268 CPU @ 2.90GHz 8480CL +decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 295926 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 291804 0 8480CL 8480CL +decontx_raw_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 291803 171296 8480CL 8268 CPU @ 2.90GHz +decontx_raw_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 291803 171296 8268 CPU @ 2.90GHz 8480CL +decontx_raw_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 291804 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +cellbender_fromraw_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 321818 0 8480CL 8480CL +cellbender_fromraw_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 321817 129306 8480CL 8268 CPU @ 2.90GHz +cellbender_fromraw_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 321817 129306 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 321818 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +cellbender_fromraw_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 323403 0 8480CL 8480CL +cellbender_fromraw_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 323402 187530 8480CL 8268 CPU @ 2.90GHz +cellbender_fromraw_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 323402 187530 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 323403 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 324600 0 8480CL 8480CL +cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 324599 201654 8480CL 8268 CPU @ 2.90GHz +cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 324599 201654 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 324600 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +cellbender_fromraw_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 322050 0 8480CL 8480CL +cellbender_fromraw_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 322049 166112 8480CL 8268 CPU @ 2.90GHz +cellbender_fromraw_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 322049 166112 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 322050 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 327564 0 8480CL 8480CL +doubletfinder_soupx_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 327563 127951 8480CL 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 327563 127951 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 327564 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 327796 0 8480CL 8480CL +doubletfinder_soupx_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 327795 153101 8480CL 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 327795 153101 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 327796 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 332884 0 8480+ 8480CL +doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 332883 166222 8480+ 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 332883 166222 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 332884 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 334084 0 8480+ 8480CL +doubletfinder_soupx_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 334083 159359 8480+ 8268 CPU @ 2.90GHz +doubletfinder_soupx_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 334083 159359 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 334084 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 269887 0 8480+ 8480CL +doubletfinder_soupx_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 269886 112178 8480+ 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 269886 112178 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 269887 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 272480 0 8480CL 8480CL +doubletfinder_soupx_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 272479 161668 8480CL 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 272480 161668 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 272481 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 272177 0 8480CL 8480CL +doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 272176 176719 8480CL 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 272176 176719 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 272177 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 269817 0 8480CL 8480CL +doubletfinder_soupx_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 269816 138192 8480CL 8268 CPU @ 2.90GHz +doubletfinder_soupx_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 269816 138192 8268 CPU @ 2.90GHz 8480CL +doubletfinder_soupx_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 269817 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 303807 0 8480CL 8480CL +doubletfinder_decontx_raw_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 303806 118533 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 303806 118533 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 303807 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 319755 0 8480CL 8480CL +doubletfinder_decontx_raw_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 319754 154699 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 319755 154699 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 319756 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 321190 0 8480CL 8480CL +doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 321189 167642 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 321190 167642 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 321191 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 302569 0 8480CL 8480CL +doubletfinder_decontx_raw_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 37 7 0 0 9 1 302568 152655 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 302569 152655 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 302570 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 261414 0 8480+ 8480CL +doubletfinder_decontx_raw_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 261413 106956 8480+ 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 261413 106956 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 261414 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 264733 0 8480+ 8480CL +doubletfinder_decontx_raw_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 264732 134521 8480+ 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 264731 134521 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 264732 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 265384 0 8480CL 8480CL +doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 265383 150334 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 265383 150334 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 265384 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 261432 0 8480CL 8480CL +doubletfinder_decontx_raw_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 37 7 0 0 9 1 261431 154029 8480CL 8268 CPU @ 2.90GHz +doubletfinder_decontx_raw_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 261432 154029 8268 CPU @ 2.90GHz 8480CL +doubletfinder_decontx_raw_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 261433 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 286275 0 8480CL 8480CL +doubletfinder_cellbender_fromraw_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 37 7 0 0 10 1 286274 115955 8480CL 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 10 0 286275 115955 8268 CPU @ 2.90GHz 8480CL +doubletfinder_cellbender_fromraw_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 286276 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 289141 0 8480CL 8480CL +doubletfinder_cellbender_fromraw_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 289140 166977 8480CL 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 289139 166977 8268 CPU @ 2.90GHz 8480CL +doubletfinder_cellbender_fromraw_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 289140 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 289651 0 8480CL 8480CL +doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 289650 175857 8480CL 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 289649 175857 8268 CPU @ 2.90GHz 8480CL +doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 289650 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 287307 0 8480CL 8480CL +doubletfinder_cellbender_fromraw_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 287306 148093 8480CL 8268 CPU @ 2.90GHz +doubletfinder_cellbender_fromraw_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 287306 148093 8268 CPU @ 2.90GHz 8480CL +doubletfinder_cellbender_fromraw_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 287307 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 346950 0 8480CL 8480CL +scdblfinder_soupx_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 346949 133591 8480CL 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 346949 133591 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 346950 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 346423 0 8480CL 8480CL +scdblfinder_soupx_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 346422 161964 8480CL 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 346422 161964 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 346423 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 352744 0 8480+ 8480CL +scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 352743 180569 8480+ 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 352743 180569 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 352744 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 350549 0 8480+ 8480CL +scdblfinder_soupx_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 350548 182631 8480+ 8268 CPU @ 2.90GHz +scdblfinder_soupx_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 350548 182631 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 350549 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 301277 0 8480+ 8480CL +scdblfinder_soupx_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 301276 117292 8480+ 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 301276 117292 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 301277 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 302962 0 8480CL 8480CL +scdblfinder_soupx_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 302961 175419 8480CL 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 302961 175419 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 302962 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 303176 0 8480CL 8480CL +scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 303175 187549 8480CL 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 303175 187549 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 303176 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 301479 0 8480CL 8480CL +scdblfinder_soupx_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 301478 154999 8480CL 8268 CPU @ 2.90GHz +scdblfinder_soupx_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 301478 154999 8268 CPU @ 2.90GHz 8480CL +scdblfinder_soupx_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 301479 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 329779 0 8480CL 8480CL +scdblfinder_decontx_raw_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 329778 124983 8480CL 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 329778 124983 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 329779 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 338192 0 8480CL 8480CL +scdblfinder_decontx_raw_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 338191 163642 8480CL 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 338191 163642 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 338192 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 337989 0 8480CL 8480CL +scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 337988 195159 8480CL 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 337988 195159 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 337989 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 331227 0 8480CL 8480CL +scdblfinder_decontx_raw_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 331226 164129 8480CL 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 331226 164129 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 331227 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 285528 0 8480+ 8480CL +scdblfinder_decontx_raw_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 285527 116310 8480+ 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 285527 116310 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 285528 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 289190 0 8480+ 8480CL +scdblfinder_decontx_raw_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 289189 147573 8480+ 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 289189 147573 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 289190 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 290112 0 8480+ 8480CL +scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 290111 177213 8480+ 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 290111 177213 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 290112 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 285584 0 8480+ 8480CL +scdblfinder_decontx_raw_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 285583 149391 8480+ 8268 CPU @ 2.90GHz +scdblfinder_decontx_raw_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 285583 149391 8268 CPU @ 2.90GHz 8480CL +scdblfinder_decontx_raw_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 285584 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 321818 0 8480+ 8480CL +scdblfinder_cellbender_fromraw_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 321817 129306 8480+ 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 321817 129306 8268 CPU @ 2.90GHz 8480CL +scdblfinder_cellbender_fromraw_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 321818 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 323403 0 8480CL 8480CL +scdblfinder_cellbender_fromraw_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 323402 187530 8480CL 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 323402 187530 8268 CPU @ 2.90GHz 8480CL +scdblfinder_cellbender_fromraw_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 323403 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 324600 0 8480CL 8480CL +scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 324599 201654 8480CL 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 324599 201654 8268 CPU @ 2.90GHz 8480CL +scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 324600 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 322154 0 8480CL 8480CL +scdblfinder_cellbender_fromraw_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 322153 167974 8480CL 8268 CPU @ 2.90GHz +scdblfinder_cellbender_fromraw_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 322153 167974 8268 CPU @ 2.90GHz 8480CL +scdblfinder_cellbender_fromraw_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 322154 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 172289 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 172288 76000 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 172288 76000 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 172289 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 173121 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 173120 92992 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 173120 92992 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 173121 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 173906 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 173905 104307 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 173905 104307 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 173906 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 171739 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 171738 101452 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 171738 101452 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 171739 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 166900 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 166899 73510 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 166899 73510 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 166900 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 167781 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 167780 92472 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 167780 92472 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 167781 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 168709 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 168708 101135 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 168709 101135 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 168710 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 166712 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 166711 94338 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 166711 94338 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_soupx_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 166712 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 101999 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 101998 54291 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 101998 54291 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 101999 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 103716 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 103715 64436 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 103715 64436 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 103716 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 103728 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 103727 73950 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 103727 73950 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 103728 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 102017 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 102016 64456 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 102016 64456 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 102017 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 115320 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 115319 59049 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 115319 59049 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 115320 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 115876 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 115875 76275 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 115875 76275 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 115876 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 116036 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 116035 81211 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 116035 81211 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 116036 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 115603 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 115602 76281 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 115602 76281 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_decontx_raw_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 115603 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 164576 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 164575 72192 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 164575 72192 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 164576 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 165583 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 165582 107917 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 165582 107917 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 165583 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 165586 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 165585 117523 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 165585 117523 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 165586 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 164281 0 8480CL 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 164280 96564 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 37 7 0 0 9 1 164279 96564 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_doubletfinder_cellbender_fromraw_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 164280 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 185487 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 185486 80364 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 185486 80364 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 185487 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 185916 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 185915 97019 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 185915 97019 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 185916 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 186722 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 186721 107428 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 186721 107428 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 186722 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 185579 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 185578 116097 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 185578 116097 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 185579 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 194019 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 194018 84081 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 194018 84081 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 194019 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 194660 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 194659 122911 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 194659 122911 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 194660 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 195495 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 195494 129066 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 195494 129066 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 195495 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 194168 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 0 194167 113160 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 37 7 0 0 9 1 194166 113160 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_soupx_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 194167 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 109454 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 37 7 0 0 10 1 109453 57422 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 7 0 0 10 0 109454 57422 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 109455 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 111320 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 111319 79287 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 111319 79287 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 111320 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 111342 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 111341 83124 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 5 0 0 10 0 111341 83124 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 111342 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 109334 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 109333 69186 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 109333 69186 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_tenx_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 109334 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 136210 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 136209 65401 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 136209 65401 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 136210 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 137140 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 137139 78429 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 137139 78429 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 137140 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 136826 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 136825 87195 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 136825 87195 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 136826 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 136120 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 136119 79675 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 136119 79675 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_decontx_raw_emptydrops_test T meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 136120 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T pm percent.mt production production exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 198018 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 198017 84640 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 1 198017 84640 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 1 198018 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 198819 0 8480+ 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 198818 126712 8480+ 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 198818 126712 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 198819 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 199187 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 199186 133276 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 199186 133276 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 199187 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 197757 0 8480CL 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 197756 107633 8480CL 8268 CPU @ 2.90GHz +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 197756 107633 8268 CPU @ 2.90GHz 8480CL +posthocfilt_threshold_scdblfinder_cellbender_fromraw_test T meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 197757 0 8268 CPU @ 2.90GHz 8268 CPU @ 2.90GHz +soupx_tenx_SRR18256555 P pm percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938306 0 8480CL 8480CL +soupx_tenx_SRR18256555 P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938305 6006351 8480CL 8480CL +soupx_tenx_SRR18256555 P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938305 6006351 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938306 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938306 0 8480CL 8480CL +soupx_tenx_SRR18256555 P ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938305 6006351 8480CL 8480CL +soupx_tenx_SRR18256555 P ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938305 6006351 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938306 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938565 0 8480CL 8480CL +soupx_tenx_SRR18256555 P ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938564 6434176 8480CL 8480CL +soupx_tenx_SRR18256555 P ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 9938564 6434176 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 9938565 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 9947354 0 8480CL 8480CL +soupx_tenx_SRR18256555 P meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 9947353 4988145 8480CL 8480CL +soupx_tenx_SRR18256555 P meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 9947353 4988145 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_SRR18256555 P meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 9947354 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316735 0 8480CL 8480CL +soupx_tenx_10xmousebrain P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37316734 16523676 8480CL 8480CL +soupx_tenx_10xmousebrain P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37316734 16523676 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316735 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316735 0 8480CL 8480CL +soupx_tenx_10xmousebrain P ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37316734 16523676 8480CL 8480CL +soupx_tenx_10xmousebrain P ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37316734 16523676 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316735 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37317993 0 8480CL 8480CL +soupx_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37317992 21638785 8480CL 8480CL +soupx_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37317992 21638785 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37317993 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P meta score production production exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 37316553 0 8480CL 8480CL +soupx_tenx_10xmousebrain P meta score production portable tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 37316552 18404382 8480CL 8480CL +soupx_tenx_10xmousebrain P meta score portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 9 1 37316552 18404382 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_10xmousebrain P meta score portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 8 1 37316553 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316545 0 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 37316544 19433501 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 37316545 19433501 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 37316546 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P ids percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37316545 0 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 7 0 0 9 1 37316544 19433501 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 7 0 0 9 0 37316545 19433501 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 37316546 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37318264 0 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37318263 22391876 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 1 37318263 22391876 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 1 37318264 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 37317538 0 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 37317537 19141503 8480CL 8480CL +filtered_seurat_tenx_10xmousebrain P meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 37317537 19141503 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_tenx_10xmousebrain P meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 37317538 0 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P pm percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83566977 0 8480+ 8480CL +soupx_emptydrops_4500871lane P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83566976 45550988 8480+ 8480CL +soupx_emptydrops_4500871lane P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83566976 45550988 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83566977 0 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83566977 0 8480+ 8480CL +soupx_emptydrops_4500871lane P ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83566976 45550988 8480+ 8480CL +soupx_emptydrops_4500871lane P ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83566976 45550988 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83566977 0 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83589946 0 8480+ 8480CL +soupx_emptydrops_4500871lane P ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83589945 51975105 8480+ 8480CL +soupx_emptydrops_4500871lane P ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 83589945 51975105 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 83589946 0 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P meta score production production exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 83526690 0 8480+ 8480CL +soupx_emptydrops_4500871lane P meta score production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 83526689 44743317 8480+ 8480CL +soupx_emptydrops_4500871lane P meta score portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 9 0 83526689 44743317 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_4500871lane P meta score portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 8 0 83526690 0 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_sscovelli P pm percent.mt production production exact clustering.floor.kernel_regressed yes 44 0 0 0 9 1 9635222 0 8480+ 8480CL +soupx_emptydrops_sscovelli P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 37 6 0 0 10 1 9635221 4189943 8480+ 8480CL +soupx_emptydrops_sscovelli P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 6 0 0 10 0 9635222 4189943 8268 CPU @ 2.90GHz 8480CL +soupx_emptydrops_sscovelli P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 45 0 0 0 9 0 9635223 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_sscovelli P pm percent.mt production production exact clustering.floor.kernel_regressed yes 44 0 0 0 9 1 9466507 0 8480+ 8480CL +filtered_seurat_emptydrops_sscovelli P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 5 0 0 10 1 9466506 4192509 8480+ 8480CL +filtered_seurat_emptydrops_sscovelli P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 5 0 0 10 1 9466506 4192509 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_sscovelli P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 44 0 0 0 9 1 9466507 0 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_sscovelli P meta score production production exact clustering.floor.kernel_regressed yes 44 0 0 0 8 1 9465942 0 8480+ 8480CL +filtered_seurat_emptydrops_sscovelli P meta score production portable tolerance clustering.floor.kernel_regressed yes 38 5 0 0 9 1 9465941 4190312 8480+ 8480CL +filtered_seurat_emptydrops_sscovelli P meta score portable production tolerance clustering.floor.kernel_regressed yes 38 5 0 0 9 1 9465941 4190312 8268 CPU @ 2.90GHz 8480CL +filtered_seurat_emptydrops_sscovelli P meta score portable portable exact clustering.floor.kernel_regressed yes 44 0 0 0 8 1 9465942 0 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_ghirsutum2 P pm percent.mt production production exact clustering.floor.kernel_regressed yes 44 0 0 0 9 1 6992930 0 8480+ 8480CL +cellbender_fromraw_ghirsutum2 P pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 38 5 0 0 10 1 6992929 3166704 8480+ 8480CL +cellbender_fromraw_ghirsutum2 P pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 38 5 0 0 10 1 6992929 3166704 8268 CPU @ 2.90GHz 8480CL +cellbender_fromraw_ghirsutum2 P pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 44 0 0 0 9 1 6992930 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X pm percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26378775 0 8480+ 8480CL +soupx_tenx_drerio X pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26378774 17006121 8480+ 8480CL +soupx_tenx_drerio X pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26378774 17006121 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26378775 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26413123 0 8480+ 8480CL +soupx_tenx_drerio X ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26413122 15674618 8480+ 8480CL +soupx_tenx_drerio X ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26413122 15674618 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26413123 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26410977 0 8480CL 8480CL +soupx_tenx_drerio X ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26410976 17928052 8480CL 8480CL +soupx_tenx_drerio X ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 26410976 17928052 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_drerio X ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 26410977 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X pm percent.mt production production exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 24954086 0 8480CL 8480CL +soupx_tenx_pvitticeps X pm percent.mt production portable tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 24954085 8364487 8480CL 8480CL +soupx_tenx_pvitticeps X pm percent.mt portable production tolerance clustering.floor.kernel_regressed yes 39 6 0 0 10 0 24954085 8364487 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X pm percent.mt portable portable exact clustering.floor.kernel_regressed yes 46 0 0 0 9 0 24954086 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X ids percent.mt production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 24956204 0 8480CL 8480CL +soupx_tenx_pvitticeps X ids percent.mt production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 24956203 13272043 8480CL 8480CL +soupx_tenx_pvitticeps X ids percent.mt portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 24956203 13272043 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X ids percent.mt portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 24956204 0 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X ids_ncount percent.mt,nCount_RNA production production exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 24949006 0 8480CL 8480CL +soupx_tenx_pvitticeps X ids_ncount percent.mt,nCount_RNA production portable tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 24949005 15217085 8480CL 8480CL +soupx_tenx_pvitticeps X ids_ncount percent.mt,nCount_RNA portable production tolerance clustering.floor.kernel_regressed yes 40 6 0 0 9 0 24949005 15217085 8268 CPU @ 2.90GHz 8480CL +soupx_tenx_pvitticeps X ids_ncount percent.mt,nCount_RNA portable portable exact clustering.floor.kernel_regressed yes 47 0 0 0 8 0 24949006 0 8268 CPU @ 2.90GHz 8480CL diff --git a/loaders/R/scrustio/R/metadata.R b/loaders/R/scrustio/R/metadata.R index 1a09733..2e1e242 100644 --- a/loaders/R/scrustio/R/metadata.R +++ b/loaders/R/scrustio/R/metadata.R @@ -2,8 +2,9 @@ # cell_metadata.tsv (rna_cell_metadata), scrust doubletfinder's cells.tsv (doublet_calls), with # each column's type as Seurat holds it and each factor in its levels' order. -# Columns of metadata.tsv with a known type (docs/output_manifest.md, role cell_metadata). -.META_DOUBLE <- c("nCount_RNA", "nCount_SCT", "silhouette_width", "neighborhood_purity") +# Columns of metadata.tsv with a known type (docs/output_manifest.md, role cell_metadata); +# percent.mt (M15b) when the output computed it. +.META_DOUBLE <- c("nCount_RNA", "percent.mt", "nCount_SCT", "silhouette_width", "neighborhood_purity") .META_INTEGER <- c("nFeature_RNA", "nFeature_SCT") # Factor levels, from the files of role cluster_levels: each holds one column's levels in order, diff --git a/loaders/R/scrustio/R/seurat.R b/loaders/R/scrustio/R/seurat.R index 91399e3..f0c66d8 100644 --- a/loaders/R/scrustio/R/seurat.R +++ b/loaders/R/scrustio/R/seurat.R @@ -64,6 +64,13 @@ load_seurat <- function(dir, check_sha256 = FALSE) { rownames(counts) <- feat$seurat obj <- SeuratObject::CreateSeuratObject(counts = counts) } + md <- .read_metadata(m) + if (!is.null(obj) && !is.null(md) && "percent.mt" %in% colnames(md)) { + # percent.mt (M15b) before the SCT assay's columns, where the workflow's objects hold it (their + # scripts call PercentageFeatureSet() before SCTransform()) + if (!identical(rownames(md), cells)) stop("scrustio: the metadata's cells differ from the object's", call. = FALSE) + obj <- SeuratObject::AddMetaData(obj, metadata = md[, "percent.mt", drop = FALSE]) + } if (.has_role(m, "sct_counts")) { sct <- .sct_assay(m, feat, cells, counts) if (is.null(obj)) { @@ -78,7 +85,7 @@ load_seurat <- function(dir, check_sha256 = FALSE) { "(scrust cluster --export holds both); add its per-cell columns to an object with add_scrust()", call. = FALSE) } - obj <- .add_metadata_seurat(obj, m) + obj <- .add_metadata_seurat(obj, m, md) if (.has_role(m, "pca_embeddings")) obj[["pca"]] <- .pca_reduction(m, feat, cells) for (g in list(c("graph_nn", "SCT_nn"), c("graph_snn", "SCT_snn"))) { if (!.has_role(m, g[1])) next @@ -171,9 +178,9 @@ load_seurat <- function(dir, check_sha256 = FALSE) { # meta.data: the output's per-cell columns (and DoubletFinder's calls), each with Seurat's type, # factors in their levels' order. Columns Seurat computes itself when the assays are added -# (nCount_RNA, nFeature_RNA, nCount_SCT, nFeature_SCT) must equal the output's. -.add_metadata_seurat <- function(obj, m) { - md <- .read_metadata(m) +# (nCount_RNA, nFeature_RNA, nCount_SCT, nFeature_SCT) must equal the output's, as must +# percent.mt when load_seurat() has added it with the RNA assay. `md`: .read_metadata(m). +.add_metadata_seurat <- function(obj, m, md = .read_metadata(m)) { calls <- .read_doublet_calls(m) cells <- colnames(obj) if (!is.null(calls)) { @@ -186,7 +193,7 @@ load_seurat <- function(dir, check_sha256 = FALSE) { if (!identical(rownames(md), cells)) stop("scrustio: the metadata's cells differ from the object's", call. = FALSE) have <- obj[[]] for (col in intersect(colnames(md), colnames(have))) { - if (!col %in% c("nCount_RNA", "nFeature_RNA", "nCount_SCT", "nFeature_SCT")) { + if (!col %in% c("nCount_RNA", "nFeature_RNA", "nCount_SCT", "nFeature_SCT", "percent.mt")) { stop("scrustio: the output's column ", col, " would replace the object's", call. = FALSE) } if (!identical(as.double(md[[col]]), as.double(have[[col]]))) { diff --git a/loaders/R/scrustio/README.md b/loaders/R/scrustio/README.md index 4697931..6fb7746 100644 --- a/loaders/R/scrustio/README.md +++ b/loaders/R/scrustio/README.md @@ -14,7 +14,7 @@ Seurat names features as `Read10X()` and `CreateSeuratObject()` do (`make.unique()`, then `_` and `|` replaced by `-`), and every list of features of the output is mapped onto the counts' rows; the SingleCellExperiment uses the features file's names, made unique, with the ids, names and types in `rowData`. -**What is not rebuilt** (it is not in a scrust output): the `umap` reduction (scrust does not run RunUMAP, which changes nothing downstream), the `commands` (scrust records its run in `summary.json`), metadata columns of other workflow steps (such as `percent.mt`), and, for objects whose RNA assay was a v3 `Assay` (the workflow's emptyDrops objects, made by `as.Seurat()`), that class: the loader makes the `Assay5` that `CreateSeuratObject()` makes, with the same counts. +**What is not rebuilt** (it is not in a scrust output): the `umap` reduction (scrust does not run RunUMAP, which changes nothing downstream), the `commands` (scrust records its run in `summary.json`), metadata columns of other workflow steps (`percent.mt` only when the output did not compute it: `scrust cluster --counts` and `scrust sctransform` write it when asked for, with `--percent-mt`, `--mt-genes` or `--vars-to-regress percent.mt`, and the loaders then load it as a double column; milestone M15b), and, for objects whose RNA assay was a v3 `Assay` (the workflow's emptyDrops objects, made by `as.Seurat()`), that class: the loader makes the `Assay5` that `CreateSeuratObject()` makes, with the same counts. **`cells_step1` is drawn again, not read.** The SCTModel's cell attributes say which cells vst() fitted on in its first step. SCTransform calls `set.seed(seed.use)` and passes vst `min(ncells, cells)`; vst takes every cell when there are at most `ncells` (5,000 by default), and otherwise draws them with `sample(colnames(umi), ncells)`, the first draw after that `set.seed()`. The output does not list the drawn cells; its manifest records the seed and `ncells` (the parameters and the seeds). That is enough to make the same draw, so no file was added for them. The loader therefore: diff --git a/loaders/R/scrustio/tests/scrustio_tests.R b/loaders/R/scrustio/tests/scrustio_tests.R index a7c4889..c6c02a4 100644 --- a/loaders/R/scrustio/tests/scrustio_tests.R +++ b/loaders/R/scrustio/tests/scrustio_tests.R @@ -4,7 +4,8 @@ # SCRUST_ROOT (env.sh) locates the committed fixtures and .rlib/; the scrust binary (SCRUST_BIN, else # $SCRUST_ROOT/target/release/scrust) makes the outputs the tests load: an export of a tier-T # object, scrust sctransform --corrected-counts, scrust doubletfinder (with and without its nested -# outputs, M15) and scrust cluster without --export. Exit status 1 if a test fails. +# outputs, M15), scrust cluster without --export, and an export and a scrust sctransform output with +# percent.mt (M15b). Exit status 1 if a test fails. root <- Sys.getenv("SCRUST_ROOT") if (!nzchar(root)) stop("SCRUST_ROOT is not set (source env.sh)") @@ -383,5 +384,30 @@ check(identical(levels(with_hook$seurat_clusters), readLines(file.path(df_in, "s all(c("silhouette_width", "neighborhood_purity") %in% colnames(with_hook[[]])), "nested outputs: clustering on the fly's labels, levels and scores, by add_scrust") +# 7. percent.mt and vars.to.regress (M15b) ----------------------------------------------------------- +# an export with percent.mt (its mitochondrial features given by id: a stand-in list on the test data, +# which has none) regressed with nCount_RNA: percent.mt loads as a double column, exactly as written, +# into the Seurat object, the SCE and add_scrust; the scrust sctransform output carries it too +ids_file <- file.path(tmp, "mt_genes.txt") +feat <- read.delim(gzfile(file.path(counts_in, "features.tsv.gz")), header = FALSE, colClasses = "character") +writeLines(c("# a stand-in list", feat$V1[grepl("^Rp[ls]", feat$V2)][1:5], "NOT_A_FEATURE"), ids_file) +pm_out <- file.path(tmp, "export_percent_mt") +run("cluster", "--counts", counts_in, "--preset", "workflow", "--export", "--vars-to-regress", "percent.mt,nCount_RNA", + "--mt-genes", ids_file, "--out", pm_out, "--threads", "2") +pm_text <- read.delim(file.path(pm_out, "metadata.tsv"), colClasses = "character")$percent.mt +pmo <- load_seurat(pm_out) +check(is.double(pmo$percent.mt) && identical(sprintf("%.17g", pmo$percent.mt), pm_text) && any(pmo$percent.mt > 0), + "percent.mt: a double column of meta.data, exactly as written") +check(identical(colnames(pmo[[]])[1:4], c("orig.ident", "nCount_RNA", "nFeature_RNA", "percent.mt")), + "percent.mt: after the counts' columns, as the workflow's objects hold it") +pms <- load_sce(pm_out) +check(identical(pms$percent.mt, unname(pmo$percent.mt)), "percent.mt: in the SCE's colData") +with_pm <- suppressMessages(add_scrust(bare, pm_out)) +check(identical(with_pm$percent.mt, pmo$percent.mt), "percent.mt: added by add_scrust") +pm_sct <- file.path(tmp, "sctransform_percent_mt") +run("sctransform", "--counts", counts_in, "--seed", "12345", "--percent-mt", "--mt-genes", ids_file, "--corrected-counts", + "--out", pm_sct, "--threads", "2") +check(identical(load_seurat(pm_sct)$percent.mt, pmo$percent.mt), "percent.mt: scrust sctransform's cell_metadata.tsv") + cat(sprintf("scrustio %s: %d tests, %d failed\n", as.character(packageVersion("scrustio")), n_tests, length(failures))) if (length(failures)) quit(status = 1) diff --git a/loaders/python/scrustio/README.md b/loaders/python/scrustio/README.md index 75a6673..70d05fe 100644 --- a/loaders/python/scrustio/README.md +++ b/loaders/python/scrustio/README.md @@ -19,7 +19,7 @@ From `scrust cluster --export`: Genes are named by the features file's names, made unique as scanpy does (`var_names_make_unique`); `var["gene_ids"]` and `var["feature_types"]` hold the rest. From `scrust sctransform --corrected-counts` (no raw counts there) `var` holds the model genes; from `scrust doubletfinder`, `layers["counts"]` holds the singlets' raw counts, `obs` DoubletFinder's calls (named as DoubletFinder names them), and `X` stays empty: only SCTransform's log1p data go there. -**What is not rebuilt:** the UMAP; metadata columns of other workflow steps; and `uns["sct_model"]["cell_attributes"]["cells_step1"]` for objects above 5,000 cells (vst() drew those cells with R's `sample()`, which this loader does not reproduce; the R loader does). +**What is not rebuilt:** the UMAP; metadata columns of other workflow steps (`percent.mt` is loaded, as a float column of `obs`, when the output computed it: `scrust cluster --counts` and `scrust sctransform` with `--percent-mt`, `--mt-genes` or `--vars-to-regress percent.mt`; milestone M15b); and `uns["sct_model"]["cell_attributes"]["cells_step1"]` for objects above 5,000 cells (vst() drew those cells with R's `sample()`, which this loader does not reproduce; the R loader does). **Seurat's data layer is read, not recomputed.** Its values are the C library's `log1p` (R's). numpy's `np.log1p` may differ in the last bit (in 13,457 of 65,546 values of one test export, numpy 2.5.5), so `X` must come from the file; the loader checks it against `math.log1p` of the corrected counts. diff --git a/loaders/python/scrustio/scrustio/anndata_loader.py b/loaders/python/scrustio/scrustio/anndata_loader.py index 331f4b7..6786217 100644 --- a/loaders/python/scrustio/scrustio/anndata_loader.py +++ b/loaders/python/scrustio/scrustio/anndata_loader.py @@ -27,7 +27,7 @@ from .sctmodel import model_parts, sct_tables from .slots import check_slot, read_for_slot -META_DOUBLE = ("nCount_RNA", "nCount_SCT", "silhouette_width", "neighborhood_purity") +META_DOUBLE = ("nCount_RNA", "percent.mt", "nCount_SCT", "silhouette_width", "neighborhood_purity") META_INTEGER = ("nFeature_RNA", "nFeature_SCT") diff --git a/loaders/python/scrustio/tests/conftest.py b/loaders/python/scrustio/tests/conftest.py index 2ed8cf1..91162e8 100644 --- a/loaders/python/scrustio/tests/conftest.py +++ b/loaders/python/scrustio/tests/conftest.py @@ -33,7 +33,7 @@ def _run(*args): @pytest.fixture(scope="session") def outputs(tmp_path_factory): d = tmp_path_factory.mktemp("scrust") - out = {k: str(d / k) for k in ("export", "sctransform", "cluster", "doubletfinder", "doubletfinder_nested")} + out = {k: str(d / k) for k in ("export", "sctransform", "cluster", "doubletfinder", "doubletfinder_nested", "export_percent_mt")} _run("cluster", "--counts", COUNTS_IN, "--preset", "workflow", "--export", "--out", out["export"], "--threads", "2") _run("sctransform", "--counts", COUNTS_IN, "--seed", "12345", "--corrected-counts", "--out", out["sctransform"], "--threads", "2") _run("cluster", "--counts", COUNTS_IN, "--preset", "workflow", "--out", out["cluster"], "--threads", "2") @@ -43,6 +43,16 @@ def outputs(tmp_path_factory): # (singlets_clusters/), nested outputs _run("doubletfinder", "--counts", DF_IN, "--out", out["doubletfinder_nested"], "--cluster-stats", "silhouette,purity", "--recluster", "--recluster-export", "--threads", "2") + # M15b: an export with percent.mt (a stand-in list of ids: the test data has no mitochondrial + # gene), regressed with nCount_RNA + import gzip + with gzip.open(os.path.join(COUNTS_IN, "features.tsv.gz"), "rt") as f: + feats = [line.rstrip("\n").split("\t") for line in f] + ids = [r[0] for r in feats if r[1].startswith(("Rpl", "Rps"))][:5] + ids_file = d / "mt_genes.txt" + ids_file.write_text("# a stand-in list\n" + "\n".join(ids) + "\nNOT_A_FEATURE\n") + _run("cluster", "--counts", COUNTS_IN, "--preset", "workflow", "--export", "--vars-to-regress", "percent.mt,nCount_RNA", + "--mt-genes", str(ids_file), "--out", out["export_percent_mt"], "--threads", "2") return out diff --git a/loaders/python/scrustio/tests/test_scrustio.py b/loaders/python/scrustio/tests/test_scrustio.py index 5e39bce..b5420d0 100644 --- a/loaders/python/scrustio/tests/test_scrustio.py +++ b/loaders/python/scrustio/tests/test_scrustio.py @@ -269,3 +269,17 @@ def test_cluster_output_without_export_holds_no_matrices(outputs): assert not m.has_role("raw_counts") and not m.has_role("sct_counts") with pytest.raises(ScrustError, match="neither raw counts nor"): scrustio.load_anndata(outputs["cluster"]) + + +def test_percent_mt(outputs): + """M15b: an export with percent.mt loads it as a float column of obs, exactly as written, + after the counts' columns.""" + import scrustio + + d = outputs["export_percent_mt"] + a = scrustio.load_anndata(d) + text = pd.read_csv(os.path.join(d, "metadata.tsv"), sep="\t", dtype=str)["percent.mt"].tolist() + assert a.obs["percent.mt"].dtype == np.float64 + assert [float(t) for t in text] == a.obs["percent.mt"].tolist() + assert list(a.obs.columns[:3]) == ["nCount_RNA", "nFeature_RNA", "percent.mt"] + assert (a.obs["percent.mt"] > 0).any() diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/metadata.tsv.gz b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/metadata.tsv.gz new file mode 100644 index 0000000..88fe0dd Binary files /dev/null and b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/seurat_clusters_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/seurat_clusters_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/summary.json b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/summary.json new file mode 100644 index 0000000..260f1ad --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids/summary.json @@ -0,0 +1,215 @@ +{ + "result": { + "level": "full", + "n_cells": 267, + "idents_equal_seurat_clusters": true, + "n_clusters": 4, + "cluster_sizes": [100, 79, 45, 43], + "default_assay": "SCT", + "assays": { + "RNA": "Assay", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 821, + "sct_nnz": 61367, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "7e19ef21c6fa048d8736c6e472ef92f53eceee2701bc081aad46db8acc88fa90", + "sct_data_x_sha256": "02430cf7d4667b6330cbd0f435740050583b4c1435b41e205812cf3e9f3f8eb6", + "scale_data_dim": [821, 267], + "scale_data_sha256": "cb972ab9c00b64c897d8af847ce039a8942894c751c07f8d6858e69862c9af69", + "n_variable_features": 821, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay", + "seed": 12345, + "optimizer": { + "nodes": 267, + "edges": 12241, + "max_modularity": "0.4940", + "communities": 4, + "singletons": 0, + "final_clusters": 4 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "c6e761b05213550401a02c32f96c4a130904f0384f37bda9419746d0b183c279", + "RunUMAP": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindNeighbors": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindClusters": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "add_silhouette_to_metadata": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d" + }, + "rng_end_sha256": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "covariates": { + "percent_mt": { + "definition": "ids", + "file": "data/clustering/m15b/inputs/filtered_seurat_emptydrops_test/mt_genes.txt", + "sha256": "33fa18ada09c2dc5d375d3f16b658ac5ae7b6b85a8655be1da9db80a1e475184", + "features": ["Rpl5", "Rplp2", "Rpl13", "Rpsa", "Rpl26", "Rpl19", "Rpl17"], + "ids_not_found": ["NOT_A_FEATURE_1", "NOT_A_FEATURE_2"], + "cells_zero": 0 + } + }, + "regression": { + "vars": ["percent.mt"], + "rank": 2, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/filtered_seurat_emptydrops_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/filtered_seurat_emptydrops_test/ids/direct-portable-cascadelake.partial.62084538", + "level": "full", + "umap": true, + "assay": "v3", + "start_time": "2026-11-19T07:07:04-0500", + "slurm_job_id": "62084538", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22505.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084538", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22505", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.20400000000000063, + "peak_rss_kib": 706672, + "rss_kib": 706672 + }, + "covariates": { + "elapsed_s": 0.25500000000000078, + "peak_rss_kib": 706812, + "rss_kib": 706812 + }, + "SCTransform": { + "elapsed_s": 3.4100000000000001, + "peak_rss_kib": 834552, + "rss_kib": 834552 + }, + "RunPCA": { + "elapsed_s": 3.7300000000000004, + "peak_rss_kib": 851152, + "rss_kib": 848340 + }, + "RunUMAP": { + "elapsed_s": 6.5440000000000023, + "peak_rss_kib": 851152, + "rss_kib": 849484 + }, + "FindNeighbors": { + "elapsed_s": 6.9270000000000014, + "peak_rss_kib": 851152, + "rss_kib": 849648 + }, + "FindClusters": { + "elapsed_s": 6.9779999999999998, + "peak_rss_kib": 851152, + "rss_kib": 849648 + }, + "silhouette": { + "elapsed_s": 7.2620000000000022, + "peak_rss_kib": 851152, + "rss_kib": 849960 + }, + "purity": { + "elapsed_s": 7.2810000000000006, + "peak_rss_kib": 851152, + "rss_kib": 850120 + }, + "chain_end": { + "elapsed_s": 7.2829999999999995, + "peak_rss_kib": 851152, + "rss_kib": 850120 + }, + "write": { + "elapsed_s": 8.0550000000000015, + "peak_rss_kib": 890536, + "rss_kib": 890536 + } + }, + "peak_rss_kib": 899936, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 267", "Number of edges: 12241", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.4940", "Number of communities: 4", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/metadata.tsv.gz b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/metadata.tsv.gz new file mode 100644 index 0000000..babe3be Binary files /dev/null and b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/seurat_clusters_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/seurat_clusters_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/summary.json b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/summary.json new file mode 100644 index 0000000..c8344f3 --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/ids_ncount/summary.json @@ -0,0 +1,215 @@ +{ + "result": { + "level": "full", + "n_cells": 267, + "idents_equal_seurat_clusters": true, + "n_clusters": 4, + "cluster_sizes": [96, 83, 45, 43], + "default_assay": "SCT", + "assays": { + "RNA": "Assay", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 821, + "sct_nnz": 61367, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "7e19ef21c6fa048d8736c6e472ef92f53eceee2701bc081aad46db8acc88fa90", + "sct_data_x_sha256": "02430cf7d4667b6330cbd0f435740050583b4c1435b41e205812cf3e9f3f8eb6", + "scale_data_dim": [821, 267], + "scale_data_sha256": "46672a919138ca2cdfa752d8bb0b134861de16c198f8c2a5763590eaae596e38", + "n_variable_features": 821, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay", + "seed": 12345, + "optimizer": { + "nodes": 267, + "edges": 12263, + "max_modularity": "0.4947", + "communities": 4, + "singletons": 0, + "final_clusters": 4 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "c6e761b05213550401a02c32f96c4a130904f0384f37bda9419746d0b183c279", + "RunUMAP": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindNeighbors": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindClusters": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "add_silhouette_to_metadata": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d" + }, + "rng_end_sha256": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "covariates": { + "percent_mt": { + "definition": "ids", + "file": "data/clustering/m15b/inputs/filtered_seurat_emptydrops_test/mt_genes.txt", + "sha256": "33fa18ada09c2dc5d375d3f16b658ac5ae7b6b85a8655be1da9db80a1e475184", + "features": ["Rpl5", "Rplp2", "Rpl13", "Rpsa", "Rpl26", "Rpl19", "Rpl17"], + "ids_not_found": ["NOT_A_FEATURE_1", "NOT_A_FEATURE_2"], + "cells_zero": 0 + } + }, + "regression": { + "vars": ["percent.mt", "nCount_RNA"], + "rank": 3, + "pivot": [1, 2, 3], + "n_columns": 3 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/filtered_seurat_emptydrops_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/filtered_seurat_emptydrops_test/ids_ncount/direct-portable-cascadelake.partial.62084539", + "level": "full", + "umap": true, + "assay": "v3", + "start_time": "2026-11-19T07:06:57-0500", + "slurm_job_id": "62084539", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22505.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084539", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22505", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.19699999999999918, + "peak_rss_kib": 704888, + "rss_kib": 704888 + }, + "covariates": { + "elapsed_s": 0.25099999999999945, + "peak_rss_kib": 704888, + "rss_kib": 704888 + }, + "SCTransform": { + "elapsed_s": 3.5719999999999992, + "peak_rss_kib": 829292, + "rss_kib": 829292 + }, + "RunPCA": { + "elapsed_s": 3.8819999999999997, + "peak_rss_kib": 848132, + "rss_kib": 848132 + }, + "RunUMAP": { + "elapsed_s": 6.6629999999999985, + "peak_rss_kib": 848532, + "rss_kib": 829252 + }, + "FindNeighbors": { + "elapsed_s": 7.0540000000000003, + "peak_rss_kib": 848532, + "rss_kib": 831376 + }, + "FindClusters": { + "elapsed_s": 7.1070000000000011, + "peak_rss_kib": 848532, + "rss_kib": 831376 + }, + "silhouette": { + "elapsed_s": 7.4339999999999993, + "peak_rss_kib": 848532, + "rss_kib": 834832 + }, + "purity": { + "elapsed_s": 7.4550000000000001, + "peak_rss_kib": 848532, + "rss_kib": 834972 + }, + "chain_end": { + "elapsed_s": 7.456999999999999, + "peak_rss_kib": 848532, + "rss_kib": 834972 + }, + "write": { + "elapsed_s": 8.270999999999999, + "peak_rss_kib": 887220, + "rss_kib": 887220 + } + }, + "peak_rss_kib": 896480, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 267", "Number of edges: 12263", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.4947", "Number of communities: 4", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/metadata.tsv b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/metadata.tsv new file mode 100644 index 0000000..1209176 --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/metadata.tsv @@ -0,0 +1,268 @@ +barcode score label +AGACCCGCAATTAGGA-1 9.5350257728550929 a +GTACAACAGGCATGCA-1 +1.11081471750811 b +TCAATCTGTGCATTTG-1 +25.8730503030716 b +GAAGTAACACATTCTT-1 45 b +AGAACCTTCGCTTGAA-1 1.7163e+01 a +AGTTCCCTCGAAGAAT-1 2.7146e+01 a +TGAGCATGTACTCCGG-1 9 b +CCCTTAGGTAGCCAGA-1 32 b +GCATCTCAGTAGCATA-1 1.0741e+01 a +TGCTTCGGTAGAGTTA-1 36.3467 b +CCGGACAAGGCACCAA-1 0.047 a +AAGGAATAGGCGAACT-1 13.89685304053986 a +GTCATTTAGAGCAACC-1 5.0986e+00 a +GCCAGGTCACGGTGAA-1 27 b +TCAATTCCATTGCTGA-1 37.612050541606884 a +ATCCATTCACTCTGCT-1 +49.2101268731808 b +TCCGAAATCTACTTCA-1 4 b +GACGTTAGTCATTCCC-1 +48.5448952345823 b +CAGGTATTCCGGACTG-1 -1.50879 b +AACGTCATCGATACTG-1 28.516630753058713 a +CATGCGGCAATCTGCA-1 17 b +CCAATGACAATACCTG-1 28.7138 b +GCCAGTGAGTAGGTTA-1 0.007 a +AAGACAACAGTCGCTG-1 1.2671e+01 a +ACTATTCAGATTGTGA-1 31 b +ACTTCCGAGTAGGCCA-1 26.721369237626835 a +GGCTGTGAGCTCTGTA-1 0.013 a +ACTCTCGCAATCGCCG-1 0.004 a +GGGACAATCCCTTCCC-1 33.458007257500441 a +GTGAGCCCAACCGGAA-1 2.0154e+01 a +TAGGTACAGAGATCGC-1 +7.64582341633036 b +AGCTTCCCAAGTGGAC-1 +37.6676258231131 b +CCCGAAGGTAGCGATG-1 48.056564891272075 a +TTACCATCAAACTAGA-1 22 b +TCATTGTAGGCGACAT-1 +6.51319820972993 b +GACGCTGTCACGACTA-1 0.006 a +GTTCCGTGTCGTCGGT-1 +12.6661711899727 b +CTAGACACACGGTGCT-1 +29.5811967170448 b +TTAGGCAGTGAACTAA-1 +43.7416786278812 b +GTTGTAGTCTAAGCGT-1 34.709262427146172 a +CATAAGCAGGCCCGTT-1 0.005 a +GCAGCCACAACGATTC-1 33.4856 b +ATCTCTAGTCAGACTT-1 1.0005 b +TAACGACGTGCGCTCA-1 0.018 a +TATATCCTCGACGATT-1 1.8486e+01 a +TCTTCCTGTTAGAGAT-1 2.3394e+01 a +CTACCTGGTCCCGGTA-1 -0.002 a +TTCAATCCAATGGGTG-1 3.8511251835537967 a +AGCGCTGAGGCCTAAG-1 19 b +AAACGCTGTGACCGAA-1 47.6959 b +ACTATCTGTAGGCTCC-1 3.5094e+01 a +TGTTTGTAGGCATGGT-1 31.4618 b +GGTGATTAGACCGTTT-1 12 b +AGCCAGCTCTAACGCA-1 3.6496e+01 a +TGATCAGCACACAGCC-1 0.049 a +TGATTCTTCCCATAAG-1 1.1304e+01 a +GTTCATTAGCCTCAGC-1 0.045 a +TGCGGCATCTTACCGC-1 +29.733564658982 b +TAATTCCGTCGTTCAA-1 +35.722344333707 b +AGGGTCCCATCCGATA-1 24.514296992326695 a +ATTCCATTCGTGACTA-1 26 b +GCAGCCAAGCAAGCCA-1 20.120623712564942 a +TGTAACGCACTCGATA-1 0.035 a +TTTAGTCTCTTTCTAG-1 0.045 a +TCCTCGATCACACGAT-1 +47.2101924540167 b +ACAGGGAGTCATGGCC-1 31 b +GAGGGTAGTGGATTTC-1 0.030 a +TCTTCCTGTCTACATG-1 31.2864 b +TGCTTCGTCTTCCGTG-1 1.1360e+01 a +TCAGTTTGTACCTGTA-1 -1.6137e+00 a +TTTGGTTAGCTCCGAC-1 34.6125 b +TTACCATAGTAAACGT-1 4.6256e+00 a +TGATCAGTCGAGTACT-1 +49.4245130762138 b +AACACACCAGTCCGTG-1 31 b +TGGATCAAGATGCTTC-1 0.042 a +TTTGATCTCGTCTACC-1 23.09472397984133 a +GGAGGTAAGAGACAAG-1 29.0142 b +GTCACGGAGTTGGAAT-1 19.525955381499283 a +TATTTCGAGATCCAAA-1 0 b +GAAGAATTCCGTACGG-1 4.1012e+01 a +GAGCCTGCACGTGAGA-1 42 b +ACCTACCGTAGGCTGA-1 +10.394041836322 b +GTGTAACCATCTTCGC-1 3.1263e+01 a +GTGCACGCAACCAACT-1 22 b +TAGGTTGGTCTGTCCT-1 46.512727406067647 a +GTGGAAGGTAGAGCTG-1 29.684817477377791 a +ACTACGATCCTGGGAC-1 9.1219 b +CCGGTGAAGTGAGTGC-1 +2.22652473266015 b +AAACGAAAGGATTCCT-1 16.688161498250672 a +TCAAGTGAGTGCTCAT-1 0.037 a +CTTCTCTAGGGCTGAT-1 39.1678 b +ACAGGGACAGCCTATA-1 4.1644e+01 a +ATGCATGAGAACAAGG-1 30 b +CCACTTGAGTCACGAG-1 3.7611e+01 a +TCACGGGCAGCCTTCT-1 39.9617 b +CTCCTTTCAGGACAGT-1 12 b +CAGCACGAGTCATACC-1 +34.4016386198336 b +ACCATTTCATACAGCT-1 0.038 a +CAGCGTGCAGGTGAGT-1 12.156328391596716 a +AAGTACCGTTTCGTAG-1 19.0558 b +AGAAGCGGTTTAAGGA-1 0 b +GTCCTCATCCGTTTCG-1 4.8985005837757214 a +ATTCCCGTCTAAGGAA-1 0.047 a +AAGCGTTCAGACCTAT-1 +44.4388008454264 b +TGCGGCAGTTGTGCCG-1 0.001 a +ATGCCTCTCCGACGGT-1 0.005 a +TCATTGTGTCAAAGCG-1 40.277626275966362 a +AGGATAAAGCTCATAC-1 -1.0302e+00 a +TCGTGCTCAAAGTGTA-1 +41.6698834410453 b +CCCTAACCAGGATGAC-1 16.1156 b +CAGAGCCTCCAAGCAT-1 0.039 a +TTGTGGATCATGGATC-1 24.2843 b +TTCAGGATCTATTGTC-1 4.0436e+01 a +AATCACGGTGGACAGT-1 7 b +GCGAGAAAGCGTTACT-1 7.93502 b +CTGAATGTCGGCTGTG-1 2.4749496007307643 a +ACTTCCGCAGAACCGA-1 21.2765 b +CCACTTGTCCACTTCG-1 4 b +GGAGGATCAGGCACTC-1 32.495961937838338 a +AGTGCCGGTCATGCAT-1 17.8233 b +CCTGCATTCTCCTGAC-1 33.523616481275646 a +ACGTAGTTCGCACTCT-1 +46.5853361167338 b +TCGGGCAGTTCCTTGC-1 30 b +TTCCACGCATTGGCAT-1 24 b +CACCGTTCATTCTCCG-1 42 b +CTCCGATGTACCCGAC-1 4.1878e+01 a +TTACGCCCACGAGAAC-1 0.020 a +CAGTTAGCAAGGAGTC-1 43 b +AGGCCACCATGAAGGC-1 15 b +GATCATGAGGACAGCT-1 24.304284335447782 a +CATCCCAGTTTCACTT-1 3.8178e+00 a +AGCTTCCGTGTCATTG-1 37.853613196583126 a +CACAGATAGCGACTAG-1 3.0780e+01 a +CATGCTCAGATAACAC-1 0.028 a +GTGGTTAAGGTAGCAC-1 10.3898 b +GTCCACTTCTGAACGT-1 +14.8229085244195 b +ACAACCACAAGACAAT-1 5.6720052406975388 a +TGCAGTATCTCAGTCC-1 8 b +CATTGTTAGCCAAGCA-1 +17.3503058597443 b +TGGAACTGTACAGCGA-1 22 b +TTCCGTGAGAGAACCC-1 0.030 a +GCCATTCCAGGTCAAG-1 22.902305976068032 a +CGTGATACATTGGATC-1 3.2127e+00 a +GCACATAGTCATAGTC-1 +12.9534595692796 b +GGAGAACTCATCGCAA-1 1 b +GAGACCCTCCCTCGAT-1 22.4808 b +ACCTGAATCACTAGCA-1 21.429802905202173 a +TATACCTAGCCGGATA-1 44.2638 b +GTGTCCTTCTGCAGCG-1 22 b +TCGTAGATCGATTCCC-1 0.013 a +TCCTAATTCCGCGAGT-1 -0.000 a +GCCAGTGGTATCGTGT-1 +44.2261876956267 b +CTCCAACTCGCCTATC-1 43.85 b +TCATCATTCTCTATGT-1 -0.001 a +TTCACCGCAGACCAAG-1 -2.25671 b +CACAACATCGCCTAGG-1 30.7902 b +AGTCTCCAGTTGCATC-1 20.021073311561373 a +GCTTTCGCACAAGCAG-1 2.0018e+01 a +GATGATCAGACGATAT-1 2.2004e+01 a +GATGCTATCAACGAGG-1 3 b +AGGACGAGTTCGGGTC-1 31.7801 b +ATGGTTGCATACAGAA-1 23.973115961299207 a +CAATACGGTAATTAGG-1 -1.5466183004275904 a +ATTACTCAGCAAACAT-1 13.0466 b +CTCGAGGTCAAGTGTC-1 0.042 a +AGGGTGAAGCCTGAAG-1 20.3212 b +ATGAGGGGTTATTCCT-1 3.3333e+01 a +TTTACGTGTGGTCTGC-1 6 b +AGCGTATTCAAGCTGT-1 0.004 a +TGGCGTGGTCTGTTAG-1 8.5346369534359123 a +TCATCATTCGGAACTT-1 0 b +CGTCAAATCATGGGAG-1 33.7488 b +CATACTTCAGTCGCTG-1 37.1814 b +GGGATCCTCCCGAATA-1 -2.47189 b +CCCTAACGTTGCGAAG-1 3.2286e+01 a +TCCTTCTCAAGTACCT-1 1.0558472128263103 a +TGATGGTCAATCAAGA-1 31.7883 b +ATCACGAAGCGTCAAG-1 43 b +GAGACTTGTGTAGTGG-1 7.0120e+00 a +ACGGAAGCAGACCGCT-1 2.8786e+01 a +AAGCCATGTTATGACC-1 34 b +TGTAGACAGGCTAGCA-1 +35.8338226027052 b +AATGGCTCAACACGAG-1 +36.41255180256 b +ACCTGTCTCCGTACGG-1 8.86584 b +CGTAATGGTCAACGCC-1 6.2801534626896593 a +TGCTCGTGTTCTCGTC-1 31.443894859535426 a +AGAAGTAAGGTTACCT-1 0.000 a +CGAGAAGCATTCATCT-1 36.3339 b +AGGTTACCAATAGTAG-1 29 b +CGTAAGTGTAAGGCTG-1 +16.3564879232813 b +CAGTGCGTCCGGACTG-1 1.6688e+01 a +GTCAGCGGTCCATCTC-1 18.7179 b +TGGGCGTGTCCCGTGA-1 21 b +CGCCAGACAAATGGAT-1 11 b +ATTCATCGTTATAGAG-1 2.2904e+01 a +GGGTGAAGTAAGTTAG-1 4.4676e+01 a +AATGACCAGTTCCAGT-1 0.031 a +GAGTCATTCAAGTTGC-1 +20.6261927655074 b +CCACTTGTCGTGGAAG-1 0.015 a +TACCCGTCATTGTAGC-1 1.4244e+01 a +TCTGTCGCAGAAGCGT-1 28.988646796203337 a +ACTGATGCAACTTGCA-1 +24.6666769822365 b +GTTGTCCGTGTCACAT-1 7.01378 b +AACCACACATAAGATG-1 0.004 a +GAGAAATCATAGATGA-1 38.613514523886245 a +TCGATTTAGGTCATAA-1 42.2054 b +AGAGCCCAGCCGGATA-1 47.3882 b +TACAACGCAACGCCCA-1 26.612437934495286 a +TGGGCGTGTAACCCTA-1 1.5021e+01 a +TGGATGTTCCGAAGGA-1 +36.24328571912 b +CGGAGAAAGGCGTCCT-1 0.025 a +GTGCTGGAGACTAGAT-1 +16.5669232505649 b +CCAAGCGCATGGGATG-1 20.647616939834617 a +AACCTTTCACGGGTAA-1 +24.3495495373719 b +TAACGACAGAGGTTAT-1 -2 b +TGTCCTGTCAACGAGG-1 18.22337657891811 a +AGGTGTTTCGCCATAA-1 2.1905e+01 a +TGGGAGAGTCTGTCCT-1 41.0298 b +CCCGAAGCATTGCTTT-1 +8.10526078155815 b +CAAAGAAAGTCATCGT-1 +28.8836855357289 b +AGGGTCCCAGCATCTA-1 +38.2834405284716 b +TTGCATTTCACTGCTC-1 45.172970284250546 a +TTCTCTCAGAGAAGGT-1 +2.01399400793311 b +ATCCCTGGTGGGTTGA-1 21.500385609247644 a +CTCAACCCAGATACTC-1 34.90302018502576 a +TCCATCGTCGAGCCTG-1 41.6991 b +AGTAGCTGTACAAGTA-1 +1.08588459282025 b +ACGTAGTCAGCTAACT-1 0.018 a +TACCTGCTCTAAGCCA-1 16 b +GTGCACGTCAGGAAGC-1 0.022 a +TAGATCGCAATCACGT-1 0.019 a +ACAAGCTGTCATTGCA-1 1.46297 b +CGATGCGCAGGTGTGA-1 -1.6472e+00 a +AACTTCTGTAGTAAGT-1 0.423935 b +TTGTGGATCCTCAGAA-1 8.4993e+00 a +CTAACTTCACGCCAGT-1 46 b +GGAGCAAGTCTAGTGT-1 +12.3712386940237 b +GTCCACTGTTCGATTG-1 -0.001 a +TCGGGACGTAACATAG-1 4.2778e+01 a +ATGCGATTCGGCCTTT-1 +44.8423084043801 b +AACAAAGGTAAGATTG-1 4.4787e+01 a +TGATGCAGTTTCGTTT-1 34.854364628815233 a +GGCACGTCAGCACCCA-1 37 b +AAGCGAGCACTACACA-1 0.021 a +ACGGTTATCCGAACGC-1 5 b +GTCCACTCACTTTATC-1 0 b +AGACACTCAAATAAGC-1 +13.3581150819315 b +CTCTGGTTCCTTCTGG-1 +20.4719737014492 b +ATCACTTTCTTCCTAA-1 0.016 a +GGAGATGTCAGTGTGT-1 0.015 a +TTTCGATCAATTCACG-1 +20.668260105122 b +GGATCTACAGGCATGA-1 3.5159e+01 a +CATACCCGTCAGTCTA-1 +46.01618023633 b +AGTACTGAGAAGTATC-1 0.003 a +TAACCAGTCATGCAGT-1 2.2801e+01 a +TCCCATGGTATCAGCT-1 3.4657e+01 a +ACGTCCTTCACCATCC-1 -0.16274304537639672 a +AGGGCCTAGTTTGTCG-1 0.039 a +GGCTGTGTCTCCGATC-1 +0.416017120295446 b +GATGCTATCGGTCACG-1 0.034 a +GTCGTTCTCGAGTACT-1 29.467 b +CATACTTCAAGCTCTA-1 33.115203767582848 a +GTAACCAAGGTTCCGC-1 0.011 a +TTTGTTGAGAGCAGTC-1 2.8817e+01 a +GATCATGAGGCCCGTT-1 9.91521 b +AAGTCGTTCGGTGTAT-1 2.4795e+01 a +TACATTCTCAGCATTG-1 30.7776 b diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/mt_genes.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/mt_genes.txt new file mode 100644 index 0000000..0a9628d --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/mt_genes.txt @@ -0,0 +1,12 @@ +# tier T has no mitochondrial gene: a stand-in set, the ribosomal protein genes (Rpl*, Rps*) +Rpl5 +Rplp2 +Rpl13 + +Rpsa +Rpl26 +Rpl19 +Rpl17 +Rpl5 +NOT_A_FEATURE_1 +NOT_A_FEATURE_2 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/zero_genes.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/zero_genes.txt new file mode 100644 index 0000000..83cdb89 --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/inputs/zero_genes.txt @@ -0,0 +1,4 @@ +# three features with no counts in any cell: percent.mt is 0 in every cell +Gm17644 +Gm29663 +Gm28095 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/metadata.tsv.gz b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/metadata.tsv.gz new file mode 100644 index 0000000..ccd45cb Binary files /dev/null and b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/seurat_clusters_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/seurat_clusters_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/summary.json b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/summary.json new file mode 100644 index 0000000..15c7764 --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/meta/summary.json @@ -0,0 +1,216 @@ +{ + "result": { + "level": "full", + "n_cells": 267, + "idents_equal_seurat_clusters": true, + "n_clusters": 4, + "cluster_sizes": [84, 65, 59, 59], + "default_assay": "SCT", + "assays": { + "RNA": "Assay", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 821, + "sct_nnz": 61367, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "7e19ef21c6fa048d8736c6e472ef92f53eceee2701bc081aad46db8acc88fa90", + "sct_data_x_sha256": "02430cf7d4667b6330cbd0f435740050583b4c1435b41e205812cf3e9f3f8eb6", + "scale_data_dim": [821, 267], + "scale_data_sha256": "5a247624a47cfd1f3c465da4e9c4b86711ddcb963ba2363d224a2a61ef51abfc", + "n_variable_features": 821, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay", + "seed": 12345, + "optimizer": { + "nodes": 267, + "edges": 11622, + "max_modularity": "0.5123", + "communities": 4, + "singletons": 0, + "final_clusters": 4 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "c6e761b05213550401a02c32f96c4a130904f0384f37bda9419746d0b183c279", + "RunUMAP": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindNeighbors": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindClusters": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "add_silhouette_to_metadata": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d" + }, + "rng_end_sha256": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "covariates": { + "metadata": { + "file": "data/clustering/m15b/inputs/filtered_seurat_emptydrops_test/metadata.tsv", + "sha256": "77c4d1845370242ae974ce2a0f9a3967b906c97de3be2e048c8b6bba7d081223", + "columns": ["score", "label"], + "classes": { + "score": "numeric", + "label": "character" + } + } + }, + "regression": { + "vars": ["score"], + "rank": 2, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/filtered_seurat_emptydrops_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/filtered_seurat_emptydrops_test/meta/direct-portable-cascadelake.partial.62084540", + "level": "full", + "umap": true, + "assay": "v3", + "start_time": "2026-11-19T07:07:52-0500", + "slurm_job_id": "62084540", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22505.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084540", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22505", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.20000000000000107, + "peak_rss_kib": 704792, + "rss_kib": 704792 + }, + "covariates": { + "elapsed_s": 0.23800000000000132, + "peak_rss_kib": 704940, + "rss_kib": 704940 + }, + "SCTransform": { + "elapsed_s": 3.5080000000000009, + "peak_rss_kib": 821448, + "rss_kib": 821456 + }, + "RunPCA": { + "elapsed_s": 3.8070000000000004, + "peak_rss_kib": 838640, + "rss_kib": 838640 + }, + "RunUMAP": { + "elapsed_s": 6.7060000000000013, + "peak_rss_kib": 838816, + "rss_kib": 824792 + }, + "FindNeighbors": { + "elapsed_s": 7.1160000000000014, + "peak_rss_kib": 838816, + "rss_kib": 829728 + }, + "FindClusters": { + "elapsed_s": 7.168000000000001, + "peak_rss_kib": 838816, + "rss_kib": 829796 + }, + "silhouette": { + "elapsed_s": 7.4550000000000001, + "peak_rss_kib": 838816, + "rss_kib": 830004 + }, + "purity": { + "elapsed_s": 7.474000000000002, + "peak_rss_kib": 838816, + "rss_kib": 830172 + }, + "chain_end": { + "elapsed_s": 7.4760000000000009, + "peak_rss_kib": 838816, + "rss_kib": 830172 + }, + "write": { + "elapsed_s": 8.3970000000000002, + "peak_rss_kib": 887120, + "rss_kib": 887120 + } + }, + "peak_rss_kib": 896320, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 267", "Number of edges: 11622", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.5123", "Number of communities: 4", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/metadata.tsv.gz b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/metadata.tsv.gz new file mode 100644 index 0000000..81635be Binary files /dev/null and b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/seurat_clusters_levels.txt new file mode 100644 index 0000000..bc856da --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/seurat_clusters_levels.txt @@ -0,0 +1,4 @@ +0 +1 +2 +3 diff --git a/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/summary.json b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/summary.json new file mode 100644 index 0000000..7f1b4a7 --- /dev/null +++ b/tests/fixtures/clustering/m15b/filtered_seurat_emptydrops_test/pm/summary.json @@ -0,0 +1,213 @@ +{ + "result": { + "level": "full", + "n_cells": 267, + "idents_equal_seurat_clusters": true, + "n_clusters": 4, + "cluster_sizes": [80, 65, 62, 60], + "default_assay": "SCT", + "assays": { + "RNA": "Assay", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 821, + "sct_nnz": 61367, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "7e19ef21c6fa048d8736c6e472ef92f53eceee2701bc081aad46db8acc88fa90", + "sct_data_x_sha256": "02430cf7d4667b6330cbd0f435740050583b4c1435b41e205812cf3e9f3f8eb6", + "scale_data_dim": [821, 267], + "scale_data_sha256": "ad53351b0971d4e635484ef36145e2a2ce4c7fb8586d40e0fab66e0a8ef8cca5", + "n_variable_features": 821, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay", + "seed": 12345, + "optimizer": { + "nodes": 267, + "edges": 11498, + "max_modularity": "0.5188", + "communities": 4, + "singletons": 0, + "final_clusters": 4 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "c6e761b05213550401a02c32f96c4a130904f0384f37bda9419746d0b183c279", + "RunUMAP": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindNeighbors": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "FindClusters": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "add_silhouette_to_metadata": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d" + }, + "rng_end_sha256": "7a9ee1e56bb6f215698eac1392fe46c039e249e23dca22ec88ed986db716358d", + "covariates": { + "percent_mt": { + "definition": "pattern", + "pattern": "(?i)^mt-", + "features": [], + "cells_zero": 267 + } + }, + "regression": { + "vars": ["percent.mt"], + "rank": 1, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/filtered_seurat_emptydrops_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/filtered_seurat_emptydrops_test/pm/direct-portable-cascadelake.partial.62084537", + "level": "full", + "umap": true, + "assay": "v3", + "start_time": "2026-11-19T07:09:07-0500", + "slurm_job_id": "62084537", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22506.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084537", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22506", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.18200000000000038, + "peak_rss_kib": 704928, + "rss_kib": 704928 + }, + "covariates": { + "elapsed_s": 0.23200000000000109, + "peak_rss_kib": 704928, + "rss_kib": 704928 + }, + "SCTransform": { + "elapsed_s": 3.3060000000000009, + "peak_rss_kib": 834992, + "rss_kib": 834992 + }, + "RunPCA": { + "elapsed_s": 3.5960000000000001, + "peak_rss_kib": 851780, + "rss_kib": 851780 + }, + "RunUMAP": { + "elapsed_s": 6.2210000000000001, + "peak_rss_kib": 852424, + "rss_kib": 852424 + }, + "FindNeighbors": { + "elapsed_s": 6.5869999999999997, + "peak_rss_kib": 852456, + "rss_kib": 852456 + }, + "FindClusters": { + "elapsed_s": 6.636000000000001, + "peak_rss_kib": 852516, + "rss_kib": 852516 + }, + "silhouette": { + "elapsed_s": 6.902000000000001, + "peak_rss_kib": 852720, + "rss_kib": 852720 + }, + "purity": { + "elapsed_s": 6.9200000000000017, + "peak_rss_kib": 852780, + "rss_kib": 852780 + }, + "chain_end": { + "elapsed_s": 6.9220000000000006, + "peak_rss_kib": 852780, + "rss_kib": 852780 + }, + "write": { + "elapsed_s": 7.6760000000000019, + "peak_rss_kib": 888684, + "rss_kib": 888848 + } + }, + "peak_rss_kib": 898100, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 267", "Number of edges: 11498", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.5188", "Number of communities: 4", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/metadata.tsv.gz b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/metadata.tsv.gz new file mode 100644 index 0000000..667e5ea Binary files /dev/null and b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/seurat_clusters_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/seurat_clusters_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/summary.json b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/summary.json new file mode 100644 index 0000000..fe640a8 --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids/summary.json @@ -0,0 +1,215 @@ +{ + "result": { + "level": "full", + "n_cells": 300, + "idents_equal_seurat_clusters": true, + "n_clusters": 3, + "cluster_sizes": [129, 113, 58], + "default_assay": "SCT", + "assays": { + "RNA": "Assay5", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 815, + "sct_nnz": 62883, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "8aa076bbd6ab1a3953d06b5fa51923796fc59bbc44a453c99c27bb404bd53009", + "sct_data_x_sha256": "0e0dd2af9f57ef300c2338af4454a9c8f2464aa9fc4b13b3b99e533d982c6a0e", + "scale_data_dim": [815, 300], + "scale_data_sha256": "ab06a253f38c0fb34e90a599a539f5ca10b02ead3f0d083fa199eff320ae7311", + "n_variable_features": 815, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay5", + "seed": 12345, + "optimizer": { + "nodes": 300, + "edges": 22386, + "max_modularity": "0.3917", + "communities": 3, + "singletons": 0, + "final_clusters": 3 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "1fbf20d4b21d1e1833c433257a88af9076e6a23ac3a2cb3b3ab615a1b2056676", + "RunUMAP": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindNeighbors": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindClusters": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "add_silhouette_to_metadata": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c" + }, + "rng_end_sha256": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "covariates": { + "percent_mt": { + "definition": "ids", + "file": "data/clustering/m15b/inputs/soupx_tenx_test/mt_genes.txt", + "sha256": "33fa18ada09c2dc5d375d3f16b658ac5ae7b6b85a8655be1da9db80a1e475184", + "features": ["Rpl5", "Rplp2", "Rpl13", "Rpsa", "Rpl26", "Rpl19", "Rpl17"], + "ids_not_found": ["NOT_A_FEATURE_1", "NOT_A_FEATURE_2"], + "cells_zero": 1 + } + }, + "regression": { + "vars": ["percent.mt"], + "rank": 2, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/soupx_tenx_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/soupx_tenx_test/ids/direct-portable-cascadelake.partial.62084542", + "level": "full", + "umap": true, + "assay": "v5", + "start_time": "2026-11-19T07:08:12-0500", + "slurm_job_id": "62084542", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22502.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084542", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22502", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.43800000000000239, + "peak_rss_kib": 707364, + "rss_kib": 707364 + }, + "covariates": { + "elapsed_s": 0.53099999999999881, + "peak_rss_kib": 708100, + "rss_kib": 708100 + }, + "SCTransform": { + "elapsed_s": 5.054000000000002, + "peak_rss_kib": 862160, + "rss_kib": 862160 + }, + "RunPCA": { + "elapsed_s": 5.4510000000000005, + "peak_rss_kib": 872360, + "rss_kib": 872360 + }, + "RunUMAP": { + "elapsed_s": 8.3370000000000033, + "peak_rss_kib": 872648, + "rss_kib": 861968 + }, + "FindNeighbors": { + "elapsed_s": 8.7070000000000007, + "peak_rss_kib": 872648, + "rss_kib": 865604 + }, + "FindClusters": { + "elapsed_s": 8.777000000000001, + "peak_rss_kib": 872648, + "rss_kib": 865604 + }, + "silhouette": { + "elapsed_s": 10.133000000000003, + "peak_rss_kib": 872648, + "rss_kib": 865892 + }, + "purity": { + "elapsed_s": 10.152999999999999, + "peak_rss_kib": 872648, + "rss_kib": 866052 + }, + "chain_end": { + "elapsed_s": 10.155000000000001, + "peak_rss_kib": 872648, + "rss_kib": 866052 + }, + "write": { + "elapsed_s": 11.890000000000001, + "peak_rss_kib": 902404, + "rss_kib": 902404 + } + }, + "peak_rss_kib": 911640, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 300", "Number of edges: 22386", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.3917", "Number of communities: 3", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..0d66ea1 --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,2 @@ +0 +1 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/metadata.tsv.gz b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/metadata.tsv.gz new file mode 100644 index 0000000..f77ad6d Binary files /dev/null and b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/seurat_clusters_levels.txt new file mode 100644 index 0000000..0d66ea1 --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/seurat_clusters_levels.txt @@ -0,0 +1,2 @@ +0 +1 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/summary.json b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/summary.json new file mode 100644 index 0000000..266b59e --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/ids_ncount/summary.json @@ -0,0 +1,215 @@ +{ + "result": { + "level": "full", + "n_cells": 300, + "idents_equal_seurat_clusters": true, + "n_clusters": 2, + "cluster_sizes": [156, 144], + "default_assay": "SCT", + "assays": { + "RNA": "Assay5", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 815, + "sct_nnz": 62883, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "8aa076bbd6ab1a3953d06b5fa51923796fc59bbc44a453c99c27bb404bd53009", + "sct_data_x_sha256": "0e0dd2af9f57ef300c2338af4454a9c8f2464aa9fc4b13b3b99e533d982c6a0e", + "scale_data_dim": [815, 300], + "scale_data_sha256": "d96eb34645ca69fbdf812fd7518d8624a2671ca28c2622bdd9312cd46d4d6a5d", + "n_variable_features": 815, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay5", + "seed": 12345, + "optimizer": { + "nodes": 300, + "edges": 25060, + "max_modularity": "0.3263", + "communities": 2, + "singletons": 0, + "final_clusters": 2 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "1fbf20d4b21d1e1833c433257a88af9076e6a23ac3a2cb3b3ab615a1b2056676", + "RunUMAP": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindNeighbors": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindClusters": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "add_silhouette_to_metadata": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c" + }, + "rng_end_sha256": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "covariates": { + "percent_mt": { + "definition": "ids", + "file": "data/clustering/m15b/inputs/soupx_tenx_test/mt_genes.txt", + "sha256": "33fa18ada09c2dc5d375d3f16b658ac5ae7b6b85a8655be1da9db80a1e475184", + "features": ["Rpl5", "Rplp2", "Rpl13", "Rpsa", "Rpl26", "Rpl19", "Rpl17"], + "ids_not_found": ["NOT_A_FEATURE_1", "NOT_A_FEATURE_2"], + "cells_zero": 1 + } + }, + "regression": { + "vars": ["percent.mt", "nCount_RNA"], + "rank": 3, + "pivot": [1, 2, 3], + "n_columns": 3 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/soupx_tenx_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/soupx_tenx_test/ids_ncount/direct-portable-cascadelake.partial.62084556", + "level": "full", + "umap": true, + "assay": "v5", + "start_time": "2026-11-19T07:08:45-0500", + "slurm_job_id": "62084556", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22501.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084556", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22501", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.2029999999999994, + "peak_rss_kib": 707148, + "rss_kib": 707148 + }, + "covariates": { + "elapsed_s": 0.25399999999999956, + "peak_rss_kib": 707956, + "rss_kib": 707956 + }, + "SCTransform": { + "elapsed_s": 3.5869999999999997, + "peak_rss_kib": 862044, + "rss_kib": 862044 + }, + "RunPCA": { + "elapsed_s": 3.9320000000000004, + "peak_rss_kib": 869120, + "rss_kib": 869120 + }, + "RunUMAP": { + "elapsed_s": 6.786999999999999, + "peak_rss_kib": 869476, + "rss_kib": 857600 + }, + "FindNeighbors": { + "elapsed_s": 7.1759999999999984, + "peak_rss_kib": 869476, + "rss_kib": 860228 + }, + "FindClusters": { + "elapsed_s": 7.2429999999999986, + "peak_rss_kib": 869476, + "rss_kib": 860964 + }, + "silhouette": { + "elapsed_s": 7.5160000000000018, + "peak_rss_kib": 869476, + "rss_kib": 862736 + }, + "purity": { + "elapsed_s": 7.5360000000000014, + "peak_rss_kib": 869476, + "rss_kib": 862896 + }, + "chain_end": { + "elapsed_s": 7.5380000000000003, + "peak_rss_kib": 869476, + "rss_kib": 862896 + }, + "write": { + "elapsed_s": 8.5309999999999988, + "peak_rss_kib": 904104, + "rss_kib": 904104 + } + }, + "peak_rss_kib": 904104, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 300", "Number of edges: 25060", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.3263", "Number of communities: 2", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/metadata.tsv b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/metadata.tsv new file mode 100644 index 0000000..806280f --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/metadata.tsv @@ -0,0 +1,301 @@ +barcode score label +TTACCATCAAACTAGA-1 21 b +GGAGAACTCATCGCAA-1 33 b +GCTTTCGCACAAGCAG-1 40.627870454727031 a +CGGAGAAAGGCGTCCT-1 25 b +GGGTGAAGTAAGTTAG-1 0.043 a +TATTTCGCACCTATCC-1 38.566410425585644 a +ATGAGGGGTTATTCCT-1 12.8586 b +TTCCACGCATTGGCAT-1 0.039 a +GATCATGAGGCCCGTT-1 +19.9003841749945 b +ACCATTTCATACAGCT-1 +20.2391919716813 b +TGATGCAGTTTCGTTT-1 13.18627714354578 a +CACCGTTCATTCTCCG-1 -0.003 a +GAGCCTGCACGTGAGA-1 33.660328143597575 a +GTGGTTAAGGTAGCAC-1 3.1526e-01 a +CTCCGATGTACCCGAC-1 +45.4693180434466 b +GGAGGTAAGAGACAAG-1 35.1487 b +CTAGACATCACTCTTA-1 +4.32798746517727 b +GGCTGTGTCTCCGATC-1 21.33690906412339 a +CATCCCAGTTTCACTT-1 0.035 a +GCAGCCACAACGATTC-1 +29.4470787360493 b +AGAACCTTCGCTTGAA-1 +6.90706171825883 b +ATCCCTGGTGGGTTGA-1 +31.987166692618 b +TCGTGCTCAAAGTGTA-1 0.044 a +AAACGAAAGGATTCCT-1 18.231296661578646 a +TGCTTCGTCTTCCGTG-1 4.5873e+01 a +GACGTTAGTCATTCCC-1 5.8111e+00 a +TGCGGCAGTTGTGCCG-1 0.009 a +AGTACTGAGAAGTATC-1 5.7142e-01 a +ATTCATCGTGGCATCC-1 3.7100e+01 a +GGATCTACAGGCATGA-1 2 b +CCCGAAGGTAGCGATG-1 0.042 a +CATACTTCAAGCTCTA-1 3.3989e+01 a +TTTGTTGAGAGCAGTC-1 +26.547814939775 b +TATTTCGAGATCCAAA-1 +24.4134605190514 b +GTAACCAAGGTTCCGC-1 10.9594 b +GATGCTATCAACGAGG-1 16.8905 b +AGAGCCCAGCCGGATA-1 +31.2197581712656 b +CCCTTAGGTAGCCAGA-1 25.7721 b +GTCACGGAGTTGGAAT-1 +47.0797661876731 b +AATCACGGTGGACAGT-1 36 b +CGAGAAGCATTCATCT-1 29.137318321218501 a +GAGTGTTAGGACTGGT-1 15 b +AGGCCACCATGAAGGC-1 36.703 b +AACGTCATCGATACTG-1 39.913824500652744 a +CCAAGCGTCGAGAATA-1 0.034 a +CTAGACACACGGTGCT-1 0.027 a +TGATTCTTCCCATAAG-1 4.7759e+01 a +GGAGATGTCAGTGTGT-1 0.028 a +AAACGCTGTGACCGAA-1 0.180009 b +GATGCTATCGGTCACG-1 2.9636e+01 a +TGTAGACAGGCTAGCA-1 +30.2885787806451 b +TGGAACTGTACAGCGA-1 -2 b +TCATCATTCTCTATGT-1 9.5637e+00 a +TACATTCTCAGCATTG-1 37 b +GTGCTGGAGACTAGAT-1 28.704273856872256 a +TGTTTGTAGGCATGGT-1 18.0362 b +ACGTAGTCAGCTAACT-1 0.64937994207844385 a +CGTGATACATTGGATC-1 13.9588 b +ATTCCCGTCTAAGGAA-1 +40.9935985348677 b +TTAGGCAGTGAACTAA-1 +40.2043365972034 b +CATGCTCAGATAACAC-1 7.6577420473658826 a +TCAGTTTGTACCTGTA-1 9.3099789477051793 a +CATTCCGTCGTGGCGT-1 16.1613 b +TCCTAATTCCGCGAGT-1 26 b +CCGGTGAAGTGAGTGC-1 0.016 a +AGCCAGCTCTAACGCA-1 40.594595359488508 a +AAGACAACAGTCGCTG-1 4.1504e+01 a +AACCTTTCACGGGTAA-1 +28.9292076261955 b +GACGCTGTCACGACTA-1 18.1155 b +TTTAGTCTCTTTCTAG-1 7.61416 b +CAGTGCGTCCGGACTG-1 0.032 a +TGGGCGTGTAACCCTA-1 8.4239e+00 a +CAATACGGTAATTAGG-1 10.8559 b +AGGTTACCAATAGTAG-1 47.6927 b +CATTGTTAGCCAAGCA-1 2.7094e+01 a +AGGATAAAGCTCATAC-1 42.777090330432692 a +GCGAGAAAGCGTTACT-1 +43.3795670962553 b +AGCTTCCCAAGTGGAC-1 33 b +CTCAGTCCATCTGGGC-1 35.1613 b +TGGATGTTCCGAAGGA-1 +18.5763114555796 b +GGAGAACTCATACGGT-1 3.7763e+01 a +CATACTTCAGTCGCTG-1 23 b +TCAATTCCATTGCTGA-1 0.042 a +GATCATGAGGACAGCT-1 0.027 a +AGACCCGCAATTAGGA-1 11 b +TGCAGTATCTCAGTCC-1 7 b +TACCTGCTCTAAGCCA-1 +6.23122472289864 b +AATGACCAGTTCCAGT-1 0.010 a +CAGCACGAGTCATACC-1 6.68916 b +ACAAGCTGTCATTGCA-1 17.3444 b +ATCCATTCACTCTGCT-1 0.011 a +AGGTGTTTCGCCATAA-1 22.024772292469404 a +TGATGGTCAATCAAGA-1 18.2817 b +AACTTCTGTAGTAAGT-1 -2.20022 b +AGTGCCGGTCATGCAT-1 +35.9311476344898 b +GAGTCATTCAAGTTGC-1 1.8602e+01 a +CTCCAACTCGCCTATC-1 8 b +CATACCCGTCAGTCTA-1 38.8992 b +TCATTGTAGGCGACAT-1 41 b +AAGTCGTTCGGTGTAT-1 3.9002e+01 a +TGTAACGCACTCGATA-1 -0.003 a +TTCCGTGAGAGAACCC-1 +46.9220719513017 b +GCCATTCCAGGTCAAG-1 0.007 a +TACCCGTCATTGTAGC-1 0.043 a +GTTGTCCGTGTCACAT-1 1.2171e+01 a +AACCACACATAAGATG-1 0.001 a +GTTGTAGTCTAAGCGT-1 47.8098 b +GGAGGTACACCTGCTT-1 -1.3312e+00 a +TCCATCGTCGAGCCTG-1 +28.0528381703748 b +CTTCTCTAGGGCTGAT-1 0.027 a +GAGACTTGTGTAGTGG-1 +11.1656622997189 b +AGGACGAGTTCGGGTC-1 +39.8404052877348 b +TTCAATCCAATGGGTG-1 23.748735166003485 a +CCTGCATTCTCCTGAC-1 +19.897584105114 b +TAACGACGTGCGCTCA-1 12.929837605133532 a +GGGACAATCCCTTCCC-1 48.0653 b +AAGCGAGCACTACACA-1 0.041 a +CGCCAGACAAATGGAT-1 3.1268e+01 a +GGCTGTGAGCTCTGTA-1 +40.0599301992284 b +TCAATCTGTGCATTTG-1 16 b +AGGGTCCCAGCATCTA-1 26 b +ACCCTCATCAAGAGTA-1 42.873902264446812 a +GTTCCGTGTCGTCGGT-1 15.564638077769668 a +CCAATGACAATACCTG-1 +0.187477000975275 b +ACTTCCGAGTAGGCCA-1 14 b +TAACCAGTCATGCAGT-1 0.028 a +TTGTGGATCCTCAGAA-1 +6.61908013102621 b +GTGCACGTCAGGAAGC-1 +44.7766231697075 b +ACTGTCCTCCACTTTA-1 2.3229e+01 a +TAACGACAGAGGTTAT-1 +15.673407524675 b +TCACGGGCAGCCTTCT-1 +31.6170527275407 b +GTGAGCCCAACCGGAA-1 12.3052 b +GTGTCCTTCTGCAGCG-1 0.029 a +ACAGGGAGTCATGGCC-1 0.046 a +CGATGCGCAGGTGTGA-1 43.4995 b +ATCTCTAGTCAGACTT-1 31.586753763387328 a +AACACACCAGTCCGTG-1 20 b +GATGATCAGACGATAT-1 -1.71307883467425 a +ATGATCGGTTGCCGAC-1 8.1435e+00 a +TCTTCCTGTCTACATG-1 35.0345 b +GGAGGATCAGGCACTC-1 46.069740599600124 a +GAGGGTAGTGGATTTC-1 8.4262 b +TCAAGTGTCCGACGGT-1 1.2740e+01 a +TATACCTAGCCGGATA-1 19 b +TTCAATCTCAAGAGGC-1 26.7527 b +CGTCAAATCATGGGAG-1 40.806892635677947 a +GTACAGTCAACCTATG-1 0.008 a +ACCTGAATCACTAGCA-1 1.1639e+01 a +GAGACCCTCCCTCGAT-1 0.019 a +ACGTCCTTCACCATCC-1 1.2227e+01 a +TATATCCTCGACGATT-1 0.023 a +TCTTCCTGTTAGAGAT-1 8.9359e+00 a +TAATTCCGTCGTTCAA-1 -1.1351 b +CCGGACAAGGCACCAA-1 34 b +GTCGTTCTCGAGTACT-1 49.828764165019209 a +GGGATCCTCCCGAATA-1 39 b +TCATTGTGTCAAAGCG-1 0.042 a +TAGGTTGGTCTGTCCT-1 -1.9099e+00 a +TTCTCTCAGAGAAGGT-1 6.2681331773780755 a +TCGATTTAGGTCATAA-1 28.728540166392062 a +GGCACGTCAGCACCCA-1 0.049 a +GTCCACTTCTGAACGT-1 0.038 a +CATAAGCAGGCCCGTT-1 43.104748777146952 a +TCCTTCTCAAGTACCT-1 +18.1856183387505 b +CCAAGCGCATGGGATG-1 22 b +GTCATTTAGAGCAACC-1 35.245 b +AGAGCAGGTATTCCGA-1 0.017 a +CGTAATGGTCAACGCC-1 +12.8943911930476 b +AGGGCCTAGTTTGTCG-1 3.8880e+01 a +TGGGAGAGTCTGTCCT-1 39.4303 b +CTCAACCCAGATACTC-1 8.3912469682070405 a +ATCACGAAGCGTCAAG-1 2.7369e+01 a +ACGTAGTTCGCACTCT-1 44.2887 b +TGAGCATGTACTCCGG-1 2 b +GTGGAAGGTAGAGCTG-1 -1.01838 b +ACAGGGACAGCCTATA-1 0 b +CAAAGAAAGTCATCGT-1 42.386008928768703 a +CAGGTATTCCGGACTG-1 26 b +CAGTTAGCAAGGAGTC-1 +0.99035637438489 b +AGACACTCAAATAAGC-1 2.4142e+01 a +ACGGTTATCCGAACGC-1 +4.69179815014512 b +TGATCAGTCGAGTACT-1 +13.1421818586322 b +ACACAGTTCATGTCAG-1 -1.6899e+00 a +ATGGTTGCATACAGAA-1 27.24404254708789 a +CTCATGCTCACGATCA-1 4.6128e+01 a +TGATCAGCACACAGCC-1 0.045 a +TAGGTACAGAGATCGC-1 17.7348 b +AGGGTCCCATCCGATA-1 0.048 a +GTACAACAGGCATGCA-1 4.1539e+01 a +TCTACCGCACTGATTG-1 +47.8150940214022 b +AGCGTATTCAAGCTGT-1 4.1149e+01 a +CACAGATAGCGACTAG-1 47 b +CCCTAACGTTGCGAAG-1 13.894477111797933 a +GTGTAACCATCTTCGC-1 30 b +GTTCATTAGCCTCAGC-1 +15.0206909252023 b +CTCGAGGTCAAGTGTC-1 47.9988 b +TCCGAAATCTACTTCA-1 8.6232e+00 a +TTTGGTTAGCTCCGAC-1 0.021 a +AGTCTCCAGTTGCATC-1 0.034 a +AAGCGTTCAGACCTAT-1 +5.41810234020558 b +TGGATCAAGATGCTTC-1 0.044 a +AGAAGTAAGGTTACCT-1 48.9026 b +AGGGTGAAGCCTGAAG-1 +42.8587876262191 b +GAAGAATTCCGTACGG-1 +30.3457178462059 b +CACGTGGGTACAAGTA-1 +46.0632799921248 b +ACTGATGCAACTTGCA-1 27.2175 b +TCCCATGAGGGTTAAT-1 23.895065047141422 a +GAAGTAACACATTCTT-1 18.340774319170034 a +CCCGAAGCATTGCTTT-1 44 b +GCCAGTGAGTAGGTTA-1 2.6216e+01 a +CTCCTTTCAGGACAGT-1 14.925940909907517 a +TTTACGTGTGGTCTGC-1 -1.6202108369023027 a +ACTTCCGCAGAACCGA-1 0.020 a +ACTATTCAGATTGTGA-1 +28.3403597479975 b +GTCCACTCACTTTATC-1 3.3645e+01 a +TGCTTCGGTAGAGTTA-1 36.0241 b +CCACTTGAGTCACGAG-1 23.612723590729122 a +GCACATAGTCATAGTC-1 32 b +TGGCGTGGTCTGTTAG-1 5.4851276919573113 a +TTACCATAGTAAACGT-1 2.3041e+01 a +ACTATCTGTAGGCTCC-1 0.042 a +CTGAATGTCGGCTGTG-1 30 b +GCAGCCAAGCAAGCCA-1 0.020 a +CTAACTTCACGCCAGT-1 3.7112e+01 a +CGTAAGTGTAAGGCTG-1 -0.002 a +CCACTTGTCGTGGAAG-1 4.5093e+01 a +CCCTAACCAGGATGAC-1 +18.1237612420499 b +ATTCCATTCGTGACTA-1 0.040 a +TTACGCCCACGAGAAC-1 0.001 a +GTACAGTAGGGCAGAG-1 48 b +TTGATGGCACTACCCT-1 2.9627e+01 a +GGGACCTAGTCATCGT-1 2.2500e+00 a +ACTCTCGCAATCGCCG-1 1.9529952246361431 a +GCATCTCAGTAGCATA-1 12.535584984806723 a +TCGTAGATCGATTCCC-1 41 b +TACAACGCAACGCCCA-1 3.4097e+01 a +ATTCATCGTTATAGAG-1 49 b +TCAAGTGAGTGCTCAT-1 18.7316 b +TGTCCTGTCAACGAGG-1 48.912807210873289 a +TGGGCGTGTCCCGTGA-1 33 b +GGTTCTCTCCCAACTC-1 44.127031864762884 a +GTCCTCATCCGTTTCG-1 +34.8972476156045 b +GGAGCAAGTCTAGTGT-1 +11.7800901822273 b +TCCTCGATCACACGAT-1 0.009 a +AACAAAGGTAAGATTG-1 3.8995e+01 a +GTCAGCGGTCCATCTC-1 12.043035264039208 a +GGAAGTGTCGCCGAAC-1 10.7239 b +AAGTACCGTTTCGTAG-1 20.4177 b +TTTCGATCAATTCACG-1 1.1777e+00 a +AGCTTCCGTGTCATTG-1 0.040 a +GCCAGGTCACGGTGAA-1 10.5875 b +TTCACCGCAGACCAAG-1 3.1142e+01 a +TCCCATGGTATCAGCT-1 2.52676 b +GTGAGGAAGGTAGATT-1 1.2950e+01 a +CACAACATCGCCTAGG-1 3.0725e+01 a +CTACCTGGTCCCGGTA-1 15 b +ATCACTTTCTTCCTAA-1 12 b +CATGCGGCAATCTGCA-1 +22.0356244693723 b +TGCTCGTGTTCTCGTC-1 25.495831944675391 a +ACCTACCGTAGGCTGA-1 25.8248 b +TTGTGGATCATGGATC-1 0.006 a +ACTACGATCCTGGGAC-1 41 b +AAGGAATAGGCGAACT-1 6.2064163188574444 a +ATGCGATTCGGCCTTT-1 +9.1532311602776 b +ATAGGCTCACACCGCA-1 37.5351 b +TGCGGCATCTTACCGC-1 +38.590632990263 b +TCGGGCAGTTCCTTGC-1 4.1483e+00 a +CCGATCTCATCGAAGG-1 4.5408e+01 a +TAACACGGTAGAGGAA-1 30 b +TCATCATTCGGAACTT-1 16.7881 b +GTCCACTGTTCGATTG-1 9 b +GAGAAATCATAGATGA-1 -1 b +TTCAGGATCTATTGTC-1 29 b +TCTGTCGCAGAAGCGT-1 4.1169018882344171 a +CTCTGGTTCCTTCTGG-1 -6.9368e-01 a +TTGCATTTCACTGCTC-1 32 b +GTGCACGGTGATGAAT-1 0.029 a +ACAACCACAAGACAAT-1 37.29216609741578 a +CTCCACAGTCGACGCT-1 0.016 a +ACGGAAGCAGACCGCT-1 0.006 a +TCGGGACGTAACATAG-1 10.343 b +CAGAGCCTCCAAGCAT-1 36.713017349817669 a +AGAAGCGGTTTAAGGA-1 38.616038360258216 a +GGTGATTAGACCGTTT-1 +44.5796411599508 b +GTGCACGCAACCAACT-1 9 b +AGTAGCTGTACAAGTA-1 38 b +AGCGCTGAGGCCTAAG-1 30.1013 b +ATTACTCAGCAAACAT-1 29.7525 b +CAGCGTGCAGGTGAGT-1 6.3842e+00 a +ATGCATGAGAACAAGG-1 34 b +GCCAGTGGTATCGTGT-1 15 b +ATGCCTCTCCGACGGT-1 0.044 a +CCACTTGTCCACTTCG-1 30.3124 b +AAGCCATGTTATGACC-1 16 b +TTCTCTCGTACGGATG-1 26.9549 b +ACCTGTCTCCGTACGG-1 18 b +TTTGATCTCGTCTACC-1 47 b +TAGATCGCAATCACGT-1 7.9501325298243781 a +AGTTCCCTCGAAGAAT-1 45.274994805321008 a +AATGGCTCAACACGAG-1 +24.8094346819366 b diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/mt_genes.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/mt_genes.txt new file mode 100644 index 0000000..0a9628d --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/mt_genes.txt @@ -0,0 +1,12 @@ +# tier T has no mitochondrial gene: a stand-in set, the ribosomal protein genes (Rpl*, Rps*) +Rpl5 +Rplp2 +Rpl13 + +Rpsa +Rpl26 +Rpl19 +Rpl17 +Rpl5 +NOT_A_FEATURE_1 +NOT_A_FEATURE_2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/zero_genes.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/zero_genes.txt new file mode 100644 index 0000000..83cdb89 --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/inputs/zero_genes.txt @@ -0,0 +1,4 @@ +# three features with no counts in any cell: percent.mt is 0 in every cell +Gm17644 +Gm29663 +Gm28095 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/metadata.tsv.gz b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/metadata.tsv.gz new file mode 100644 index 0000000..d546c05 Binary files /dev/null and b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/seurat_clusters_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/seurat_clusters_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/summary.json b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/summary.json new file mode 100644 index 0000000..90405a6 --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/meta/summary.json @@ -0,0 +1,216 @@ +{ + "result": { + "level": "full", + "n_cells": 300, + "idents_equal_seurat_clusters": true, + "n_clusters": 3, + "cluster_sizes": [160, 119, 21], + "default_assay": "SCT", + "assays": { + "RNA": "Assay5", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 815, + "sct_nnz": 62883, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "8aa076bbd6ab1a3953d06b5fa51923796fc59bbc44a453c99c27bb404bd53009", + "sct_data_x_sha256": "0e0dd2af9f57ef300c2338af4454a9c8f2464aa9fc4b13b3b99e533d982c6a0e", + "scale_data_dim": [815, 300], + "scale_data_sha256": "5c32c8600a7495caae096c2567cf1810b8c2a5baebb29957a841c8045ca5c0de", + "n_variable_features": 815, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay5", + "seed": 12345, + "optimizer": { + "nodes": 300, + "edges": 23741, + "max_modularity": "0.3500", + "communities": 3, + "singletons": 0, + "final_clusters": 3 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "1fbf20d4b21d1e1833c433257a88af9076e6a23ac3a2cb3b3ab615a1b2056676", + "RunUMAP": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindNeighbors": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindClusters": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "add_silhouette_to_metadata": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c" + }, + "rng_end_sha256": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "covariates": { + "metadata": { + "file": "data/clustering/m15b/inputs/soupx_tenx_test/metadata.tsv", + "sha256": "5be8853f450116c33e51e4e29dfdd4fc4e87c7ebd5cacac2adeeb02aac68024c", + "columns": ["score", "label"], + "classes": { + "score": "numeric", + "label": "character" + } + } + }, + "regression": { + "vars": ["score"], + "rank": 2, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/soupx_tenx_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/soupx_tenx_test/meta/direct-portable-cascadelake.partial.62084557", + "level": "full", + "umap": true, + "assay": "v5", + "start_time": "2026-11-19T07:06:50-0500", + "slurm_job_id": "62084557", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22501.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084557", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22501", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.22199999999999953, + "peak_rss_kib": 707348, + "rss_kib": 707348 + }, + "covariates": { + "elapsed_s": 0.27499999999999858, + "peak_rss_kib": 707432, + "rss_kib": 707432 + }, + "SCTransform": { + "elapsed_s": 3.7009999999999987, + "peak_rss_kib": 863016, + "rss_kib": 863016 + }, + "RunPCA": { + "elapsed_s": 4.0709999999999997, + "peak_rss_kib": 875036, + "rss_kib": 874800 + }, + "RunUMAP": { + "elapsed_s": 6.8949999999999996, + "peak_rss_kib": 875204, + "rss_kib": 864760 + }, + "FindNeighbors": { + "elapsed_s": 7.2839999999999989, + "peak_rss_kib": 875204, + "rss_kib": 869472 + }, + "FindClusters": { + "elapsed_s": 7.343, + "peak_rss_kib": 875204, + "rss_kib": 869596 + }, + "silhouette": { + "elapsed_s": 7.6110000000000007, + "peak_rss_kib": 875204, + "rss_kib": 869756 + }, + "purity": { + "elapsed_s": 7.6310000000000002, + "peak_rss_kib": 875204, + "rss_kib": 869964 + }, + "chain_end": { + "elapsed_s": 7.6319999999999979, + "peak_rss_kib": 875204, + "rss_kib": 869964 + }, + "write": { + "elapsed_s": 8.629999999999999, + "peak_rss_kib": 905788, + "rss_kib": 905788 + } + }, + "peak_rss_kib": 905788, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 300", "Number of edges: 23741", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.3500", "Number of communities: 3", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/SCT_snn_res.0.8_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/SCT_snn_res.0.8_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/SCT_snn_res.0.8_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/metadata.tsv.gz b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/metadata.tsv.gz new file mode 100644 index 0000000..4316912 Binary files /dev/null and b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/metadata.tsv.gz differ diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/seurat_clusters_levels.txt b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/seurat_clusters_levels.txt new file mode 100644 index 0000000..4539bbf --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/seurat_clusters_levels.txt @@ -0,0 +1,3 @@ +0 +1 +2 diff --git a/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/summary.json b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/summary.json new file mode 100644 index 0000000..5f7548c --- /dev/null +++ b/tests/fixtures/clustering/m15b/soupx_tenx_test/pm/summary.json @@ -0,0 +1,213 @@ +{ + "result": { + "level": "full", + "n_cells": 300, + "idents_equal_seurat_clusters": true, + "n_clusters": 3, + "cluster_sizes": [165, 121, 14], + "default_assay": "SCT", + "assays": { + "RNA": "Assay5", + "SCT": "SCTAssay" + }, + "metadata_vst_attr_names": [], + "sct_n_features": 815, + "sct_nnz": 62883, + "sct_counts_integer": true, + "sct_counts_min": 1, + "sct_counts_explicit_zeros": 0, + "sct_data_is_log1p_counts": true, + "nCount_SCT_is_colSums": true, + "nFeature_SCT_is_nonzero": true, + "sct_counts_x_sha256": "8aa076bbd6ab1a3953d06b5fa51923796fc59bbc44a453c99c27bb404bd53009", + "sct_data_x_sha256": "0e0dd2af9f57ef300c2338af4454a9c8f2464aa9fc4b13b3b99e533d982c6a0e", + "scale_data_dim": [815, 300], + "scale_data_sha256": "350a833556f495698e7581461895d8f8a4fb515fed8c911b91c28a216cd66042", + "n_variable_features": 815, + "scale_data_rows_are_variable_features": true, + "scale_data_rows_in_variable_feature_order": false, + "sct_models": 1, + "model_feature_rows_are_sct_features": true, + "model_cell_rows_are_cells": true, + "rna_assay_class": "Assay5", + "seed": 12345, + "optimizer": { + "nodes": 300, + "edges": 24965, + "max_modularity": "0.3302", + "communities": 3, + "singletons": 0, + "final_clusters": 3 + }, + "rng_after": { + "SCTransform": "6fd1c4c8188e63e0021a0394257f98a380f221a09f7b10cbfaa5506bef06c840", + "RunPCA": "1fbf20d4b21d1e1833c433257a88af9076e6a23ac3a2cb3b3ab615a1b2056676", + "RunUMAP": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindNeighbors": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "FindClusters": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "add_silhouette_to_metadata": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c" + }, + "rng_end_sha256": "aa99171186dcbc77f7bb48e635ae53f80a51f648e05b228c589c27e07bd3618c", + "covariates": { + "percent_mt": { + "definition": "pattern", + "pattern": "(?i)^mt-", + "features": [], + "cells_zero": 300 + } + }, + "regression": { + "vars": ["percent.mt"], + "rank": 1, + "pivot": [1, 2], + "n_columns": 2 + } + }, + "run": { + "kind": "validation/R/reference_clustering.R", + "input": "data/clustering/soupx_tenx_test/input", + "input_source": "export", + "outdir": "data/clustering/m15b/runs/soupx_tenx_test/pm/direct-portable-cascadelake.partial.62084541", + "level": "full", + "umap": true, + "assay": "v5", + "start_time": "2026-11-19T07:08:54-0500", + "slurm_job_id": "62084541", + "profile": "portable", + "fingerprint": { + "scrust_version": "0.1.0", + "host": "holy7c22503.rc.fas.harvard.edu", + "kernel": "4.18.0-553.155.1.el8_10.x86_64", + "cpu_model": "Intel(R) Xeon(R) Platinum 8268 CPU @ 2.90GHz", + "cpu_flags": ["avx2", "fma", "avx512f", "avx512bw"], + "glibc": "2.28", + "openblas_corename": "Haswell", + "openblas_config": "OpenBLAS 0.3.34 DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=128", + "openblas_num_threads": 1, + "openblas_library": "/n/holylfs05/LABS/informatics/Lab/projects/afreedman/scRust/.envs/rust-dev/lib/libopenblasp-r0.3.34.so", + "OPENBLAS_CORETYPE": "Haswell", + "OPENBLAS_NUM_THREADS": "1", + "OMP_NUM_THREADS": null, + "SLURM_JOB_ID": "62084541", + "SLURM_JOB_PARTITION": "shared", + "SLURMD_NODENAME": "holy7c22503", + "SLURM_CPUS_PER_TASK": "1", + "R": "R version 4.5.3 (2026-03-11)", + "platform": "x86_64-conda-linux-gnu", + "packages": { + "Seurat": { + "version": "5.5.1" + }, + "SeuratObject": { + "version": "5.4.0" + }, + "sctransform": { + "version": "0.4.3" + }, + "glmGamPoi": { + "version": "1.22.0" + }, + "irlba": { + "version": "2.4.1" + }, + "uwot": { + "version": "0.2.5" + }, + "RcppAnnoy": { + "version": "0.0.23" + }, + "RcppEigen": { + "version": "0.3.4.0.2" + }, + "bluster": { + "version": "1.20.0" + }, + "BiocNeighbors": { + "version": "2.4.0" + }, + "assorthead": { + "version": "1.4.0" + }, + "Matrix": { + "version": "1.7-6" + }, + "future": { + "version": "1.82.0" + }, + "future.apply": { + "version": "1.21.0" + }, + "Rcpp": { + "version": "1.1.2" + } + }, + "blas_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_library": "/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_/lib/libopenblasp-r0.3.34.so", + "lapack_version": "3.12.0", + "blas_md5": "d77a762c672e6e8c39a458506f73cfd1", + "rng_kind": ["Mersenne-Twister", "Inversion", "Rejection"], + "locale": "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=en_US.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.UTF-8;LC_IDENTIFICATION=C", + "sizeof_longdouble": 16 + }, + "phases": { + "load": { + "elapsed_s": 0.2029999999999994, + "peak_rss_kib": 707040, + "rss_kib": 707040 + }, + "covariates": { + "elapsed_s": 0.24399999999999977, + "peak_rss_kib": 708304, + "rss_kib": 708304 + }, + "SCTransform": { + "elapsed_s": 3.7119999999999997, + "peak_rss_kib": 862096, + "rss_kib": 862096 + }, + "RunPCA": { + "elapsed_s": 4.0419999999999998, + "peak_rss_kib": 872016, + "rss_kib": 872016 + }, + "RunUMAP": { + "elapsed_s": 6.7589999999999986, + "peak_rss_kib": 872284, + "rss_kib": 861788 + }, + "FindNeighbors": { + "elapsed_s": 7.141, + "peak_rss_kib": 872284, + "rss_kib": 865480 + }, + "FindClusters": { + "elapsed_s": 7.1989999999999998, + "peak_rss_kib": 872284, + "rss_kib": 865584 + }, + "silhouette": { + "elapsed_s": 7.4900000000000002, + "peak_rss_kib": 872284, + "rss_kib": 865744 + }, + "purity": { + "elapsed_s": 7.5080000000000009, + "peak_rss_kib": 872284, + "rss_kib": 865932 + }, + "chain_end": { + "elapsed_s": 7.5099999999999998, + "peak_rss_kib": 872284, + "rss_kib": 865932 + }, + "write": { + "elapsed_s": 8.4330000000000016, + "peak_rss_kib": 904176, + "rss_kib": 904176 + } + }, + "peak_rss_kib": 904176, + "printed": ["Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck", "", "Number of nodes: 300", "Number of edges: 24965", "", "Running Louvain algorithm...", "Maximum modularity in 10 random starts: 0.3302", "Number of communities: 3", "Elapsed time: 0 seconds"], + "messages": [] + } +} diff --git a/tests/fixtures/clustering/percent_mt/expected.tsv b/tests/fixtures/clustering/percent_mt/expected.tsv new file mode 100644 index 0000000..f365108 --- /dev/null +++ b/tests/fixtures/clustering/percent_mt/expected.tsv @@ -0,0 +1,7 @@ +# counts definition features (Seurat's names) percent.mt per cell +integer pattern mt-Co1,MT-ND2,Mt-Atp6,mT-Cytb,mt-Zero,MT- 40411af286bca1af,4037cf3cf3cf3cf3,4045400000000000,4040aaaaaaaaaaaa,403b45d1745d1745,40424aed44aed44b,0000000000000000 +integer list MT-ND2,Mt-Atp6,mT-Cytb,mt-Zero 40250d79435e50d7,40230c30c30c30c3,4034000000000000,4034d55555555556,402e4d9364d9364e,403ad44aed44aed5,0000000000000000 +integer nCount_RNA - 4043000000000000,4045000000000000,4044000000000000,4048000000000000,4040800000000000,4044800000000000,4022000000000000 +real pattern mt-Co1,MT-ND2,Mt-Atp6,mT-Cytb,mt-Zero,MT- 4041388d12d9b0f2,40389e6581f3bad7,40454cea30371a66,4040dbb574b86602,403c1bacf914c1bb,404226c5462111ab,0000000000000000 +real list MT-ND2,Mt-Atp6,mT-Cytb,mt-Zero 40283a6013755bd1,40232c0f9dd6ba48,40334852a79afa41,403512a2d1e67f82,4030c1bacf914c1c,403b2be6e9c3903e,0000000000000000 +real nCount_RNA - 40450ccccccccccd,4046f33333333334,40464cccccccccce,404a19999999999a,4042800000000000,4046733333333334,4022666666666666 diff --git a/tests/fixtures/clustering/percent_mt/integer/barcodes.tsv.gz b/tests/fixtures/clustering/percent_mt/integer/barcodes.tsv.gz new file mode 100644 index 0000000..735ea78 Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/integer/barcodes.tsv.gz differ diff --git a/tests/fixtures/clustering/percent_mt/integer/features.tsv.gz b/tests/fixtures/clustering/percent_mt/integer/features.tsv.gz new file mode 100644 index 0000000..18adc8f Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/integer/features.tsv.gz differ diff --git a/tests/fixtures/clustering/percent_mt/integer/matrix.mtx.gz b/tests/fixtures/clustering/percent_mt/integer/matrix.mtx.gz new file mode 100644 index 0000000..c03833b Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/integer/matrix.mtx.gz differ diff --git a/tests/fixtures/clustering/percent_mt/make_unique.tsv b/tests/fixtures/clustering/percent_mt/make_unique.tsv new file mode 100644 index 0000000..e9e7141 --- /dev/null +++ b/tests/fixtures/clustering/percent_mt/make_unique.tsv @@ -0,0 +1,6 @@ +# names make.unique(names) +a,a,b,a,a.1,b a,a.2,b,a.3,a.1,b.1 +a,a.1,a a,a.1,a.2 +x,x,x.1,x.1,x x,x.2,x.1,x.1.1,x.3 +g,g.2,g,g,g.1 g,g.2,g.3,g.4,g.1 +mt,mt,mt.1,MT,mt mt,mt.2,mt.1,MT,mt.3 diff --git a/tests/fixtures/clustering/percent_mt/mt_genes.txt b/tests/fixtures/clustering/percent_mt/mt_genes.txt new file mode 100644 index 0000000..d4223b3 --- /dev/null +++ b/tests/fixtures/clustering/percent_mt/mt_genes.txt @@ -0,0 +1,10 @@ +# an ID list: ID03 and ID04 (renamed by Seurat), ID11 (no counts), ID02 twice, +# two IDs not among the features, and a blank line +ID03 +ID04 + +ID11 +ID02 +ID02 +NOPE1 +NOPE2 diff --git a/tests/fixtures/clustering/percent_mt/real/barcodes.tsv.gz b/tests/fixtures/clustering/percent_mt/real/barcodes.tsv.gz new file mode 100644 index 0000000..735ea78 Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/real/barcodes.tsv.gz differ diff --git a/tests/fixtures/clustering/percent_mt/real/features.tsv.gz b/tests/fixtures/clustering/percent_mt/real/features.tsv.gz new file mode 100644 index 0000000..18adc8f Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/real/features.tsv.gz differ diff --git a/tests/fixtures/clustering/percent_mt/real/matrix.mtx.gz b/tests/fixtures/clustering/percent_mt/real/matrix.mtx.gz new file mode 100644 index 0000000..5436562 Binary files /dev/null and b/tests/fixtures/clustering/percent_mt/real/matrix.mtx.gz differ diff --git a/tests/fixtures/clustering/percent_mt/seurat_names.txt b/tests/fixtures/clustering/percent_mt/seurat_names.txt new file mode 100644 index 0000000..9a979c1 --- /dev/null +++ b/tests/fixtures/clustering/percent_mt/seurat_names.txt @@ -0,0 +1,14 @@ +mt-Co1 +MT-ND2 +Mt-Atp6 +mT-Cytb +Mtor +xmt-a +mt +mt.1 +Gene-1 +Gene-1.1 +mt-Zero +Actb +mtx-1 +MT- diff --git a/tests/fixtures/kernels.tsv b/tests/fixtures/kernels.tsv index befbba8..e7c7ed6 100644 --- a/tests/fixtures/kernels.tsv +++ b/tests/fixtures/kernels.tsv @@ -23,3 +23,5 @@ clustering/soupx_emptydrops_test/saved SapphireRapids the saved object's workflo clustering/decontx_raw_tenx_test/saved SapphireRapids the saved object's workflow job (Sapphire Rapids, kernel detected; docs/validation/clustering_m8.md) clustering/decontx_raw_emptydrops_test/saved SapphireRapids the saved object's workflow job (Sapphire Rapids, kernel detected; docs/validation/clustering_m8.md) clustering/cellbender_fromraw_test/saved SapphireRapids the saved object's workflow job (Sapphire Rapids, kernel detected; docs/validation/clustering_m8.md) +rcompat/linpack_qr.tsv.gz Haswell validation/manifest.toml: profile portable (OPENBLAS_CORETYPE=Haswell), validation/R/regress_vectors.R (M15b) +rcompat/linpack_resid.tsv.gz Haswell validation/manifest.toml: profile portable (OPENBLAS_CORETYPE=Haswell), validation/R/regress_vectors.R (M15b) diff --git a/tests/fixtures/rcompat/linpack_qr.tsv.gz b/tests/fixtures/rcompat/linpack_qr.tsv.gz new file mode 100644 index 0000000..f9e65b0 Binary files /dev/null and b/tests/fixtures/rcompat/linpack_qr.tsv.gz differ diff --git a/tests/fixtures/rcompat/linpack_resid.tsv.gz b/tests/fixtures/rcompat/linpack_resid.tsv.gz new file mode 100644 index 0000000..2840265 Binary files /dev/null and b/tests/fixtures/rcompat/linpack_resid.tsv.gz differ diff --git a/validation/R/export_percent_mt.R b/validation/R/export_percent_mt.R new file mode 100644 index 0000000..b853218 --- /dev/null +++ b/validation/R/export_percent_mt.R @@ -0,0 +1,57 @@ +# Milestone M15b: percent.mt as the production run saved it (docs/PLAN.md C5's M15b row). Reads one +# saved workflow object (.rds) and writes its cells' percent.mt, with nCount_RNA and nFeature_RNA, +# as %.17g text, for comparison with scrust's percent.mt computed by the workflow's pattern. Every +# workflow script computes it before SCTransform: +# obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = "(?i)^mt-") +# The script also computes it again on the saved object's RNA counts (the same call) and records +# whether that gives the saved column bit for bit, which features the pattern matches (Seurat's row +# names), and the counts' digest against an export of the same counts when one is given. Reading a +# saved object is not a new R run of the workflow. Run through validation/slurm/m15b_saved.sbatch +# (it reads .rds files): +# Rscript validation/R/export_percent_mt.R --rds --out [--counts-from <10x dir>] +# Output: /percent_mt.tsv (barcode, nCount_RNA, nFeature_RNA, percent.mt) and +# /percent_mt.json. + +args0 <- commandArgs(trailingOnly = FALSE) +here <- dirname(normalizePath(sub("^--file=", "", grep("^--file=", args0, value = TRUE)))) +source(file.path(here, "lib", "io.R")) +source(file.path(here, "lib", "doubletfinder.R")) # df_args + +args <- df_args(list(rds = NULL, out = NULL, `counts-from` = "")) +suppressPackageStartupMessages({ + library("Seurat") + library("Matrix") +}) +dir.create(args$out, recursive = TRUE, showWarnings = FALSE) +o <- readRDS(args$rds) +md <- o@meta.data +if (!"percent.mt" %in% colnames(md)) stop(args$rds, ": no percent.mt column") +if (!identical(rownames(md), colnames(o))) stop("meta.data rows differ from the cells") +tsv_write(data.frame(barcode = colnames(o), nCount_RNA = md$nCount_RNA, nFeature_RNA = md$nFeature_RNA, + percent.mt = md$percent.mt, stringsAsFactors = FALSE, check.names = FALSE), + file.path(args$out, "percent_mt.tsv")) +again <- unname(PercentageFeatureSet(o, pattern = "(?i)^mt-", assay = "RNA")) +features <- grep("(?i)^mt-", rownames(o[["RNA"]]), value = TRUE) +facts <- list( + rds = args$rds, + n_cells = ncol(o), + rna_assay_class = class(o[["RNA"]])[1], + default_assay = DefaultAssay(o), + percent_mt_class = class(md$percent.mt)[1], + recomputed_identical = identical(again, unname(md$percent.mt)), + pattern = "(?i)^mt-", + n_features = length(features), + features = I(features), + cells_zero = sum(md$percent.mt == 0), + cells_nan = sum(is.nan(md$percent.mt)), + max = if (ncol(o)) max(md$percent.mt) else NA +) +if (nzchar(args$`counts-from`)) { + cnt <- LayerData(o, assay = "RNA", layer = "counts") + ex <- mtx_read_10x(args$`counts-from`) + facts$counts_from <- args$`counts-from` + facts$counts_identical_to_export <- identical(unname(cnt), unname(ex)) && identical(colnames(cnt), colnames(ex)) +} +json_write(facts, file.path(args$out, "percent_mt.json")) +cat(args$rds, ":", ncol(o), "cells,", length(features), "features match the pattern; recomputed identical:", + facts$recomputed_identical, "\n") diff --git a/validation/R/lib/clustering.R b/validation/R/lib/clustering.R index a1bb98e..fb19a8b 100644 --- a/validation/R/lib/clustering.R +++ b/validation/R/lib/clustering.R @@ -15,7 +15,8 @@ # # The chain's input is the object's RNA counts layer as saved (C1). The scripts' other work # (reading 10x files, emptyDrops, SoupX, decontX, DoubletFinder, scDblFinder, subset(), -# percent.mt) is not part of the chain and is not run: SCTransform reads only the counts and the +# percent.mt) is not part of the chain and is not run, except, for milestone M15b's runs with +# vars.to.regress (cl_covariates below), percent.mt as the scripts compute it before SCTransform: SCTransform reads only the counts and the # cell names (Seurat passes meta.data to vst() as cell_attr, which uses only the columns umi, # gene, log_umi, log_gene, umi_per_gene and log_umi_per_gene if present; export_clustering.R # checks that no saved object has them), and every later step reads only what the chain made. @@ -174,6 +175,58 @@ cl_load_input <- function(input, assay = c("v5", "v3")) { list(seurat = seu, source = if (grepl("\\.rds$", input)) "rds" else "export") } +# Milestone M15b: the covariates of SCTransform's vars.to.regress, made on the object before the +# chain. percent.mt as every workflow script computes it before SCTransform (pipeline repo, +# workflow/scripts/*.R at ea053fa: seurat_obj[["percent.mt"]] <- PercentageFeatureSet(seurat_obj, +# pattern = "(?i)^mt-")), or with the features a file of ids names (one per line, blank lines and +# lines starting with # skipped, each line trimmed; matched against column 1 of the input's +# features.tsv.gz, taken in the counts' row order); a table's columns (`metadata`: a TSV with a +# barcode column) added with AddMetaData(), its numbers read by read.delim() (R_strtod). Returns +# the object and what was done, for summary.json. +cl_covariates <- function(seu, input, percent_mt = FALSE, mt_genes = "", metadata = "") { + info <- list() + if (percent_mt || nzchar(mt_genes)) { + if (!nzchar(mt_genes)) { + seu[["percent.mt"]] <- PercentageFeatureSet(seu, pattern = "(?i)^mt-") + info$percent_mt <- list(definition = "pattern", pattern = "(?i)^mt-", + features = I(grep("(?i)^mt-", rownames(seu), value = TRUE))) + } else { + ids <- trimws(readLines(mt_genes, warn = FALSE)) + ids <- ids[nzchar(ids) & !startsWith(ids, "#")] + feat <- read.delim(file.path(input, "features.tsv.gz"), header = FALSE, colClasses = "character", + quote = "", comment.char = "") + if (nrow(feat) != nrow(seu)) stop("features.tsv.gz does not have one line per row of the counts") + listed <- rownames(seu)[feat[[1]] %in% ids] + if (!length(listed)) stop("none of the ids in ", mt_genes, " is among the features") + seu[["percent.mt"]] <- PercentageFeatureSet(seu, features = listed) + info$percent_mt <- list(definition = "ids", file = mt_genes, sha256 = sha256_file(mt_genes), + features = I(listed), ids_not_found = I(unique(setdiff(ids, feat[[1]])))) + } + info$percent_mt$cells_zero <- sum(seu$percent.mt == 0) + } + if (nzchar(metadata)) { + md <- read.delim(metadata, check.names = FALSE, stringsAsFactors = FALSE) + bc <- if ("barcode" %in% names(md)) "barcode" else names(md)[1] + rownames(md) <- md[[bc]] + cols <- setdiff(names(md), bc) + seu <- AddMetaData(seu, md[colnames(seu), cols, drop = FALSE]) + info$metadata <- list(file = metadata, sha256 = sha256_file(metadata), columns = I(cols), + classes = as.list(vapply(md[cols], function(x) class(x)[1], ""))) + } + list(seurat = seu, info = info) +} + +# The QR RegressOutMatrix() takes, made again from the object's metadata for the record (M15b): +# lm(GENE ~ vars, qr = TRUE)$qr's rank and pivot (the response does not change the QR). +cl_regression_qr <- function(seu, vars) { + latent <- seu@meta.data[, vars, drop = FALSE] + fmla <- as.formula(paste("GENE ~", paste(vars, collapse = "+"))) + m <- cbind(latent, GENE = 0) + colnames(m) <- c(vars, "GENE") + qr <- lm(fmla, data = m, qr = TRUE)$qr + list(vars = I(vars), rank = qr$rank, pivot = I(qr$pivot), n_columns = ncol(qr$qr)) +} + cl_rng_digest <- function() { s <- rng_state() if (is.null(s)) return("none") @@ -184,10 +237,11 @@ cl_rng_digest <- function() { # changes nothing downstream). mark(name) is called after each step. FindClusters' printed # output (the modularity optimizer's numbers) and its messages (GroupSingletons) are captured # and still printed. Returns the object and what the steps printed, with a digest of R's -# .Random.seed after each step. -cl_chain <- function(seu, umap = TRUE, mark = function(name) invisible(NULL)) { +# .Random.seed after each step. `vars.to.regress` (M15b) goes to SCTransform as the workflow's +# scripts passed it before their commit 8d34de1 (NULL, the default, is the call as it is now). +cl_chain <- function(seu, umap = TRUE, mark = function(name) invisible(NULL), vars.to.regress = NULL) { rng <- list() - seu <- SCTransform(seu, seed.use = WORKFLOW_SEED, verbose = FALSE) + seu <- SCTransform(seu, vars.to.regress = vars.to.regress, seed.use = WORKFLOW_SEED, verbose = FALSE) rng$SCTransform <- cl_rng_digest() mark("SCTransform") require_min_cells_for_pca(seu, context = "reference_clustering") @@ -324,17 +378,20 @@ cl_check_names <- function(seu) { # %.17g; rows and columns are the cells), graphs/graphs.json # Returns the facts for object.json: dimensions, checks and digests. cl_write_object <- function(seu, dir, level = c("full", "standard", "light", "labels"), - software = "scRust validation/R/lib/clustering.R") { + software = "scRust validation/R/lib/clustering.R", extra = character()) { level <- match.arg(level) cl_check_names(seu) dir.create(dir, recursive = TRUE, showWarnings = FALSE) cells <- colnames(seu) md <- seu@meta.data facts <- list(level = level, n_cells = length(cells)) - missing <- setdiff(CL_META, colnames(md)) + missing <- setdiff(c(CL_META, extra), colnames(md)) if (length(missing)) stop("metadata columns missing: ", paste(missing, collapse = ", ")) meta <- data.frame(barcode = cells, stringsAsFactors = FALSE) - for (col in CL_META) meta[[col]] <- md[[col]] + # M15b: percent.mt after the counts' columns, the other extra columns (a table's) at the end, as + # scrust cluster's metadata.tsv orders them + cols <- c(CL_META[1:2], intersect(extra, "percent.mt"), CL_META[-(1:2)], setdiff(extra, "percent.mt")) + for (col in cols) meta[[col]] <- md[[col]] tsv_write(meta, file.path(dir, "metadata.tsv")) for (col in c("seurat_clusters", "SCT_snn_res.0.8")) { if (!is.factor(md[[col]])) stop(col, " is not a factor") @@ -469,6 +526,13 @@ CL_PACKAGES <- c("Seurat", "SeuratObject", "sctransform", "glmGamPoi", "irlba", # (timings, peak RSS after each step, current RSS, fingerprint). cl_main <- function(args, kind, hooks = NULL) { umap <- switch(args$umap, yes = TRUE, no = FALSE, stop("--umap must be yes or no")) + # M15b: vars.to.regress and its covariates (empty: the chain as the workflow runs it now) + opt <- function(x) if (is.null(x)) "" else x + vars <- strsplit(opt(args$vars_to_regress), ",", fixed = TRUE)[[1]] + vars <- trimws(vars[nzchar(trimws(vars))]) + percent_mt <- identical(opt(args$percent_mt), "yes") || "percent.mt" %in% vars + mt_genes <- opt(args$mt_genes) + metadata <- opt(args$metadata) assay <- if (identical(args$assay, "auto")) readLines(file.path(args$input, "assay.txt")) else args$assay dir.create(args$out, recursive = TRUE, showWarnings = FALSE) cl_setup() @@ -482,6 +546,16 @@ cl_main <- function(args, kind, hooks = NULL) { inp <- cl_load_input(args$input, assay) mark("load") seu <- inp$seurat + covariates <- NULL + extra <- character() + if (percent_mt || nzchar(mt_genes) || nzchar(metadata) || length(vars)) { + cv <- cl_covariates(seu, args$input, percent_mt = percent_mt, mt_genes = mt_genes, metadata = metadata) + seu <- cv$seurat + covariates <- cv$info + extra <- c(if ("percent.mt" %in% colnames(seu@meta.data)) "percent.mt", + intersect(vars, setdiff(colnames(seu@meta.data), c(CL_META, "percent.mt", "orig.ident")))) + mark("covariates") + } run_info <- list(kind = kind, input = args$input, input_source = inp$source, outdir = args$out, level = args$level, umap = umap, assay = assay, start_time = format(Sys.time(), "%Y-%m-%dT%H:%M:%S%z"), @@ -489,13 +563,13 @@ cl_main <- function(args, kind, hooks = NULL) { fingerprint = fingerprint(packages = CL_PACKAGES)) rm(inp) if (!is.null(hooks)) hooks$install(seu) - res <- cl_chain(seu, umap = umap, mark = mark) + res <- cl_chain(seu, umap = umap, mark = mark, vars.to.regress = if (length(vars)) vars else NULL) rm(seu) seu <- res$seurat mark("chain_end") if (!is.null(hooks)) hooks$finish(seu, umap) write_cluster_metadata(seu, file.path(args$out, "nclusters.txt"), file.path(args$out, "cluster_ids.txt")) - facts <- cl_write_object(seu, args$out, args$level, software = paste0("scRust ", kind)) + facts <- cl_write_object(seu, args$out, args$level, software = paste0("scRust ", kind), extra = extra) mark("write") result <- c(facts, list( rna_assay_class = class(seu[["RNA"]])[1], @@ -503,6 +577,10 @@ cl_main <- function(args, kind, hooks = NULL) { optimizer = cl_parse_printed(res$printed, res$messages), rng_after = res$rng, rng_end_sha256 = cl_rng_digest())) + if (!is.null(covariates)) { + result$covariates <- covariates + if (length(vars)) result$regression <- cl_regression_qr(seu, vars) + } json_write(list(result = result, run = c(run_info, list(phases = phases, peak_rss_kib = peak_rss_kib(), printed = I(res$printed), messages = I(res$messages)))), diff --git a/validation/R/loader_compare.R b/validation/R/loader_compare.R index 4886e1b..13680dd 100644 --- a/validation/R/loader_compare.R +++ b/validation/R/loader_compare.R @@ -88,7 +88,7 @@ add_whole <- function(loader, component, ident, prefixes) { CHAIN <- c("nCount_RNA", "nFeature_RNA", "nCount_SCT", "nFeature_SCT", "SCT_snn_res.0.8", "seurat_clusters", "silhouette_width", "neighborhood_purity") COL_FLOOR <- c(silhouette_width = "K8_silhouette_width", neighborhood_purity = "K9_purity") -COL_BLAS_FREE <- c("nCount_RNA", "nFeature_RNA") +COL_BLAS_FREE <- c("nCount_RNA", "nFeature_RNA", "percent.mt") # The metadata columns, the identities ----------------------------------------------------------- cmp_column <- function(L, col, a, b) { @@ -154,6 +154,11 @@ cmp_seurat <- function(obj, o) { } add(L, "metadata orig.ident", identical(obj$orig.ident, o$orig.ident), blas = FALSE) for (col in CHAIN) cmp_column(L, col, obj@meta.data[[col]], o@meta.data[[col]]) + # M15b: percent.mt, when the export computed it (scrust's --percent-mt, --mt-genes or + # --vars-to-regress percent.mt); otherwise it is one of the columns not rebuilt + if ("percent.mt" %in% colnames(obj@meta.data) && "percent.mt" %in% colnames(o@meta.data)) { + cmp_column(L, "percent.mt", obj@meta.data[["percent.mt"]], o@meta.data[["percent.mt"]]) + } add(L, "identities (active.ident)", identical(obj@active.ident, o@active.ident)) add(L, "default assay", identical(DefaultAssay(obj), DefaultAssay(o)), blas = FALSE) s1 <- obj[["SCT"]]; s2 <- o[["SCT"]] @@ -228,6 +233,9 @@ cmp_sce <- function(sce, o) { cd <- as.data.frame(colData(sce)) add(L, "colData rows (cells)", identical(rownames(cd), colnames(o)), blas = FALSE) for (col in CHAIN) cmp_column(L, col, cd[[col]], o@meta.data[[col]]) + if ("percent.mt" %in% colnames(cd) && "percent.mt" %in% colnames(o@meta.data)) { + cmp_column(L, "percent.mt", cd[["percent.mt"]], o@meta.data[["percent.mt"]]) + } sct <- altExp(sce, "SCT"); s2 <- o[["SCT"]] a <- assay(sct, "corrected_counts"); add(L, "altExp SCT corrected_counts", identical(a, s2@counts), ld_sparse_stats(a, s2@counts)) a <- assay(sct, "logcounts"); add(L, "altExp SCT logcounts", identical(a, s2@data), ld_sparse_stats(a, s2@data)) diff --git a/validation/R/percent_mt_sct.R b/validation/R/percent_mt_sct.R new file mode 100644 index 0000000..34ca79f --- /dev/null +++ b/validation/R/percent_mt_sct.R @@ -0,0 +1,47 @@ +# Milestone M15b: how doubletfinder.R made its saved percent.mt. The script subsets its input object +# (a clustered object whose default assay is SCT) to the singlets and calls +# PercentageFeatureSet(seurat_singlets, pattern = "(?i)^mt-") with no assay, so the default +# assay's: the SCT assay's counts layer (the corrected counts) over nCount_SCT, not the RNA counts +# over nCount_RNA. This script computes both on the saved input object, takes the singlets (the +# saved DoubletFinder object's cells, from validation/R/export_percent_mt.R's percent_mt.tsv) and +# compares each with the saved column as %.17g text (so bit for bit). With --rust, also with +# scrust's percent.mt of the same singlets (validation/slurm/m15b_saved_rust.sbatch's re-clustering, +# its metadata.tsv), so the RNA-based value R computes is checked against scrust's. Reads .rds +# files; not a new R run of the workflow. Through validation/slurm/m15b_percent_mt_sct.sbatch: +# Rscript validation/R/percent_mt_sct.R --rds --saved --out +# [--rust ] + +args0 <- commandArgs(trailingOnly = FALSE) +here <- dirname(normalizePath(sub("^--file=", "", grep("^--file=", args0, value = TRUE)))) +source(file.path(here, "lib", "io.R")) +source(file.path(here, "lib", "doubletfinder.R")) # df_args + +args <- df_args(list(rds = NULL, saved = NULL, out = NULL, rust = NULL)) +suppressPackageStartupMessages(library("Seurat")) +o <- readRDS(args$rds) +saved <- read.delim(args$saved, colClasses = "character") +cells <- saved$barcode +if (!all(cells %in% colnames(o))) stop("the saved object's cells are not all the input's") +res <- list(rds = args$rds, saved = args$saved, n_cells = length(cells), default_assay = DefaultAssay(o)) +rust <- NULL +if (!is.null(args$rust)) { + rust <- read.delim(args$rust, colClasses = "character") + if (!identical(rust$barcode, cells)) stop("scrust's cells are not the saved object's, in order") + res$rust <- args$rust +} +for (assay in c("SCT", "RNA")) { + pm <- PercentageFeatureSet(o, pattern = "(?i)^mt-", assay = assay) + txt <- fmt17(unname(pm[cells])) + res[[assay]] <- list(n_features = length(grep("(?i)^mt-", rownames(o[[assay]]))), + identical_to_saved = identical(txt, saved$percent.mt), + differing = sum(txt != saved$percent.mt)) + if (!is.null(rust)) { + res[[assay]]$identical_to_scrust <- identical(txt, rust$percent.mt) + res[[assay]]$differing_from_scrust <- sum(txt != rust$percent.mt) + } +} +json_write(res, args$out) +cat(args$rds, ": default assay", res$default_assay, "; SCT identical", res$SCT$identical_to_saved, "(", res$SCT$differing, + "differ ); RNA identical", res$RNA$identical_to_saved, "(", res$RNA$differing, "differ )", + if (!is.null(rust)) paste("; scrust: RNA identical", res$RNA$identical_to_scrust, "(", res$RNA$differing_from_scrust, "differ ), SCT identical", + res$SCT$identical_to_scrust, "(", res$SCT$differing_from_scrust, "differ )"), "\n") diff --git a/validation/R/reference_clustering.R b/validation/R/reference_clustering.R index 743edba..625f7fe 100644 --- a/validation/R/reference_clustering.R +++ b/validation/R/reference_clustering.R @@ -6,7 +6,12 @@ # validation/slurm/reference_clustering.sbatch. # # Rscript validation/R/reference_clustering.R --input --out \ -# --level full|standard|light --umap yes|no --assay auto|v5|v3 +# --level full|standard|light --umap yes|no --assay auto|v5|v3 \ +# [--vars-to-regress ] [--percent-mt yes|no] [--mt-genes ] [--metadata ] +# +# M15b: --vars-to-regress passes SCTransform(vars.to.regress = ...); percent.mt is computed first +# (by the workflow's pattern, or by the ids --mt-genes lists) and a table's columns are added with +# AddMetaData() (lib/clustering.R cl_covariates). # # --input is an export's input/ (export_clustering.R): the object's RNA counts as saved, rebuilt as # the identical dgCMatrix and wrapped with CreateSeuratObject(), as a v3 Assay for the emptyDrops @@ -21,5 +26,9 @@ source(file.path(here, "lib", "io.R")) source(file.path(here, "lib", "doubletfinder.R")) # df_args source(file.path(here, "lib", "clustering.R")) -args <- df_args(list(input = NULL, out = NULL, level = NULL, umap = "yes", assay = "auto")) +# M15b: --vars-to-regress , --percent-mt yes|no, --mt-genes , --metadata +# (lib/clustering.R cl_covariates; the defaults are the chain as the workflow runs it now) +args <- df_args(list(input = NULL, out = NULL, level = NULL, umap = "yes", assay = "auto", + `vars-to-regress` = "", `percent-mt` = "no", `mt-genes` = "", metadata = "")) +names(args) <- gsub("-", "_", names(args), fixed = TRUE) cl_main(args, "validation/R/reference_clustering.R") diff --git a/validation/R/regress_vectors.R b/validation/R/regress_vectors.R new file mode 100644 index 0000000..3c0a710 --- /dev/null +++ b/validation/R/regress_vectors.R @@ -0,0 +1,220 @@ +#!/usr/bin/env Rscript +# Milestone M15b (docs/PLAN.md C3, "vars.to.regress and percent.mt"): the code path of +# SCTransform's second regression and of PercentageFeatureSet() as the pinned env runs them, and +# reference vectors for the Rust port (rcompat::linpack, scio's percent.mt). +# +# 1. The code path. The installed functions are compared with the source tarballs that +# third_party/fetch_sources.sh fetched (their bodies parsed from the tarball's files must be +# identical() to the installed ones): Seurat 5.5.1's SCTransform.default, .Assay, .Seurat, +# .StdAssay, FetchResiduals.SCTAssay, FetchResidualSCTModel, ScaleData.default, +# RegressOutMatrix, FastRowScale, PercentageFeatureSet; R 4.5.3's lm, lm.fit, qr.resid; and +# how R's grep (TRE, perl = FALSE) treats "(?i)^mt-". +# 2. tests/fixtures/rcompat/linpack_qr.tsv and linpack_resid.tsv: the QR that +# RegressOutMatrix() takes once, lm(GENE ~ , qr = TRUE)$qr (LINPACK dqrdc2 through +# Cdqrls, tol = 1e-7), and qr.resid() of several rows (dqrrsd -> dqrsl), with +# RegressOutMatrix()'s own result for the same rows. dqrdc2 and dqrsl call BLAS ddot, daxpy, +# dnrm2 and dscal: run with OPENBLAS_CORETYPE=Haswell, the portable profile (env.sh's default). +# 3. tests/fixtures/clustering/percent_mt/: a small 10x directory with tricky feature names +# (case, underscores and pipes that Seurat turns into dashes, duplicates that Read10X makes +# unique, a mitochondrial gene with no counts, non-integer counts in a second matrix) and +# PercentageFeatureSet()'s results, by the pattern and by a list of features. +# +# Reads no .rds. Runs in the production R env with the hermetic flags, through srun or sbatch: +# R_ENV=/n/holylfs05/LABS/informatics/Users/afreedman/smk-conda-envs/d3ca7f730a70e6f748bb65a12a5ed3f9_ +# env -u R_LIBS_USER -u R_LIBS_SITE -u R_LIBS -u PERL5LIB PYTHONNOUSERSITE=1 \ +# "$R_ENV/bin/Rscript" validation/R/regress_vectors.R +# +# Doubles are written as their IEEE-754 bit patterns (16 hex digits), lists comma-separated. + +args <- commandArgs(trailingOnly = TRUE) +root <- if (length(args)) args[[1]] else "." +fx <- file.path(root, "tests", "fixtures") +stopifnot(R.version$major == "4", R.version$minor == "5.3") +suppressPackageStartupMessages({ + library(Seurat) + library(Matrix) +}) +stopifnot(as.character(packageVersion("Seurat")) == "5.5.1") +cat("OpenBLAS kernel:", Sys.getenv("OPENBLAS_CORETYPE"), " threads:", Sys.getenv("OPENBLAS_NUM_THREADS"), "\n") +cat("La_library:", La_library(), "\n") +cat("BLAS (extSoftVersion):", extSoftVersion()[["BLAS"]], "\n") + +hex <- function(x) { + x <- as.double(x) + if (!length(x)) return(character()) + b <- writeBin(x, raw(), size = 8, endian = "big") + apply(matrix(as.character(b), nrow = 8), 2, paste, collapse = "") +} +lst <- function(v) if (length(v)) paste(v, collapse = ",") else "-" +hexl <- function(x) lst(hex(x)) + +# 1. The code path ---------------------------------------------------------------------------- + +src <- file.path(root, "third_party", "src") +from_source <- function(file, name) { + e <- new.env() + exprs <- parse(file = file, keep.source = FALSE) + for (ex in exprs) { + if (is.call(ex) && identical(ex[[1]], as.name("<-")) && identical(ex[[2]], as.name(name))) { + return(eval(ex[[3]], e)) + } + } + stop(name, " not found in ", file) +} +same_fun <- function(installed, file, name) { + f <- from_source(file, name) + ok <- identical(body(installed), body(f)) && identical(formals(installed), formals(f)) + cat(sprintf("%-28s %s (%s)\n", name, if (ok) "identical to the source" else "DIFFERS", basename(file))) + ok +} +seu_r <- file.path(src, "Seurat-5.5.1", "R") +checks <- c( + same_fun(Seurat:::SCTransform.default, file.path(seu_r, "preprocessing.R"), "SCTransform.default"), + same_fun(Seurat:::SCTransform.Assay, file.path(seu_r, "preprocessing.R"), "SCTransform.Assay"), + same_fun(Seurat:::SCTransform.Seurat, file.path(seu_r, "preprocessing.R"), "SCTransform.Seurat"), + same_fun(Seurat:::SCTransform.StdAssay, file.path(seu_r, "preprocessing5.R"), "SCTransform.StdAssay"), + same_fun(Seurat:::FetchResiduals.SCTAssay, file.path(seu_r, "preprocessing5.R"), "FetchResiduals.SCTAssay"), + same_fun(Seurat:::FetchResidualSCTModel, file.path(seu_r, "preprocessing5.R"), "FetchResidualSCTModel"), + same_fun(Seurat:::ScaleData.default, file.path(seu_r, "preprocessing.R"), "ScaleData.default"), + same_fun(Seurat:::RegressOutMatrix, file.path(seu_r, "preprocessing.R"), "RegressOutMatrix"), + same_fun(Seurat::FastRowScale, file.path(seu_r, "utilities.R"), "FastRowScale"), + same_fun(Seurat::PercentageFeatureSet, file.path(seu_r, "utilities.R"), "PercentageFeatureSet"), + same_fun(stats::lm, file.path(src, "R-4.5.3", "src", "library", "stats", "R", "lm.R"), "lm"), + same_fun(stats::lm.fit, file.path(src, "R-4.5.3", "src", "library", "stats", "R", "lm.R"), "lm.fit"), + same_fun(base::qr.resid, file.path(src, "R-4.5.3", "src", "library", "base", "R", "qr.R"), "qr.resid") +) +if (!all(checks)) stop("an installed function differs from its source") +cat("future plan workers:", future::nbrOfWorkers(), "\n") + +# grep's TRE engine (perl = FALSE) and the inline flag +names_tre <- c("mt-Nd1", "MT-ND1", "Mt-Co1", "mT-Cytb", "mt-", "MT-", "mt", "MT", "mt.1", "xmt-a", + " mt-a", "mt -a", "mt‐a", "mt-a", "m-t-a", "MT--", "mt-mt-", "Mtor", "MTX-1", + "mt_a", "mt|a") +hit <- grepl("(?i)^mt-", names_tre) +cat("grep(\"(?i)^mt-\", perl = FALSE):\n") +for (i in seq_along(names_tre)) cat(sprintf(" %-10s %s\n", encodeString(names_tre[i], quote = "\""), hit[i])) +want <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, + FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE) +if (!identical(hit, want)) stop("TRE's matches are not the ones expected") +# the same with perl = TRUE (PCRE): for the record +stopifnot(identical(grepl("(?i)^mt-", names_tre, perl = TRUE), want)) + +# 2. The QR and the residuals ------------------------------------------------------------------ + +set.seed(20261119) +cases <- list() +add <- function(name, latent) cases[[name]] <<- as.data.frame(latent) +add("full_n5", list(v = rnorm(5))) +add("percent_n40", list(percent.mt = round(runif(40) * 100, 3))) +add("count_score_n151", list(nCount_RNA = round(runif(151) * 20000) + 500, score = runif(151) * 5)) +add("zero_n151", list(percent.mt = rep(0, 151))) +add("constant_n151", list(v = rep(7.25, 151))) +v151 <- rnorm(151) +add("collinear_n151", list(v = v151, w = 2 * v151)) +pz <- ifelse(runif(613) < 0.3, 0, rexp(613) * 3) +add("percent_count_n613", list(percent.mt = pz, nCount_RNA = round(rexp(613) * 4000) + 200)) +add("square_n2", list(v = c(1, 3))) +add("square_n3", list(v = rnorm(3), w = rnorm(3))) +add("wide_n2", list(v = rnorm(2), w = rnorm(2))) +add("outlier_n151", list(v = c(rnorm(150), 1e6))) +add("block_n64", list(v = runif(64))) +add("odd_n17", list(v = runif(17), w = rnorm(17))) +add("nearly_n151", list(v = rep(1, 151) + c(1e-9, rep(0, 150)))) + +qr_rows <- character() +resid_rows <- character() +for (name in names(cases)) { + L <- cases[[name]] + n <- nrow(L) + Y <- rbind(round(rnorm(n) * 2, 6), pmin(pmax(rnorm(n) * 3, -3), 3), rep(0.5, n)) + rownames(Y) <- paste0("g", seq_len(nrow(Y))) + colnames(Y) <- paste0("c", seq_len(n)) + rownames(L) <- colnames(Y) + # as RegressOutMatrix takes it (Seurat 5.5.1, preprocessing.R): the formula, then lm's qr once + fmla <- as.formula(paste("GENE ~", paste(colnames(L), collapse = "+"))) + regression.mat <- cbind(L, Y[1, ]) + colnames(regression.mat) <- c(colnames(L), "GENE") + qr <- lm(fmla, data = regression.mat, qr = TRUE)$qr + X <- model.matrix(fmla, data = regression.mat) + qr_rows <- c(qr_rows, paste(name, n, ncol(X), paste(colnames(L), collapse = ","), hexl(X), + hexl(qr$qr), hexl(qr$qraux), lst(qr$pivot), qr$rank, hexl(qr$tol), sep = "\t")) + seurat <- Seurat:::RegressOutMatrix(data.expr = Y, latent.data = L, features.regress = rownames(Y), + model.use = "linear", use.umi = FALSE, verbose = FALSE) + for (k in seq_len(nrow(Y))) { + r <- qr.resid(qr = qr, y = Y[k, ]) + if (!identical(unname(r), unname(seurat[k, ]))) stop(name, " row ", k, ": qr.resid and RegressOutMatrix differ") + resid_rows <- c(resid_rows, paste(name, k, hexl(Y[k, ]), hexl(r), sep = "\t")) + } + cat(sprintf("%-20s n %4d, p %d, rank %d, pivot %s\n", name, n, ncol(X), qr$rank, lst(qr$pivot))) +} +dir.create(file.path(fx, "rcompat"), showWarnings = FALSE, recursive = TRUE) +gz_write <- function(lines, path) { + writeLines(lines, path) + if (system2("gzip", c("-n", "-9", "-f", shQuote(path))) != 0) stop("gzip ", path) +} +gz_write(c("# case\tn\tp\tvariables\tx (model.matrix, column-major)\tqr\tqraux\tpivot\trank\ttol", qr_rows), + file.path(fx, "rcompat", "linpack_qr.tsv")) +gz_write(c("# case\trow\ty\tqr.resid(qr, y) (= RegressOutMatrix's row)", resid_rows), + file.path(fx, "rcompat", "linpack_resid.tsv")) + +# 3. percent.mt ------------------------------------------------------------------------------- + +pdir <- file.path(fx, "clustering", "percent_mt") +dir.create(pdir, showWarnings = FALSE, recursive = TRUE) +feat <- data.frame( + id = sprintf("ID%02d", 1:14), + name = c("mt-Co1", "MT-ND2", "Mt_Atp6", "mT|Cytb", "Mtor", "xmt-a", "mt", "mt", "Gene_1", "Gene_1", + "mt-Zero", "Actb", "mtx-1", "MT-"), + type = "Gene Expression", stringsAsFactors = FALSE) +cells <- sprintf("CELL%d-1", 1:7) +set.seed(7) +m <- matrix(rpois(14 * 7, 3), 14, 7) +m[11, ] <- 0 # mt-Zero: no counts +m[, 7] <- 0 # a cell with no mitochondrial counts +m[c(1, 12), 7] <- c(0, 9) +m[1, 6] <- 0 +counts_int <- as(m, "CsparseMatrix") +mreal <- m * 1 +mreal[mreal > 0] <- mreal[mreal > 0] + c(0.1, 0.2, 0.7, 0.3)[seq_len(sum(mreal > 0)) %% 4 + 1] +counts_real <- as(mreal, "CsparseMatrix") +write_10x <- function(cm, d) { + dir.create(d, showWarnings = FALSE, recursive = TRUE) + writeMM(cm, file.path(d, "matrix.mtx")) + writeLines(cells, file.path(d, "barcodes.tsv")) + write.table(feat, file.path(d, "features.tsv"), sep = "\t", quote = FALSE, row.names = FALSE, col.names = FALSE) + # Read10X reads Cell Ranger v3's gzipped names + for (f in c("matrix.mtx", "barcodes.tsv", "features.tsv")) { + if (system2("gzip", c("-n", "-9", "-f", shQuote(file.path(d, f)))) != 0) stop("gzip ", f) + } +} +ids_file <- file.path(pdir, "mt_genes.txt") +writeLines(c("# an ID list: ID03 and ID04 (renamed by Seurat), ID11 (no counts), ID02 twice,", + "# two IDs not among the features, and a blank line", "ID03", "ID04", "", "ID11", "ID02", + "ID02", "NOPE1", "NOPE2"), ids_file) +pm_rows <- character() +for (kind in c("integer", "real")) { + d <- file.path(pdir, kind) + write_10x(if (kind == "integer") counts_int else counts_real, d) + seu <- suppressWarnings(CreateSeuratObject(counts = Read10X(d))) + rn <- rownames(seu) + by_pattern <- PercentageFeatureSet(seu, pattern = "(?i)^mt-") + # the list: the features whose id (column 1) is listed, in the counts' row order + ids <- readLines(ids_file) + ids <- ids[nzchar(ids) & !startsWith(ids, "#")] + listed <- rn[feat$id %in% ids] + by_list <- suppressWarnings(PercentageFeatureSet(seu, features = listed)) + pm_rows <- c(pm_rows, + paste(kind, "pattern", lst(grep("(?i)^mt-", rn, value = TRUE)), hexl(unname(by_pattern)), sep = "\t"), + paste(kind, "list", lst(listed), hexl(unname(by_list)), sep = "\t"), + paste(kind, "nCount_RNA", "-", hexl(seu$nCount_RNA), sep = "\t")) + if (kind == "integer") writeLines(rn, file.path(pdir, "seurat_names.txt")) +} +# make.unique(), as Read10X() applies it +mu <- list(c("a", "a", "b", "a", "a.1", "b"), c("a", "a.1", "a"), c("x", "x", "x.1", "x.1", "x"), + c("g", "g.2", "g", "g", "g.1"), c("mt", "mt", "mt.1", "MT", "mt")) +writeLines(c("# names\tmake.unique(names)", vapply(mu, function(v) paste(lst(v), lst(make.unique(v)), sep = "\t"), "")), + file.path(pdir, "make_unique.tsv")) +writeLines(c("# counts\tdefinition\tfeatures (Seurat's names)\tpercent.mt per cell", pm_rows), + file.path(pdir, "expected.tsv")) +cat("Seurat's names:", lst(readLines(file.path(pdir, "seurat_names.txt"))), "\n") +cat("done\n") diff --git a/validation/benchmark/README.md b/validation/benchmark/README.md index ee2f9bf..165d499 100644 --- a/validation/benchmark/README.md +++ b/validation/benchmark/README.md @@ -38,6 +38,10 @@ The benchmark's harness (docs/benchmarks.md describes the method; this file is a - Clustering its own input (`h`) adds the clustering's CPU time, 1.13–1.64× `d`'s at one thread, and no memory: its peak stays DoubletFinder's, or below it on the smallest object (0.89×). - The whole rule in one process (`p`) takes `d` + `r`'s CPU time at one thread (0.98–1.04×) at the same peak. The in-process re-clustering takes 0.93–0.98× `r`'s CPU time (each object's median): the second command's start and its reading of `singlets/`. That is under 2% of the rule. At 32 threads `p` finishes 3–12% sooner. - Within one repeat, `p`'s DoubletFinder phases took 0.93–1.06× `d`'s CPU time, the same code run twice. That is more than the hand-off saves, so such comparisons need the repeats and the per-phase records. +- **M15b: the chain with SCTransform's `vars.to.regress`** (`cluster_regress`; docs/benchmarks.md has the tables): + - Against R's scripts as they ran with the regression (before the pipeline's commit 8d34de1): 2.7–6.7× less CPU time at one thread, 2.1–3.7× with `--export`, 8.8–44× less memory, 14–20× sooner at 32 threads. + - The regression costs Rust nothing measurable: on the same node `n` took 0.98–1.01× `b`'s CPU time (seven pairs). The medians across nodes (0.99–1.12× at one thread) mix nodes whose repeats differ by up to 15%: comparing variants, compare runs on the same node. + - It raises R's peak by up to 12% (cellbender_fromraw_ghirsutum2: 118 against 105 GiB). ### What each side runs (like for like) @@ -72,6 +76,10 @@ The benchmark's harness (docs/benchmarks.md describes the method; this file is a - `h`: `scrust doubletfinder` without `--clusters`: it clusters its own input in process first (clustering on the fly). Against `d`, it shows the hook's cost; - `p`: `scrust doubletfinder --clusters ... --recluster --recluster-export`: the whole rule in one process, the singlets handed to the clustering from memory, with the export as `r` writes it. Against `d` + `r`, it shows what the in-process hand-off saves; against R's whole rule, the port's gain. - The in-process clusterings record their stages on the command's clock (`clustering: `, `recluster: `), which `analyze.py` classifies as `r`'s stages. The re-clustering writes `singlets_clusters/` (`recluster/` in the runs of binaries before M15's final commit, which `analyze.py` also reads). From M15 on, the chain's stage files are written in its write phase, not after each stage; `analyze.py` knows the binaries that wrote them after each stage (`STAGE_WRITER`), and applies the pca writer's calibration to those only. +- **M15b: the chain with SCTransform's `vars.to.regress`** (tool `cluster_regress`, on the seven tier-P clustering objects): + - R's side: the same rules' scripts as they were before the pipeline's commit 8d34de1 (2026-10-30), which still passed `vars.to.regress = "percent.mt"` to SCTransform: `validation/benchmark/workflow_regress/`, made by `make_workflow_copies.py --rev 8d34de1^ --out workflow_regress`, each source's git blob id in its `SOURCES.tsv`. The four scripts these rules run differ from `workflow/`'s sources in that argument and two comment lines only, so against the `cluster` rows they show what the regression costs R. Checks: the number of clusters and the cluster ids equal M15b's R reference run of the same chain (`data/clustering/m15b/runs//pm/`). + - Rust's side: `scrust cluster --counts --preset workflow --vars-to-regress percent.mt`, without `--export` and with it. Where the workflow's pattern finds no mitochondrial feature (soupx_emptydrops_sscovelli, filtered_seurat_emptydrops_sscovelli, cellbender_fromraw_ghirsutum2), R regresses an all-zero `percent.mt` and scrust refuses the pattern, so scrust is given the same all-zero covariate through `--mt-genes` (`data/clustering/m15b/inputs//zero_genes.txt`, features without counts), as M15b's validation runs are. Checks: the files equal M15b's validation run of the case pm (`data/clustering/m15b/rust/