data_beans/aux/feature_rows.rs
1//! Canonical feature-row (sparse-matrix row) convention for every modality.
2//!
3//! NOT to be confused with the sibling [`crate::aux::feature_names`], which is about a
4//! different problem. This module fixes the row-name **grammar** a producer emits
5//! and a consumer splits; `feature_names` **canonicalizes** an already-emitted
6//! name so the same gene or locus matches across files that spell it differently
7//! (`FeatureNameKind`). Rows here are built and parsed; names there are matched.
8//!
9//! It lives in `data_beans::aux` rather than beside its producers because the
10//! grammar has readers on both sides of the BAM/model boundary: faba writes these
11//! rows, senna's embedding and association steps split them back apart.
12//!
13//! All per-cell matrices name their rows
14//!
15//! ```text
16//! {unit}/{modality}/{channel} unit-level (no subunit)
17//! {unit}/{modality}/{subunit}/{channel} sub-unit (component or site)
18//! ```
19//!
20//! - `unit` — the modelling unit. For every gene-resolution modality this is
21//! the gene, `{gene_id}_{gene_name}` (`gene_count::splice::format_gene_key`).
22//! [`BAF`] is the exception: a variant is a coordinate, not a gene. It does
23//! not belong to one, and two overlapping genes would otherwise give the same
24//! variant two row names, so its unit is the `{chr}:{pos}` locus.
25//! - `modality` — the lowercase subcommand name: [`COUNT`] / [`M6A`] / [`ATOI`]
26//! / [`APA`], or [`BAF`].
27//! - `subunit` — optional sub-gene id: a single-base `{chr}:{pos}` site (m6A and
28//! A-to-I sites are one base pair) or an EM mixture `{component}` index.
29//! Omitted for gene-level pooled rows. It sits **above** the channel: a
30//! component/site is a position cluster fit once per `(gene, modality)` and
31//! shared by both channels, so the channel nests inside it.
32//! - `channel` — the innermost (last) field: the two read-states that modality
33//! contrasts (gene counts split [`SPLICED`]/[`UNSPLICED`]; m6A
34//! [`METHYLATED`]/[`UNMETHYLATED`]; ATOI [`EDITED`]/[`UNEDITED`]; APA
35//! [`PROXIMAL`]/[`DISTAL`]; BAF [`ALT`]/[`DEPTH`]). Omitted by the one
36//! producer whose contrast lives across the units rather than within the row —
37//! see [`unit_row`].
38//!
39//! Putting the channel last means a unit's two channel rows share a contiguous
40//! prefix (the unit), and "strip the trailing field" recovers the unit.
41//!
42//! Every channelized modality keeps both states in ONE matrix rather than in a
43//! pair of same-shaped files, so a ratio is a division within one unit's rows
44//! and no consumer has to open two files and trust their row orders agree.
45//!
46//! Most channel pairs PARTITION the coverage — the two states are exclusive and
47//! sum to the total. [`BAF`] is the exception: [`ALT`] is nested inside
48//! [`DEPTH`] (`alt ≤ depth`), so BAF is `alt / depth` and NOT `alt / (alt +
49//! depth)`. Any consumer that sums a unit's channels to recover coverage is
50//! wrong on this modality alone.
51//!
52//! This module is the single source of truth. Consumers split rows with
53//! [`parse_feature_row`]; producers build them with [`feature_row`] /
54//! [`unit_row`] rather than hand-spelling the tokens. The gene-count, APA, SNP
55//! and quant producers all go through it; the editing / mixture / pileup
56//! producers still emit their rows inline and are the remaining migration.
57//!
58//! One consumer still parses by hand: `faba::quant::extract_gene_key` strips a
59//! trailing `/count/{channel}` with `rfind`. That is safe *there* — it runs only
60//! over faba's own gene matrices, and its job is to group every row of a gene
61//! (including the pooled `total` track) under one key for QC, which is what its
62//! callers want. A caller that must additionally decide WHICH track a row is
63//! goes through [`parse_feature_row`]: the same shortcut would put `total` in
64//! the spliced bucket and double-count the gene.
65//!
66//! The unit of a parsed row is [`FeatureRow::unit`], and the gene is
67//! [`FeatureRow::gene`] — read those fields rather than re-splitting the string.
68//! `unit.split('/').next()` USED to recover the gene and no longer does: a unit
69//! may itself contain `/`, because gene symbols do (see [`parse_feature_row`]),
70//! so that recipe truncates such a gene at its first slash.
71
72///////////////////////////////
73// modality tokens (field 1) //
74///////////////////////////////
75pub const COUNT: &str = "count";
76pub const M6A: &str = "m6a";
77pub const ATOI: &str = "atoi";
78pub const APA: &str = "apa";
79/// Per-cell allele frequency at a called variant locus. Named for what the
80/// matrix measures (B-allele frequency), not for the calling step that chose the
81/// positions: the call set — genotype, GQ, rsid — is `snp_sites.parquet` /
82/// `snp_sites.vcf.gz`, and a row here carries none of it, only two read counts.
83pub const BAF: &str = "baf";
84
85//////////////////////////////
86// channel tokens (field 2) //
87//////////////////////////////
88pub const SPLICED: &str = "spliced";
89pub const UNSPLICED: &str = "unspliced";
90/// Gene-count total (spliced + unspliced) — used by the pooled gene-QC track.
91pub const TOTAL: &str = "total";
92pub const METHYLATED: &str = "methylated";
93pub const UNMETHYLATED: &str = "unmethylated";
94pub const EDITED: &str = "edited";
95pub const UNEDITED: &str = "unedited";
96/// APA channels come from the 2-site PDUI decomposition (proximal vs distal
97/// poly-A in the 3'UTR). The K-component poly-A *mixture* is a separate count
98/// matrix, NOT channelized — it does not follow this convention.
99pub const PROXIMAL: &str = "proximal";
100pub const DISTAL: &str = "distal";
101/// BAF numerator: reads carrying the called alt allele.
102pub const ALT: &str = "alt";
103/// BAF denominator: ALL reads over the locus, alt included. The only channel
104/// pair that nests rather than partitions — see the module docs.
105pub const DEPTH: &str = "depth";
106
107/// A modality's two channels, in the order the module docs list them: the
108/// state the modality counts first ([`METHYLATED`], [`EDITED`], [`ALT`]),
109/// then its counterpart. `None` for a token outside the vocabulary.
110pub fn channels(modality: &str) -> Option<(&'static str, &'static str)> {
111 match modality {
112 COUNT => Some((SPLICED, UNSPLICED)),
113 M6A => Some((METHYLATED, UNMETHYLATED)),
114 ATOI => Some((EDITED, UNEDITED)),
115 APA => Some((PROXIMAL, DISTAL)),
116 BAF => Some((ALT, DEPTH)),
117 _ => None,
118 }
119}
120
121/// Format a feature row. Pass `subunit = None` for a gene-level (pooled) row
122/// `{gene}/{modality}/{channel}`, or `Some(site_or_component)` for a sub-gene row
123/// `{gene}/{modality}/{subunit}/{channel}` (channel innermost). The `subunit` must
124/// not contain `/` (sites use the single-base `chr:pos`, components are integers),
125/// so the row round-trips through [`parse_feature_row`].
126pub fn feature_row(gene: &str, modality: &str, channel: &str, subunit: Option<&str>) -> Box<str> {
127 match subunit {
128 Some(s) => format!("{gene}/{modality}/{s}/{channel}").into(),
129 None => format!("{gene}/{modality}/{channel}").into(),
130 }
131}
132
133/// Format a channel-less UNIT row `{gene}/{modality}/{subunit}`.
134///
135/// One producer names a unit with no channel, because its contrast lives ACROSS
136/// the units rather than within the row: the APA poly-A mixture,
137/// `{gene}/apa/{component}` — usage is relative across the components of a gene,
138/// so no component has a counterpart channel.
139///
140/// SNP allele counts were the second such producer, splitting alt and depth
141/// across two same-shaped matrices that a consumer had to open together. They
142/// are now [`BAF`], channelized on [`ALT`]/[`DEPTH`] inside one matrix.
143///
144/// Such a row is indistinguishable from a gene-level one under
145/// [`parse_feature_row`]: both are three fields, and the subunit lands in the
146/// `channel` slot. A consumer has to know which matrix it is reading. Prefer
147/// [`feature_row`] wherever the modality does have two channels.
148pub fn unit_row(gene: &str, modality: &str, subunit: &str) -> Box<str> {
149 format!("{gene}/{modality}/{subunit}").into()
150}
151
152/// A feature row split into its fields, borrowing from the source string.
153#[derive(Clone, Copy, PartialEq, Eq, Debug)]
154pub struct FeatureRow<'a> {
155 pub gene: &'a str,
156 pub modality: &'a str,
157 pub channel: &'a str,
158 pub subunit: Option<&'a str>,
159}
160
161impl FeatureRow<'_> {
162 /// The modelling unit of this row: the bare gene at gene resolution, or
163 /// `{gene}/{modality}/{subunit}` at sub-gene resolution.
164 ///
165 /// The gene is NOT recoverable by splitting this on `/` — a gene symbol may
166 /// contain one. Use [`Self::gene`], which is already the parsed field.
167 pub fn unit(&self) -> Box<str> {
168 match self.subunit {
169 Some(s) => format!("{}/{}/{}", self.gene, self.modality, s).into(),
170 None => self.gene.into(),
171 }
172 }
173}
174
175/// The closed modality vocabulary, used to LOCATE the modality field rather
176/// than to validate it — see [`parse_feature_row`].
177const MODALITIES: [&str; 5] = [COUNT, M6A, ATOI, APA, BAF];
178
179/// Split a feature row into its fields. The channel is the innermost (last)
180/// field, so a 3-field row is gene-level (`{gene}/{modality}/{channel}`) and a
181/// 4-field row carries a subunit before the channel
182/// (`{gene}/{modality}/{subunit}/{channel}`).
183///
184/// # A unit may contain `/`
185///
186/// Counting fields alone is not enough, because **real gene symbols contain
187/// slashes** — standard human references ship at least one. Such a gene's count
188/// row has four fields and used to parse as `gene = {id}_GENE1`,
189/// `modality = GENE1B`, `subunit = count`: not an error, just a different gene,
190/// so the two channel rows of that gene stopped pairing and nothing said so.
191///
192/// So the modality is located by NAME, scanned from the right against
193/// [`MODALITIES`], and whatever precedes it is the unit however many slashes it
194/// contains. The subunit and channel still may not contain `/` — they are a
195/// `chr:pos`, a component index, and a fixed token.
196///
197/// The two candidate positions are tried nearest-first, so a row whose unit ENDS
198/// in a modality token reads as the gene-level form: `A/count/count/spliced` is
199/// the gene `A/count`, not the gene `A` with a subunit called `count`. That
200/// ambiguity is unreachable in practice — a subunit is a `chr:pos` or a component
201/// index, never a modality name.
202///
203/// When NEITHER candidate position holds a known modality the old positional
204/// rule applies unchanged, so the producers that still emit their rows inline
205/// with a modality token outside the constant list (see the module docs) keep
206/// parsing exactly as they did. The vocabulary can only make a row parse
207/// BETTER, never make a row that parsed stop parsing.
208///
209/// Returns `None` for anything with fewer than three fields, or more than four
210/// when no known modality locates the split.
211pub fn parse_feature_row(name: &str) -> Option<FeatureRow<'_>> {
212 let is_modality = |s: &str| MODALITIES.contains(&s);
213
214 // Peel the channel, then look one and two fields further left for the
215 // modality. `rsplit_once` keeps every field a slice of `name`, so a
216 // multi-field unit costs no allocation.
217 if let Some((head, channel)) = name.rsplit_once('/') {
218 if let Some((left, mid)) = head.rsplit_once('/') {
219 if is_modality(mid) && !left.is_empty() {
220 return Some(FeatureRow {
221 gene: left,
222 modality: mid,
223 channel,
224 subunit: None,
225 });
226 }
227 if let Some((gene, modality)) = left.rsplit_once('/') {
228 if is_modality(modality) && !gene.is_empty() {
229 return Some(FeatureRow {
230 gene,
231 modality,
232 channel,
233 subunit: Some(mid),
234 });
235 }
236 }
237 }
238 }
239
240 let parts: Vec<&str> = name.split('/').collect();
241 match parts.as_slice() {
242 [gene, modality, channel] => Some(FeatureRow {
243 gene,
244 modality,
245 channel,
246 subunit: None,
247 }),
248 [gene, modality, subunit, channel] => Some(FeatureRow {
249 gene,
250 modality,
251 channel,
252 subunit: Some(subunit),
253 }),
254 _ => None,
255 }
256}
257
258///////////////////////////////////////////////
259// gene-count rows, interned to a gene axis //
260///////////////////////////////////////////////
261
262/// Split a gene-level count row `{gene}/count/{spliced|unspliced}` into its gene
263/// key and whether it is the **nascent** (unspliced) track. `None` when the row is
264/// not a gene-level count row at all.
265///
266/// Goes through [`parse_feature_row`] rather than matching on `/count/` directly,
267/// because a bare `rsplit_once` **cannot tell "spliced" apart from "not a count
268/// row"** — both fall to the same branch. It used to, and the consequence was
269/// silent: `GENE1/m6a/methylated` became a mature gene literally named
270/// `GENE1/m6a/methylated`, and the sub-gene form `{gene}/count/{site}/{channel}`
271/// became a mature row of the right gene.
272///
273/// [`TOTAL`] is rejected along with everything else: it already IS
274/// `spliced + unspliced`, so interning it as a third track would count the gene
275/// twice. A `subunit` is rejected because a per-site or per-component row is not
276/// a thing that pairs across tracks at gene resolution.
277#[must_use]
278pub fn split_count_row(name: &str) -> Option<(&str, bool)> {
279 let row = parse_feature_row(name)?;
280 if row.modality != COUNT || row.subunit.is_some() {
281 return None;
282 }
283 match row.channel {
284 SPLICED => Some((row.gene, false)),
285 UNSPLICED => Some((row.gene, true)),
286 _ => None,
287 }
288}
289
290/// [`CountRowMap::row_to_gene`] entry for a row that was left off the gene axis.
291/// Only ever produced under [`UnparsedRowPolicy::Reject`].
292pub const NO_GENE: u32 = u32::MAX;
293
294/// What [`intern_count_rows`] does with a row that is not
295/// `{gene}/count/{spliced|unspliced}`.
296///
297/// The two consumers want opposite things, and neither is more correct: a
298/// gene-keyed model can carry a stray row harmlessly as its own single-track
299/// gene, while a consumer that POOLS the two tracks cannot — it would have to
300/// decide which track the stray row is, and every answer is wrong.
301#[derive(Clone, Copy, PartialEq, Eq, Debug)]
302pub enum UnparsedRowPolicy {
303 /// Give the row its own single-track gene id, keyed on the whole row name,
304 /// so every index still lines up with the matrix and the row can never be
305 /// paired with a real gene. Ids stay assigned in row order across both
306 /// kinds. The caller is expected to warn.
307 OwnGene,
308 /// Leave the row off the gene axis: [`NO_GENE`] in `row_to_gene`, and its
309 /// index in [`CountRowMap::unparsed`]. The caller decides whether that is
310 /// fatal.
311 Reject,
312}
313
314/// A count matrix's feature axis interned onto a dense gene axis.
315///
316/// Row order is the matrix's own and is never permuted; gene ids are assigned in
317/// first-seen row order, so `gene_names` is stable for a given input.
318pub struct CountRowMap {
319 /// `row_to_gene[r]` = gene id of row `r`, or [`NO_GENE`].
320 pub row_to_gene: Vec<u32>,
321 /// `row_is_nascent[r]` = true when row `r` is the unspliced track. Always
322 /// `false` for an unparsed row under either policy — such a row is not a
323 /// nascent row, it is not a count row.
324 pub row_is_nascent: Vec<bool>,
325 /// Gene keys in id order.
326 pub gene_names: Vec<Box<str>>,
327 /// Indices of rows that are not `{gene}/count/{spliced|unspliced}`, in row
328 /// order. Empty on a well-formed gene-count matrix.
329 pub unparsed: Vec<usize>,
330}
331
332impl CountRowMap {
333 #[must_use]
334 pub fn n_genes(&self) -> usize {
335 self.gene_names.len()
336 }
337
338 #[must_use]
339 pub fn n_rows(&self) -> usize {
340 self.row_to_gene.len()
341 }
342
343 /// Rows on the nascent track. Zero on a spliced-only matrix — a legitimate
344 /// input that simply identifies no nascent-minus-mature contrast.
345 #[must_use]
346 pub fn n_nascent_rows(&self) -> usize {
347 self.row_is_nascent.iter().filter(|&&n| n).count()
348 }
349}
350
351/// Intern a count matrix's feature axis onto a dense gene axis, pairing a gene's
352/// two channel rows under one id.
353#[must_use]
354pub fn intern_count_rows(feature_names: &[Box<str>], policy: UnparsedRowPolicy) -> CountRowMap {
355 let mut ids: rustc_hash::FxHashMap<Box<str>, u32> = rustc_hash::FxHashMap::default();
356 let mut row_to_gene = Vec::with_capacity(feature_names.len());
357 let mut row_is_nascent = Vec::with_capacity(feature_names.len());
358 let mut gene_names: Vec<Box<str>> = Vec::new();
359 let mut unparsed: Vec<usize> = Vec::new();
360
361 for (r, name) in feature_names.iter().enumerate() {
362 let Some((gene, is_nascent)) = split_count_row(name) else {
363 unparsed.push(r);
364 match policy {
365 UnparsedRowPolicy::Reject => row_to_gene.push(NO_GENE),
366 UnparsedRowPolicy::OwnGene => {
367 let g = gene_names.len() as u32;
368 ids.insert(name.clone(), g);
369 gene_names.push(name.clone());
370 row_to_gene.push(g);
371 }
372 }
373 row_is_nascent.push(false);
374 continue;
375 };
376 let gid = match ids.get(gene) {
377 Some(&g) => g,
378 None => {
379 let g = gene_names.len() as u32;
380 ids.insert(gene.into(), g);
381 gene_names.push(gene.into());
382 g
383 }
384 };
385 row_to_gene.push(gid);
386 row_is_nascent.push(is_nascent);
387 }
388
389 CountRowMap {
390 row_to_gene,
391 row_is_nascent,
392 gene_names,
393 unparsed,
394 }
395}
396
397#[cfg(test)]
398mod tests;