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