diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index cee8260de..bd4f26bf9 100644 --- a/crates/andes/src/bin/andes/dia.rs +++ b/crates/andes/src/bin/andes/dia.rs @@ -4,11 +4,16 @@ pub(crate) mod joint; pub(crate) mod llr; pub(crate) mod pass2; pub(crate) mod pin; +pub(crate) mod qvalue; pub(crate) mod rt; pub(crate) mod score; pub(crate) mod study; pub(crate) mod transfer; +pub(crate) use qvalue::{precursor_q, precursor_q_by_class}; +#[cfg(test)] +use qvalue::{classwise_q_values, curve_at, precursor_q_values, q_curve}; + use std::collections::HashMap; use std::path::Path; use std::time::Instant; @@ -105,9 +110,9 @@ pub(crate) fn rerank_pin( .max(c_label.unwrap_or(0)) .max(c_run.unwrap_or(0)) + 1; - let mut group_of: HashMap = HashMap::new(); + let mut group_of: rustc_hash::FxHashMap = rustc_hash::FxHashMap::default(); let mut key = String::new(); - let mut run_of: HashMap = HashMap::new(); + let mut run_of: rustc_hash::FxHashMap = rustc_hash::FxHashMap::default(); let mut group = Vec::new(); let mut raw = Vec::new(); let mut ms2 = Vec::new(); @@ -225,7 +230,12 @@ pub(crate) fn rerank_pin( } drop((rt_diff, target, run)); let mut order: Vec = (0..n_rows).collect(); - order.sort_by(|&a, &b| group[a].cmp(&group[b]).then(score[b].total_cmp(&score[a]))); + order.par_sort_unstable_by(|&a, &b| { + group[a] + .cmp(&group[b]) + .then(score[b].total_cmp(&score[a])) + .then(a.cmp(&b)) + }); let mut keep_row = vec![false; n_rows]; let mut i = 0; while i < order.len() { @@ -444,14 +454,15 @@ pub(crate) fn add_to_pin( let rt = |i: u32| spectra[i as usize].rt_seconds.unwrap_or(0.0); let (slot, windows) = windows(spectra, run_ends); - let mut best_of_spec: HashMap = HashMap::new(); + let mut best_of_spec: rustc_hash::FxHashMap = rustc_hash::FxHashMap::default(); for r in &table.rows { if r.spec != NONE { let b = best_of_spec.entry(r.spec).or_insert(f64::NEG_INFINITY); *b = b.max(r.score); } } - let mut by_precursor: HashMap<(u32, u8, u32), Vec<(u32, bool)>> = HashMap::new(); + let mut by_precursor: rustc_hash::FxHashMap<(u32, u8, u32), Vec<(u32, bool)>> = + rustc_hash::FxHashMap::default(); for r in &table.rows { if r.spec == NONE || r.form == NONE { continue; @@ -523,6 +534,7 @@ pub(crate) fn add_to_pin( }) .collect(); let values: Vec> = (0..COLUMNS.len()) + .into_par_iter() .map(|c| feats.iter().map(|f| f[c]).collect()) .collect(); write_pin(pin, &table, &cols, &values)?; @@ -1072,32 +1084,41 @@ pub(crate) fn refine_rt( skipped.push(files[r].to_string()); continue; } - for k in 0..3u64 { - let train: Vec = anchors - .iter() - .copied() - .filter(|&i| fold(i) % 3 != k) - .collect(); - let ds = RegressionDataset { - x: train.iter().flat_map(|&i| row_x(i)).collect(), - y: train.iter().map(|&i| (obs[i] - pred[i]) as f32).collect(), - groups: train.iter().map(|&i| table.rows[i].form).collect(), - n_features: nf, - feature_names: names.clone(), - }; - let params = TrainParams { - n_rounds: 200, - max_depth: 3, - min_hessian: 20.0, - ..TrainParams::default() - }; - let model = train_gbdt_regression(&ds, ¶ms, 42).ok(); - for &i in rows.iter().filter(|&&i| fold(i) % 3 == k) { - let shift = model + let models: Vec<_> = (0..3u64) + .into_par_iter() + .map(|k| { + let train: Vec = anchors + .iter() + .copied() + .filter(|&i| fold(i) % 3 != k) + .collect(); + let ds = RegressionDataset { + x: train.iter().flat_map(|&i| row_x(i)).collect(), + y: train.iter().map(|&i| (obs[i] - pred[i]) as f32).collect(), + groups: train.iter().map(|&i| table.rows[i].form).collect(), + n_features: nf, + feature_names: names.clone(), + }; + let params = TrainParams { + n_rounds: 200, + max_depth: 3, + min_hessian: 20.0, + ..TrainParams::default() + }; + train_gbdt_regression(&ds, ¶ms, 42).ok() + }) + .collect(); + let errs: Vec = rows + .par_iter() + .map(|&i| { + let shift = models[(fold(i) % 3) as usize] .as_ref() .map_or(0.0, |m| m.predict_value(&row_x(i)) as f64); - err[i] = (obs[i] - pred[i] - shift).abs(); - } + (obs[i] - pred[i] - shift).abs() + }) + .collect(); + for (&i, e) in rows.iter().zip(errs) { + err[i] = e; } let mut a: Vec = anchors.iter().map(|&i| err[i]).collect(); let mut b: Vec = anchors.iter().map(|&i| (obs[i] - pred[i]).abs()).collect(); @@ -1120,7 +1141,7 @@ pub(crate) fn refine_rt( return Ok(false); } let mut fin: Vec = err.iter().copied().filter(|e| e.is_finite()).collect(); - fin.sort_by(f64::total_cmp); + fin.par_sort_unstable_by(f64::total_cmp); let med = fin[fin.len() / 2]; for e in &mut err { if !e.is_finite() { @@ -1165,324 +1186,6 @@ pub(crate) type PrecursorQ = ( std::collections::HashSet<(String, String, u8)>, ); -/// Reports precursor-level q-values for DIA: target-decoy competition over the best -/// Percolator score of each precursor (run, peptide form, charge), with q = (D + 1) / T -/// and monotone in the score. A row receives the q of the threshold at its own score, so -/// keeping rows with q <= x keeps the precursors whose best row passes, at precursor FDR x. -/// Rows Percolator did not report keep no entry. Returns the precursor counts (targets, -/// decoys, target precursors at q <= 0.01) and the best `(score, is decoy)` of every precursor, -/// for comparing the run's precursor-level target-decoy curve at other q-values. A precursor -/// PIN (one with the `score::PRESENT_COLUMN` column) is keyed by its Peptide string and -/// charge columns and needs no spectra. With `interference` (--dia-interference) and a PSM -/// PIN, [`interference_removed`] drops precursors from the competition first; their target rows -/// get q = 1. -pub(crate) fn precursor_q( - pin: &Path, - spectra: &[Spectrum], - targets: &mut HashMap, - decoys: &HashMap, - interference: Option, -) -> Result { - let header = { - use std::io::BufRead; - let f = std::fs::File::open(pin).map_err(|e| format!("{}: {e}", pin.display()))?; - std::io::BufReader::new(f) - .lines() - .find(|l| !matches!(l, Ok(l) if l.is_empty())) - .transpose() - .map_err(|e| format!("{}: {e}", pin.display()))? - .unwrap_or_default() - }; - let h: Vec<&str> = header.split('\t').collect(); - let at = |n: &str| { - h.iter() - .position(|c| *c == n) - .ok_or_else(|| format!("{}: PIN has no {n} column", pin.display())) - }; - let (c_id, c_pep, c_label) = (at("SpecId")?, at("Peptide")?, at("Label")?); - let c_file = h.iter().position(|c| *c == "FileName"); - let charge_cols: Vec<(usize, u8)> = h - .iter() - .enumerate() - .filter_map(|(i, c)| Some((i, c.strip_prefix("charge")?.parse().ok()?))) - .collect(); - let table = if h.contains(&crate::dia::score::PRESENT_COLUMN) { - None - } else { - Some(read_pin(pin, spectra, &[])?) - }; - let mut keys: HashMap<(String, String, u8), u32> = HashMap::new(); - let mut rows: Vec<(u32, f64, bool, String)> = Vec::new(); - let mut raw: Vec<(String, String, u8)> = Vec::new(); - let mut line_of: Vec = Vec::new(); - type Parsed<'a> = Option<(bool, String, u8, &'a str, f64, &'a str, &'a str, usize)>; - let targets_ro: &HashMap = targets; - crate::dia::blocks::read_blocks( - pin, - |_| Ok(()), - |first, lines| { - let parsed: Vec, String>> = lines - .par_iter() - .enumerate() - .map(|(j, line)| { - let i = first + j; - let x: Vec<&str> = line.split('\t').collect(); - if x.len() <= c_pep.max(c_label).max(c_id) { - return Err(format!("{}: short PIN row {}", pin.display(), i + 2)); - } - let (decoy, peptide, charge) = match &table { - Some(t) => { - let r = t.rows.get(i).ok_or_else(|| { - format!("{}: row {} not read", pin.display(), i + 2) - })?; - let peptide = if r.form == NONE { - x[c_pep].to_string() - } else { - format!("#{}", r.form) - }; - (r.decoy, peptide, r.charge) - } - None => ( - x[c_label].trim() == "-1", - x[c_pep].to_string(), - charge_cols - .iter() - .find(|(c, _)| x.get(*c) == Some(&"1")) - .map_or(0, |c| c.1), - ), - }; - let id = x[c_id]; - let psm = if decoy { - decoys.get(id) - } else { - targets_ro.get(id) - }; - let Some(score) = psm.and_then(|p| p.score) else { - return Ok(None); - }; - Ok(Some(( - decoy, - peptide, - charge, - id, - score, - c_file.map_or("", |i| x[i]), - x[c_pep], - i, - ))) - }) - .collect(); - for p in parsed { - let Some((decoy, peptide, charge, id, score, run, raw_pep, i)) = p? else { - continue; - }; - let n = keys.len() as u32; - let k = *keys.entry((run.to_string(), peptide, charge)).or_insert(n); - raw.push((run.to_string(), raw_pep.to_string(), charge)); - rows.push((k, score, decoy, id.to_string())); - line_of.push(i); - } - Ok(()) - }, - )?; - let removed = match (&table, interference) { - (Some(t), Some(choice)) => { - let q0 = precursor_q_values(keys.len(), &rows); - removed_keys(&keys, &rows, &line_of, &q0, t, spectra, choice) - } - _ => vec![false; keys.len()], - }; - for (k, _, decoy, id) in &rows { - if removed[*k as usize] && !*decoy { - if let Some(p) = targets.get_mut(id) { - p.q_value = 1.0; - } - } - } - let removed_precursors = rows - .iter() - .zip(raw) - .filter(|(r, _)| removed[r.0 as usize]) - .map(|(_, n)| n) - .collect(); - rows.retain(|r| !removed[r.0 as usize]); - let q = precursor_q_values(keys.len(), &rows); - let n_targets = q.iter().filter(|p| p.is_some_and(|p| !p.1)).count(); - let n_decoys = q.iter().filter(|p| p.is_some_and(|p| p.1)).count(); - let passing = q.iter().flatten().filter(|p| !p.1 && p.2 <= 0.01).count(); - let curve = q_curve(&q); - for (_, score, decoy, id) in &rows { - if *decoy { - continue; - } - if let Some(p) = targets.get_mut(id) { - p.q_value = curve_at(&curve, *score); - } - } - let best = q.iter().flatten().map(|p| (p.0, p.1)).collect(); - Ok(((n_targets, n_decoys, passing), best, removed_precursors)) -} - -/// Best score of each precursor and its precursor-level q: `(best score, is decoy, q)`, -/// `None` for a key no row reached. Ties in score count decoys first. -fn precursor_q_values( - n_keys: usize, - rows: &[(u32, f64, bool, String)], -) -> Vec> { - let mut best: Vec> = vec![None; n_keys]; - for (k, score, decoy, _) in rows { - let b = &mut best[*k as usize]; - if b.is_none_or(|(s, _)| *score > s) { - *b = Some((*score, *decoy)); - } - } - let mut order: Vec = (0..n_keys).filter(|&i| best[i].is_some()).collect(); - order.sort_by(|&a, &b| { - let (sa, da) = best[a].unwrap_or((f64::NEG_INFINITY, true)); - let (sb, db) = best[b].unwrap_or((f64::NEG_INFINITY, true)); - sb.total_cmp(&sa).then(db.cmp(&da)) - }); - let mut q = vec![1.0f64; n_keys]; - let (mut t, mut d) = (0usize, 0usize); - let mut i = 0; - while i < order.len() { - let s = best[order[i]].map_or(f64::NEG_INFINITY, |b| b.0); - let mut j = i; - while j < order.len() && best[order[j]].map_or(f64::NEG_INFINITY, |b| b.0) == s { - if best[order[j]].is_some_and(|b| b.1) { - d += 1; - } else { - t += 1; - } - j += 1; - } - let fdr = ((d + 1) as f64 / t.max(1) as f64).min(1.0); - for &k in &order[i..j] { - q[k] = fdr; - } - i = j; - } - let mut running = 1.0f64; - for &k in order.iter().rev() { - running = running.min(q[k]); - q[k] = running; - } - best.iter() - .zip(q) - .map(|(b, qv)| b.map(|(s, d)| (s, d, qv))) - .collect() -} - -/// Score thresholds in descending order with the precursor q at each. -fn q_curve(q: &[Option<(f64, bool, f64)>]) -> Vec<(f64, f64)> { - let mut c: Vec<(f64, f64)> = q.iter().flatten().map(|p| (p.0, p.2)).collect(); - c.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.total_cmp(&b.1))); - c -} - -/// The precursor q a row with this score gets: the q of the lowest precursor best score -/// that is still at or above it; 1 below every precursor. -fn curve_at(curve: &[(f64, f64)], score: f64) -> f64 { - let n = curve.partition_point(|p| p.0 >= score); - if n == 0 { - 1.0 - } else { - curve[n - 1].1 - } -} - -/// Precursor-level q of every row computed within its class only: one target-decoy competition -/// per class (rows of class `false` against each other, rows of class `true` against each -/// other), with the rules of [`precursor_q`]. Returns the q of each row, 1 for a row whose -/// class holds no precursor at or above its score. -pub(crate) fn classwise_q_values( - n_keys: usize, - rows: &[(u32, f64, bool, String)], - class: &[bool], -) -> Vec { - let mut q = vec![1.0; rows.len()]; - for c in [false, true] { - let idx: Vec = (0..rows.len()).filter(|&i| class[i] == c).collect(); - let sub: Vec<(u32, f64, bool, String)> = idx.iter().map(|&i| rows[i].clone()).collect(); - let curve = q_curve(&precursor_q_values(n_keys, &sub)); - for &i in &idx { - q[i] = curve_at(&curve, rows[i].1); - } - } - q -} - -/// Replaces the targets' q-values of a precursor PIN by the class-wise q -/// ([`classwise_q_values`], classes by `class_col` 0 or 1) and counts the target precursors at -/// q <= 0.01 by class under the pooled q they had and under the class-wise q. Returns -/// `[[pooled class 0, pooled class 1], [class-wise class 0, class-wise class 1]]`. -pub(crate) fn precursor_q_by_class( - pin: &Path, - class_col: &str, - targets: &mut HashMap, - decoys: &HashMap, -) -> Result<[[usize; 2]; 2], String> { - let err = |e: &dyn std::fmt::Display| format!("{}: {e}", pin.display()); - let f = std::fs::File::open(pin).map_err(|e| err(&e))?; - let mut lines = std::io::BufRead::lines(std::io::BufReader::new(f)); - let header = lines - .next() - .ok_or_else(|| err(&"empty PIN"))? - .map_err(|e| err(&e))?; - let h: Vec<&str> = header.split('\t').collect(); - let at = |n: &str| { - h.iter() - .position(|c| *c == n) - .ok_or_else(|| format!("{}: PIN has no {n} column", pin.display())) - }; - let (c_id, c_pep, c_label, c_class) = (at("SpecId")?, at("Peptide")?, at("Label")?, at(class_col)?); - let charge_cols: Vec<(usize, u8)> = h - .iter() - .enumerate() - .filter_map(|(i, c)| Some((i, c.strip_prefix("charge")?.parse().ok()?))) - .collect(); - let mut keys: HashMap<(String, u8), u32> = HashMap::new(); - let mut rows: Vec<(u32, f64, bool, String)> = Vec::new(); - let mut class: Vec = Vec::new(); - for line in lines { - let line = line.map_err(|e| err(&e))?; - if line.is_empty() { - continue; - } - let x: Vec<&str> = line.split('\t').collect(); - if x.len() <= c_pep.max(c_label).max(c_id).max(c_class) { - return Err(err(&"short PIN row")); - } - let decoy = x[c_label].trim() == "-1"; - let psm = if decoy { decoys.get(x[c_id]) } else { targets.get(x[c_id]) }; - let Some(score) = psm.and_then(|p| p.score) else { - continue; - }; - let charge = charge_cols - .iter() - .find(|(c, _)| x.get(*c) == Some(&"1")) - .map_or(0, |c| c.1); - let n = keys.len() as u32; - let k = *keys.entry((x[c_pep].to_string(), charge)).or_insert(n); - rows.push((k, score, decoy, x[c_id].to_string())); - class.push(x[c_class].trim().parse::().unwrap_or(0.0) > 0.5); - } - let q = classwise_q_values(keys.len(), &rows, &class); - let mut counts = [[0usize; 2]; 2]; - for (i, (_, _, decoy, id)) in rows.iter().enumerate() { - if *decoy { - continue; - } - let c = usize::from(class[i]); - if let Some(p) = targets.get_mut(id) { - counts[0][c] += usize::from(p.q_value <= 0.01); - counts[1][c] += usize::from(q[i] <= 0.01); - p.q_value = q[i]; - } - } - Ok(counts) -} - #[cfg(test)] #[path = "dia/tests/dia.rs"] mod tests; diff --git a/crates/andes/src/bin/andes/dia/blocks.rs b/crates/andes/src/bin/andes/dia/blocks.rs index 217c7e8d0..357d6de96 100644 --- a/crates/andes/src/bin/andes/dia/blocks.rs +++ b/crates/andes/src/bin/andes/dia/blocks.rs @@ -7,6 +7,8 @@ use std::io::Read; use std::path::Path; use std::sync::mpsc::sync_channel; +use rayon::prelude::*; + /// Bytes read per block. const BLOCK_BYTES: usize = 64 << 20; /// Lines per parallel work unit of a block. @@ -23,6 +25,40 @@ fn push_lines<'a>(text: &'a str, out: &mut Vec<&'a str>) { } } +/// Pieces a block's lines are split into on the thread pool. +const SPLIT_PIECES: usize = 64; + +/// The lines of `bytes` as [`push_lines`] gives them, `None` when `bytes` is not UTF-8. The +/// bytes are cut after newlines into pieces that are checked and split in parallel; each piece +/// but the last ends with a newline, so the pieces' lines, in order, are the lines of the whole. +fn block_lines(bytes: &[u8]) -> Option> { + let n = bytes.len(); + let mut cuts = vec![0usize]; + for k in 1..SPLIT_PIECES { + let from = (k * n / SPLIT_PIECES).max(*cuts.last().unwrap_or(&0)); + match bytes[from..].iter().position(|&b| b == b'\n') { + Some(p) => cuts.push(from + p + 1), + None => break, + } + } + cuts.push(n); + cuts.dedup(); + let pieces: Vec>> = cuts + .par_windows(2) + .map(|w| { + let text = std::str::from_utf8(&bytes[w[0]..w[1]]).ok()?; + let mut lines = Vec::new(); + push_lines(text, &mut lines); + Some(lines) + }) + .collect(); + let mut lines = Vec::with_capacity(pieces.iter().flatten().map(Vec::len).sum()); + for piece in pieces { + lines.extend(piece?); + } + Some(lines) +} + /// Reads `path`: `on_header` gets its first line, then `on_block` gets the following non-empty /// lines block by block, in file order, with the index of the block's first line among them. /// Lines end as [`std::io::BufRead::lines`] ends them; a file that is not UTF-8 is an error. @@ -74,18 +110,18 @@ pub(crate) fn read_blocks( }); let mut header: Option<_> = Some(on_header); let mut first = 0usize; + let not_utf8 = || err(&"stream did not contain valid UTF-8"); for block in rx { let block = block.map_err(|e| err(&e))?; - let text = std::str::from_utf8(&block) - .map_err(|_| err(&"stream did not contain valid UTF-8"))?; - let mut body = text; + let mut body: &[u8] = █ if let Some(h) = header.take() { - let (line, rest) = text.split_once('\n').unwrap_or((text, "")); + let end = body.iter().position(|&b| b == b'\n'); + let line = std::str::from_utf8(&body[..end.unwrap_or(body.len())]) + .map_err(|_| not_utf8())?; + body = end.map_or(&[][..], |e| &body[e + 1..]); h(line.strip_suffix('\r').unwrap_or(line))?; - body = rest; } - let mut lines: Vec<&str> = Vec::new(); - push_lines(body, &mut lines); + let lines = block_lines(body).ok_or_else(not_utf8)?; on_block(first, &lines)?; first += lines.len(); } @@ -145,6 +181,23 @@ mod tests { assert_eq!(rows, body); } + #[test] + fn parallel_split_gives_the_lines_of_the_whole_block() { + let text: String = (0..5000) + .map(|i| match i % 7 { + 0 => "\n".to_string(), + 1 => format!("r{i}\tx\r\n"), + _ => format!("row {i}\t{}\n", "y".repeat(i % 13)), + }) + .chain(["tail without newline".to_string()]) + .collect(); + let mut want = Vec::new(); + push_lines(&text, &mut want); + assert_eq!(block_lines(text.as_bytes()), Some(want)); + assert_eq!(block_lines(b""), Some(Vec::new())); + assert_eq!(block_lines(b"a\n\xff\nb\n"), None); + } + #[test] fn an_empty_file_is_an_error() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/andes/src/bin/andes/dia/pass2.rs b/crates/andes/src/bin/andes/dia/pass2.rs index 148640702..089ca30d8 100644 --- a/crates/andes/src/bin/andes/dia/pass2.rs +++ b/crates/andes/src/bin/andes/dia/pass2.rs @@ -185,6 +185,59 @@ impl Pass2 { } } +/// The row of the highest pool LLR per (peptidoform, charge, run) among the rows above +/// `NOMINATE_MIN_LLR`, the first such row on ties, as sorted row indices. Without a NaN LLR the +/// rows are ranked by one parallel sort; with one, they are walked in order (a NaN never +/// replaces the best row and is replaced by none). +fn best_rows( + table: &PinTable, + llr: &[f64], + run_of: &(impl Fn(usize) -> usize + Sync), +) -> Vec { + let eligible = |i: usize| { + let r = &table.rows[i]; + !(r.spec == NONE || r.form == NONE || r.charge == 0 || llr[i] <= NOMINATE_MIN_LLR) + }; + let key = |i: usize| { + let r = &table.rows[i]; + (r.form, r.charge, run_of(r.spec as usize)) + }; + let mut want: Vec = if llr.par_iter().any(|v| v.is_nan()) { + let mut best: HashMap<(u32, u8, usize), usize> = HashMap::new(); + for i in (0..table.rows.len()).filter(|&i| eligible(i)) { + let e = best.entry(key(i)).or_insert(i); + if llr[i] > llr[*e] { + *e = i; + } + } + best.into_values().collect() + } else { + let mut rows: Vec<(u32, u8, usize, usize)> = (0..table.rows.len()) + .into_par_iter() + .filter(|&i| eligible(i)) + .map(|i| { + let (form, charge, run) = key(i); + (form, charge, run, i) + }) + .collect(); + rows.par_sort_unstable_by(|a, b| { + (a.0, a.1, a.2) + .cmp(&(b.0, b.1, b.2)) + .then( + llr[b.3] + .partial_cmp(&llr[a.3]) + .unwrap_or(std::cmp::Ordering::Equal), + ) + .then(a.3.cmp(&b.3)) + }); + rows.chunk_by(|a, b| (a.0, a.1, a.2) == (b.0, b.1, b.2)) + .map(|g| g[0].3) + .collect() + }; + want.par_sort_unstable(); + want +} + /// The best pool row of every (run, peptidoform, charge) with `llr` above the nomination /// threshold. `llr` is the pool `dia_llr` of each PIN row of `table`. pub(crate) fn nominate( @@ -204,20 +257,7 @@ pub(crate) fn nominate( table.forms.len() )); } - let mut best: HashMap<(u32, u8, usize), usize> = HashMap::new(); - for (i, r) in table.rows.iter().enumerate() { - if r.spec == NONE || r.form == NONE || r.charge == 0 || llr[i] <= NOMINATE_MIN_LLR { - continue; - } - let e = best - .entry((r.form, r.charge, run_of(r.spec as usize))) - .or_insert(i); - if llr[i] > llr[*e] { - *e = i; - } - } - let mut want: Vec = best.into_values().collect(); - want.sort_unstable(); + let want = best_rows(table, llr, &run_of); predicted.keep_only(want.iter().map(|&i| (table.rows[i].form, table.rows[i].charge))); crate::memory::release_free_memory(); let predicted = &*predicted; diff --git a/crates/andes/src/bin/andes/dia/pin.rs b/crates/andes/src/bin/andes/dia/pin.rs index 1717e23a1..f8e742581 100644 --- a/crates/andes/src/bin/andes/dia/pin.rs +++ b/crates/andes/src/bin/andes/dia/pin.rs @@ -2,12 +2,12 @@ //! label and score. Lines are parsed in parallel blocks; peptidoforms are numbered in the order //! they first appear. -use std::collections::HashMap; use std::path::Path; use model::Spectrum; use onnx_infer::predictors::form::{parse_peptide, Form, Mass}; use rayon::prelude::*; +use rustc_hash::FxHashMap; use crate::dia::rt::{locate, row_charge, spectrum_bases, PinRow, PinTable, NONE}; @@ -19,8 +19,8 @@ pub(crate) fn read_pin( let layout: std::cell::OnceCell = std::cell::OnceCell::new(); let bases = spectrum_bases(spectra); let mut forms: Vec<(Form, Mass)> = Vec::new(); - let mut form_ix: HashMap = HashMap::new(); - let mut by_peptide: HashMap = HashMap::new(); + let mut form_ix: FxHashMap = FxHashMap::default(); + let mut by_peptide: FxHashMap = FxHashMap::default(); let mut rows = Vec::new(); let mut unlocated = 0usize; crate::dia::blocks::read_blocks( @@ -42,10 +42,14 @@ pub(crate) fn read_pin( for r in parsed { block.push(r?); } + let known: Vec = block + .par_iter() + .map(|r| by_peptide.contains_key(r.peptide)) + .collect(); let mut fresh: Vec<&str> = Vec::new(); - let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); - for r in &block { - if !by_peptide.contains_key(r.peptide) && seen.insert(r.peptide) { + let mut seen: rustc_hash::FxHashSet<&str> = rustc_hash::FxHashSet::default(); + for (r, _) in block.iter().zip(&known).filter(|(_, &k)| !k) { + if seen.insert(r.peptide) { fresh.push(r.peptide); } } @@ -60,13 +64,17 @@ pub(crate) fn read_pin( }); by_peptide.insert((*p).to_string(), f); } - rows.reserve(block.len()); - for r in block { - unlocated += usize::from(r.row.spec == NONE); - let mut row = r.row; - row.form = by_peptide.get(r.peptide).copied().unwrap_or(NONE); - rows.push(row); - } + unlocated += block.iter().filter(|r| r.row.spec == NONE).count(); + let by_peptide = &by_peptide; + let located: Vec = block + .into_par_iter() + .map(|r| { + let mut row = r.row; + row.form = by_peptide.get(r.peptide).copied().unwrap_or(NONE); + row + }) + .collect(); + rows.extend(located); Ok(()) }, )?; @@ -161,7 +169,7 @@ impl PinLayout { pin: &Path, row: usize, line: &'a str, - bases: &HashMap, + bases: &FxHashMap, spectra: &[Spectrum], ) -> Result, String> { let x: Vec<&str> = line.split('\t').collect(); diff --git a/crates/andes/src/bin/andes/dia/qvalue.rs b/crates/andes/src/bin/andes/dia/qvalue.rs new file mode 100644 index 000000000..401fcef43 --- /dev/null +++ b/crates/andes/src/bin/andes/dia/qvalue.rs @@ -0,0 +1,321 @@ +//! Precursor-level q-values for DIA: target-decoy competition over each precursor's best row, overall and per class. + +use super::*; + +/// Reports precursor-level q-values for DIA: target-decoy competition over the best +/// Percolator score of each precursor (run, peptide form, charge), with q = (D + 1) / T +/// and monotone in the score. A row receives the q of the threshold at its own score, so +/// keeping rows with q <= x keeps the precursors whose best row passes, at precursor FDR x. +/// Rows Percolator did not report keep no entry. Returns the precursor counts (targets, +/// decoys, target precursors at q <= 0.01) and the best `(score, is decoy)` of every precursor, +/// for comparing the run's precursor-level target-decoy curve at other q-values. A precursor +/// PIN (one with the `score::PRESENT_COLUMN` column) is keyed by its Peptide string and +/// charge columns and needs no spectra. With `interference` (--dia-interference) and a PSM +/// PIN, [`interference_removed`] drops precursors from the competition first; their target rows +/// get q = 1. +pub(crate) fn precursor_q( + pin: &Path, + spectra: &[Spectrum], + targets: &mut HashMap, + decoys: &HashMap, + interference: Option, +) -> Result { + let header = { + use std::io::BufRead; + let f = std::fs::File::open(pin).map_err(|e| format!("{}: {e}", pin.display()))?; + std::io::BufReader::new(f) + .lines() + .find(|l| !matches!(l, Ok(l) if l.is_empty())) + .transpose() + .map_err(|e| format!("{}: {e}", pin.display()))? + .unwrap_or_default() + }; + let h: Vec<&str> = header.split('\t').collect(); + let at = |n: &str| { + h.iter() + .position(|c| *c == n) + .ok_or_else(|| format!("{}: PIN has no {n} column", pin.display())) + }; + let (c_id, c_pep, c_label) = (at("SpecId")?, at("Peptide")?, at("Label")?); + let c_file = h.iter().position(|c| *c == "FileName"); + let charge_cols: Vec<(usize, u8)> = h + .iter() + .enumerate() + .filter_map(|(i, c)| Some((i, c.strip_prefix("charge")?.parse().ok()?))) + .collect(); + let table = if h.contains(&crate::dia::score::PRESENT_COLUMN) { + None + } else { + Some(read_pin(pin, spectra, &[])?) + }; + let mut keys: HashMap<(String, String, u8), u32> = HashMap::new(); + let mut rows: Vec<(u32, f64, bool, String)> = Vec::new(); + let mut raw: Vec<(String, String, u8)> = Vec::new(); + let mut line_of: Vec = Vec::new(); + type Parsed<'a> = Option<(bool, String, u8, &'a str, f64, &'a str, &'a str, usize)>; + let targets_ro: &HashMap = targets; + crate::dia::blocks::read_blocks( + pin, + |_| Ok(()), + |first, lines| { + let parsed: Vec, String>> = lines + .par_iter() + .enumerate() + .map(|(j, line)| { + let i = first + j; + let x: Vec<&str> = line.split('\t').collect(); + if x.len() <= c_pep.max(c_label).max(c_id) { + return Err(format!("{}: short PIN row {}", pin.display(), i + 2)); + } + let (decoy, peptide, charge) = match &table { + Some(t) => { + let r = t.rows.get(i).ok_or_else(|| { + format!("{}: row {} not read", pin.display(), i + 2) + })?; + let peptide = if r.form == NONE { + x[c_pep].to_string() + } else { + format!("#{}", r.form) + }; + (r.decoy, peptide, r.charge) + } + None => ( + x[c_label].trim() == "-1", + x[c_pep].to_string(), + charge_cols + .iter() + .find(|(c, _)| x.get(*c) == Some(&"1")) + .map_or(0, |c| c.1), + ), + }; + let id = x[c_id]; + let psm = if decoy { + decoys.get(id) + } else { + targets_ro.get(id) + }; + let Some(score) = psm.and_then(|p| p.score) else { + return Ok(None); + }; + Ok(Some(( + decoy, + peptide, + charge, + id, + score, + c_file.map_or("", |i| x[i]), + x[c_pep], + i, + ))) + }) + .collect(); + for p in parsed { + let Some((decoy, peptide, charge, id, score, run, raw_pep, i)) = p? else { + continue; + }; + let n = keys.len() as u32; + let k = *keys.entry((run.to_string(), peptide, charge)).or_insert(n); + raw.push((run.to_string(), raw_pep.to_string(), charge)); + rows.push((k, score, decoy, id.to_string())); + line_of.push(i); + } + Ok(()) + }, + )?; + let removed = match (&table, interference) { + (Some(t), Some(choice)) => { + let q0 = precursor_q_values(keys.len(), &rows); + removed_keys(&keys, &rows, &line_of, &q0, t, spectra, choice) + } + _ => vec![false; keys.len()], + }; + for (k, _, decoy, id) in &rows { + if removed[*k as usize] && !*decoy { + if let Some(p) = targets.get_mut(id) { + p.q_value = 1.0; + } + } + } + let removed_precursors = rows + .iter() + .zip(raw) + .filter(|(r, _)| removed[r.0 as usize]) + .map(|(_, n)| n) + .collect(); + rows.retain(|r| !removed[r.0 as usize]); + let q = precursor_q_values(keys.len(), &rows); + let n_targets = q.iter().filter(|p| p.is_some_and(|p| !p.1)).count(); + let n_decoys = q.iter().filter(|p| p.is_some_and(|p| p.1)).count(); + let passing = q.iter().flatten().filter(|p| !p.1 && p.2 <= 0.01).count(); + let curve = q_curve(&q); + for (_, score, decoy, id) in &rows { + if *decoy { + continue; + } + if let Some(p) = targets.get_mut(id) { + p.q_value = curve_at(&curve, *score); + } + } + let best = q.iter().flatten().map(|p| (p.0, p.1)).collect(); + Ok(((n_targets, n_decoys, passing), best, removed_precursors)) +} + +/// Best score of each precursor and its precursor-level q: `(best score, is decoy, q)`, +/// `None` for a key no row reached. Ties in score count decoys first. +pub(super) fn precursor_q_values( + n_keys: usize, + rows: &[(u32, f64, bool, String)], +) -> Vec> { + let mut best: Vec> = vec![None; n_keys]; + for (k, score, decoy, _) in rows { + let b = &mut best[*k as usize]; + if b.is_none_or(|(s, _)| *score > s) { + *b = Some((*score, *decoy)); + } + } + let mut order: Vec = (0..n_keys).filter(|&i| best[i].is_some()).collect(); + order.sort_by(|&a, &b| { + let (sa, da) = best[a].unwrap_or((f64::NEG_INFINITY, true)); + let (sb, db) = best[b].unwrap_or((f64::NEG_INFINITY, true)); + sb.total_cmp(&sa).then(db.cmp(&da)) + }); + let mut q = vec![1.0f64; n_keys]; + let (mut t, mut d) = (0usize, 0usize); + let mut i = 0; + while i < order.len() { + let s = best[order[i]].map_or(f64::NEG_INFINITY, |b| b.0); + let mut j = i; + while j < order.len() && best[order[j]].map_or(f64::NEG_INFINITY, |b| b.0) == s { + if best[order[j]].is_some_and(|b| b.1) { + d += 1; + } else { + t += 1; + } + j += 1; + } + let fdr = ((d + 1) as f64 / t.max(1) as f64).min(1.0); + for &k in &order[i..j] { + q[k] = fdr; + } + i = j; + } + let mut running = 1.0f64; + for &k in order.iter().rev() { + running = running.min(q[k]); + q[k] = running; + } + best.iter() + .zip(q) + .map(|(b, qv)| b.map(|(s, d)| (s, d, qv))) + .collect() +} + +/// Score thresholds in descending order with the precursor q at each. +pub(super) fn q_curve(q: &[Option<(f64, bool, f64)>]) -> Vec<(f64, f64)> { + let mut c: Vec<(f64, f64)> = q.iter().flatten().map(|p| (p.0, p.2)).collect(); + c.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.total_cmp(&b.1))); + c +} + +/// The precursor q a row with this score gets: the q of the lowest precursor best score +/// that is still at or above it; 1 below every precursor. +pub(super) fn curve_at(curve: &[(f64, f64)], score: f64) -> f64 { + let n = curve.partition_point(|p| p.0 >= score); + if n == 0 { + 1.0 + } else { + curve[n - 1].1 + } +} + +/// Precursor-level q of every row computed within its class only: one target-decoy competition +/// per class (rows of class `false` against each other, rows of class `true` against each +/// other), with the rules of [`precursor_q`]. Returns the q of each row, 1 for a row whose +/// class holds no precursor at or above its score. +pub(crate) fn classwise_q_values( + n_keys: usize, + rows: &[(u32, f64, bool, String)], + class: &[bool], +) -> Vec { + let mut q = vec![1.0; rows.len()]; + for c in [false, true] { + let idx: Vec = (0..rows.len()).filter(|&i| class[i] == c).collect(); + let sub: Vec<(u32, f64, bool, String)> = idx.iter().map(|&i| rows[i].clone()).collect(); + let curve = q_curve(&precursor_q_values(n_keys, &sub)); + for &i in &idx { + q[i] = curve_at(&curve, rows[i].1); + } + } + q +} + +/// Replaces the targets' q-values of a precursor PIN by the class-wise q +/// ([`classwise_q_values`], classes by `class_col` 0 or 1) and counts the target precursors at +/// q <= 0.01 by class under the pooled q they had and under the class-wise q. Returns +/// `[[pooled class 0, pooled class 1], [class-wise class 0, class-wise class 1]]`. +pub(crate) fn precursor_q_by_class( + pin: &Path, + class_col: &str, + targets: &mut HashMap, + decoys: &HashMap, +) -> Result<[[usize; 2]; 2], String> { + let err = |e: &dyn std::fmt::Display| format!("{}: {e}", pin.display()); + let f = std::fs::File::open(pin).map_err(|e| err(&e))?; + let mut lines = std::io::BufRead::lines(std::io::BufReader::new(f)); + let header = lines + .next() + .ok_or_else(|| err(&"empty PIN"))? + .map_err(|e| err(&e))?; + let h: Vec<&str> = header.split('\t').collect(); + let at = |n: &str| { + h.iter() + .position(|c| *c == n) + .ok_or_else(|| format!("{}: PIN has no {n} column", pin.display())) + }; + let (c_id, c_pep, c_label, c_class) = (at("SpecId")?, at("Peptide")?, at("Label")?, at(class_col)?); + let charge_cols: Vec<(usize, u8)> = h + .iter() + .enumerate() + .filter_map(|(i, c)| Some((i, c.strip_prefix("charge")?.parse().ok()?))) + .collect(); + let mut keys: HashMap<(String, u8), u32> = HashMap::new(); + let mut rows: Vec<(u32, f64, bool, String)> = Vec::new(); + let mut class: Vec = Vec::new(); + for line in lines { + let line = line.map_err(|e| err(&e))?; + if line.is_empty() { + continue; + } + let x: Vec<&str> = line.split('\t').collect(); + if x.len() <= c_pep.max(c_label).max(c_id).max(c_class) { + return Err(err(&"short PIN row")); + } + let decoy = x[c_label].trim() == "-1"; + let psm = if decoy { decoys.get(x[c_id]) } else { targets.get(x[c_id]) }; + let Some(score) = psm.and_then(|p| p.score) else { + continue; + }; + let charge = charge_cols + .iter() + .find(|(c, _)| x.get(*c) == Some(&"1")) + .map_or(0, |c| c.1); + let n = keys.len() as u32; + let k = *keys.entry((x[c_pep].to_string(), charge)).or_insert(n); + rows.push((k, score, decoy, x[c_id].to_string())); + class.push(x[c_class].trim().parse::().unwrap_or(0.0) > 0.5); + } + let q = classwise_q_values(keys.len(), &rows, &class); + let mut counts = [[0usize; 2]; 2]; + for (i, (_, _, decoy, id)) in rows.iter().enumerate() { + if *decoy { + continue; + } + let c = usize::from(class[i]); + if let Some(p) = targets.get_mut(id) { + counts[0][c] += usize::from(p.q_value <= 0.01); + counts[1][c] += usize::from(q[i] <= 0.01); + p.q_value = q[i]; + } + } + Ok(counts) +} diff --git a/crates/andes/src/bin/andes/dia/rt.rs b/crates/andes/src/bin/andes/dia/rt.rs index acc25b881..d3e566cef 100644 --- a/crates/andes/src/bin/andes/dia/rt.rs +++ b/crates/andes/src/bin/andes/dia/rt.rs @@ -7,6 +7,7 @@ use std::sync::Mutex; use std::time::Instant; use rayon::prelude::*; +use rustc_hash::FxHashMap; use model::stats::{median_mut, Even}; @@ -63,7 +64,7 @@ struct Source { /// per cleavage site and ion of `ions`, site-major. pub(crate) struct PredictedMs2 { pub(crate) ions: Vec, - pair: HashMap<(u32, u8), u32>, + pair: FxHashMap<(u32, u8), u32>, values: Vec>, /// The andes-rt source's raw (uncalibrated) prediction of every peptidoform of the PIN /// table, by form id (NaN where it has none); empty without that source. @@ -406,7 +407,7 @@ impl Predictors { )); run_cals.push(cal.clone()); if let Some(c) = cal { - let fold_of: HashMap = anchor_pts + let fold_of: FxHashMap = anchor_pts .iter() .map(|&(i, _, _)| (i, rt_fold(&table.rows[i]))) .collect(); @@ -538,24 +539,30 @@ impl Predictors { ) -> Result<(Vec>, String), String> { let pred = src.pred.as_ref(); let forms = &table.forms; - let mut fz_ix: HashMap<(u32, u8), u32> = HashMap::new(); + let located = |r: &PinRow| r.form != NONE && r.spec != NONE && r.charge != 0; + let no_peaks = table + .rows + .par_iter() + .filter(|r| located(r) && spectra[r.spec as usize].peaks.is_empty()) + .count(); + let wanted: Vec = table + .rows + .par_iter() + .map(|r| { + located(r) + && !spectra[r.spec as usize].peaks.is_empty() + && pred.supports_ms2(&forms[r.form as usize].0, r.charge) + }) + .collect(); + let mut fz_ix: FxHashMap<(u32, u8), u32> = FxHashMap::default(); let mut fz: Vec<(u32, u8)> = Vec::new(); - let mut no_peaks = 0usize; - for r in &table.rows { - if r.form == NONE || r.spec == NONE || r.charge == 0 { - continue; - } - if spectra[r.spec as usize].peaks.is_empty() { - no_peaks += 1; - continue; - } - if pred.supports_ms2(&forms[r.form as usize].0, r.charge) { - fz_ix.entry((r.form, r.charge)).or_insert_with(|| { - fz.push((r.form, r.charge)); - (fz.len() - 1) as u32 - }); - } + for (r, _) in table.rows.iter().zip(&wanted).filter(|(_, &w)| w) { + fz_ix.entry((r.form, r.charge)).or_insert_with(|| { + fz.push((r.form, r.charge)); + (fz.len() - 1) as u32 + }); } + drop(wanted); let mut row_start = vec![0u32; fz.len() + 1]; let fz_of_row = prediction_of_rows(&table.rows, spectra, &fz_ix); let fz_ix = keep.is_some().then_some(fz_ix); @@ -684,9 +691,9 @@ const ANDES_RT_PREFIX: &str = "andesrt"; fn prediction_of_rows( rows: &[PinRow], spectra: &[Spectrum], - fz_ix: &HashMap<(u32, u8), u32>, + fz_ix: &FxHashMap<(u32, u8), u32>, ) -> Vec { - rows.iter() + rows.par_iter() .map(|r| { if r.spec == NONE || spectra[r.spec as usize].peaks.is_empty() { return NONE; @@ -710,8 +717,9 @@ pub(crate) struct PinTable { pub(super) peptide_col: usize, } -pub(super) fn spectrum_bases(spectra: &[Spectrum]) -> HashMap { - let mut m: HashMap = HashMap::with_capacity(spectra.len()); +pub(super) fn spectrum_bases(spectra: &[Spectrum]) -> FxHashMap { + let mut m: FxHashMap = + FxHashMap::with_capacity_and_hasher(spectra.len(), Default::default()); for (i, s) in spectra.iter().enumerate() { let scan = s.scan.unwrap_or(0); let base = if s.title.is_empty() { @@ -725,7 +733,7 @@ pub(super) fn spectrum_bases(spectra: &[Spectrum]) -> HashMap { } pub(super) fn locate( - bases: &HashMap, + bases: &FxHashMap, spectra: &[Spectrum], spec_id: &str, scan: i32, @@ -823,7 +831,7 @@ pub(crate) fn anchor_rows( n_runs: usize, run_of: &dyn Fn(u32) -> usize, ) -> Vec> { - let mut best: HashMap = HashMap::new(); + let mut best: FxHashMap = FxHashMap::default(); for (i, r) in rows.iter().enumerate() { if r.spec == NONE { continue; @@ -1124,7 +1132,7 @@ mod tests { score: 0.0, }; let rows = [row(0, 7), row(NONE, 7), row(1, 7), row(0, 8)]; - let fz_ix = HashMap::from([((7u32, 2u8), 0u32)]); + let fz_ix = FxHashMap::from_iter([((7u32, 2u8), 0u32)]); assert_eq!( prediction_of_rows(&rows, &spectra, &fz_ix), [0, NONE, NONE, NONE] diff --git a/crates/andes/src/bin/andes/dia/score.rs b/crates/andes/src/bin/andes/dia/score.rs index f57c25ba1..442890ecd 100644 --- a/crates/andes/src/bin/andes/dia/score.rs +++ b/crates/andes/src/bin/andes/dia/score.rs @@ -263,7 +263,7 @@ pub(crate) fn learned_score( /// own nominees (their SpecIds are pass-1 SpecIds). struct Pass1 { names: Vec, - rows: HashMap<(String, String, u8), Vec>, + rows: rustc_hash::FxHashMap<(String, String, u8), Vec>, run_file: HashMap, } @@ -281,7 +281,7 @@ impl Pass1 { } /// Reads the pass-1 PIN. `own` maps the SpecId of every pass-2 row to its run. -fn read_pass1(pin: &Path, own: &HashMap<&str, u32>) -> Result { +fn read_pass1(pin: &Path, own: &rustc_hash::FxHashMap<&str, u32>) -> Result { let err = |e: &dyn std::fmt::Display| format!("{}: {e}", pin.display()); struct Layout { c_pep: usize, @@ -292,7 +292,8 @@ fn read_pass1(pin: &Path, own: &HashMap<&str, u32>) -> Result { names: Vec, } let layout: std::cell::OnceCell = std::cell::OnceCell::new(); - let mut rows: HashMap<(String, String, u8), Vec> = HashMap::new(); + let mut rows: rustc_hash::FxHashMap<(String, String, u8), Vec> = + rustc_hash::FxHashMap::default(); let mut run_file: HashMap = HashMap::new(); crate::dia::blocks::read_blocks( pin, @@ -323,7 +324,7 @@ fn read_pass1(pin: &Path, own: &HashMap<&str, u32>) -> Result { let Some(l) = layout.get() else { return Err(err(&"empty PIN")); }; - type Parsed<'a> = (&'a str, &'a str, &'a str, u8, Vec); + type Parsed<'a> = (&'a str, &'a str, (String, String, u8), Vec); let parsed: Vec>> = lines .par_iter() .map(|line| { @@ -343,12 +344,12 @@ fn read_pass1(pin: &Path, own: &HashMap<&str, u32>) -> Result { .map(|&i| x[i].trim().parse::().unwrap_or(f32::NAN)) .map(|v| if v.is_finite() { v } else { 0.0 }) .collect(); - Some((x[0], file, x[l.c_pep], z, v)) + Some((x[0], file, (file.to_string(), x[l.c_pep].to_string(), z), v)) }) .collect(); let llr = |v: &[f32]| l.c_llr.map_or(MISSING_DIA_LLR, |k| v[k]); for p in parsed { - let Some((id, file, pep, z, v)) = p else { + let Some((id, file, k, v)) = p else { return Err(err(&"short PIN row")); }; if let Some(&run) = own.get(id) { @@ -365,7 +366,6 @@ fn read_pass1(pin: &Path, own: &HashMap<&str, u32>) -> Result { } } } - let k = (file.to_string(), pep.to_string(), z); match rows.get_mut(&k) { Some(old) if llr(old) >= llr(&v) => {} Some(old) => *old = v, @@ -489,7 +489,7 @@ pub(crate) fn write_precursor_pin_with( learned: Option, ) -> Result { let t0 = std::time::Instant::now(); - let own: HashMap<&str, u32> = t + let own: rustc_hash::FxHashMap<&str, u32> = t .spec_id .iter() .zip(&t.run) @@ -783,7 +783,7 @@ mod tests { features: Vec::new(), ..Default::default() }; - let own: HashMap<&str, u32> = + let own: rustc_hash::FxHashMap<&str, u32> = t.spec_id.iter().zip(&t.run).map(|(s, &r)| (s.as_str(), r)).collect(); let p1 = read_pass1(&pin, &own).unwrap(); assert_eq!(p1.names, ["p1_dia_llr", "p1_x"]); diff --git a/crates/andes/src/bin/andes/search/finish.rs b/crates/andes/src/bin/andes/search/finish.rs index 523431f5a..016cd7246 100644 --- a/crates/andes/src/bin/andes/search/finish.rs +++ b/crates/andes/src/bin/andes/search/finish.rs @@ -714,6 +714,7 @@ pub(super) fn write_pin_and_rescore( crate::memory::mark_stage("pass 2"); } } + let early_learned = rescoring::start_learned(&cli, &mut dia_pass2); if cli.dia { crate::memory::release_free_memory(); } @@ -775,6 +776,7 @@ pub(super) fn write_pin_and_rescore( }, &mut spectra, &mut dia_pass2, + early_learned, )?; let rescoring::Rescoring { rescore_map, diff --git a/crates/andes/src/bin/andes/search/rescoring.rs b/crates/andes/src/bin/andes/search/rescoring.rs index aa50d3f27..db0ccdf01 100644 --- a/crates/andes/src/bin/andes/search/rescoring.rs +++ b/crates/andes/src/bin/andes/search/rescoring.rs @@ -35,11 +35,50 @@ pub(super) struct Rescoring { pub(super) dia_precursor_ids: std::collections::HashSet, } +/// The DIA precursor learned score trained beside the steps before rescoring, and the pass-2 +/// table it was trained on. +pub(super) type EarlyLearned = + std::thread::JoinHandle<(output::dia::pass2::Pass2Table, crate::dia::score::Learned)>; + +/// The Percolator arguments of the run: `--percolator-args`, on DIA with the default train FDR. +fn user_args(cli: &Cli) -> Vec { + let mut args: Vec = cli + .percolator_args + .split_whitespace() + .map(|s| s.to_string()) + .collect(); + if cli.dia { + crate::dia::default_train_fdr(&mut args); + } + args +} + +/// Starts the DIA precursor learned score on its own thread as soon as pass 2 has its table, +/// when rescoring will use it (`--rescore`, DIA, no `--quant-dir`): the table moves into the +/// thread and comes back with the score when [`rescore_pin`] joins it. The score depends only +/// on the table and the seed, so it is the one [`rescore_pin`] would train itself. +pub(super) fn start_learned( + cli: &Cli, + dia_pass2: &mut Option, +) -> Option { + if !(cli.rescore && cli.dia && cli.quant_dir.is_none()) { + return None; + } + let t = dia_pass2.take()?; + let seed = crate::dia::score::percolator_seed(&user_args(cli)); + Some(std::thread::spawn(move || { + let learned = crate::dia::score::learn(&t, &[], seed); + (t, learned) + })) +} + /// Rescores the search's PIN when `--rescore` is set; takes `dia_pass2` when it is used. +/// `early` is the learned score [`start_learned`] started, joined after pass 1. pub(super) fn rescore_pin( inputs: &RescoreInputs<'_>, spectra: &mut [Spectrum], dia_pass2: &mut Option, + early: Option, ) -> Result> { let RescoreInputs { cli, @@ -73,14 +112,7 @@ pub(super) fn rescore_pin( .map_err(|e| format!("{e}"))? }; log::info!(target: "rescore", "Percolator backend = {}", backend.describe()); - let mut user_args: Vec = cli - .percolator_args - .split_whitespace() - .map(|s| s.to_string()) - .collect(); - if cli.dia { - crate::dia::default_train_fdr(&mut user_args); - } + let user_args = user_args(cli); let extra = output::percolator_args_with_threads(&user_args, cli.threads); let t_resc = std::time::Instant::now(); if cli.dia && free_peaks { @@ -90,21 +122,18 @@ pub(super) fn rescore_pin( crate::memory::release_free_memory(); } let seed = crate::dia::score::percolator_seed(&user_args); - let early = dia_pass2 - .as_ref() - .filter(|_| cli.dia && cli.quant_dir.is_none()); - let (pass1, learned) = std::thread::scope(|sc| -> Result<_, String> { - let job = early.map(|t| sc.spawn(move || crate::dia::score::learn(t, &[], seed))); - let pass1 = rescore_pass1(cli, output_pin_path, spectra, &backend, &extra); - let learned = match job { - Some(h) => Some( - h.join() - .map_err(|_| "the precursor learned score panicked".to_string())?, - ), - None => None, - }; - Ok((pass1?, learned)) - })?; + let pass1 = rescore_pass1(cli, output_pin_path, spectra, &backend, &extra); + let learned = match early { + Some(h) => { + let (t, learned) = h + .join() + .map_err(|_| "the precursor learned score panicked".to_string())?; + *dia_pass2 = Some(t); + Some(learned) + } + None => None, + }; + let pass1 = pass1?; let Pass1 { targets: mut map, decoy_ids: mut decoys, diff --git a/crates/model-train/src/gbdt/tree.rs b/crates/model-train/src/gbdt/tree.rs index 13ca03e47..29cfae596 100644 --- a/crates/model-train/src/gbdt/tree.rs +++ b/crates/model-train/src/gbdt/tree.rs @@ -4,7 +4,8 @@ use scoring_crate::gbdt::Tree; /// Nodes with fewer rows than this build their histograms on the calling thread. const PAR_MIN_ROWS: usize = 4096; -/// Features per histogram task: each task reads a node's gradients once for its block. +/// Most features per histogram task: each task reads a node's gradients once for its block. +/// Fewer features share a task when the blocks would not give every thread one. const FEATURE_BLOCK: usize = 4; pub struct TreeParams { @@ -129,8 +130,9 @@ impl<'a> Builder<'a> { fn histograms(&self, rows: &[usize]) -> Vec { let nf = self.params.n_features; let nb = self.params.n_bins; + let per_task = (nf / rayon::current_num_threads().max(1)).clamp(1, FEATURE_BLOCK); let block = |first: usize| -> Vec { - let feats = first..(first + FEATURE_BLOCK).min(nf); + let feats = first..(first + per_task).min(nf); let cols: Vec<&[u8]> = feats.clone().map(|f| self.col(f)).collect(); let mut hists: Vec = feats.map(|_| BinHist::new(nb)).collect(); for &r in rows { @@ -141,7 +143,7 @@ impl<'a> Builder<'a> { } hists }; - let firsts: Vec = (0..nf).step_by(FEATURE_BLOCK).collect(); + let firsts: Vec = (0..nf).step_by(per_task).collect(); if rows.len() < PAR_MIN_ROWS { firsts.into_iter().flat_map(block).collect() } else { diff --git a/crates/output/src/fdr/class.rs b/crates/output/src/fdr/class.rs index 4594df128..c2e5b3214 100644 --- a/crates/output/src/fdr/class.rs +++ b/crates/output/src/fdr/class.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet}; use model::fdr::{ranked_q, Counts, Eval}; use model::EntryKind; +use rayon::prelude::*; use search::SearchIndex; use crate::percolator::PercolatorPsm; @@ -80,7 +81,7 @@ impl Cutoffs { .map(|p| (p.accession.as_str(), p.entry_kind())) .collect(); let variant_rows = targets - .iter() + .par_iter() .filter(|(_, p)| class_of(&p.proteins, &kinds) == "variant") .map(|(id, _)| id.clone()) .collect(); @@ -130,24 +131,22 @@ pub fn apply_class_fdr( .map(|p| (p.accession.as_str(), p.entry_kind())) .collect(); let rank = |p: &PercolatorPsm| p.score.unwrap_or(-p.q_value); + let classes = |rows: &HashMap| -> Vec<(String, f64)> { + let psms: Vec<&PercolatorPsm> = rows.values().collect(); + psms.par_iter() + .map(|p| (class_of(&p.proteins, &kinds), rank(p))) + .collect() + }; let mut by_class: HashMap = HashMap::new(); - for (i, p) in targets.values().enumerate() { - by_class - .entry(class_of(&p.proteins, &kinds)) - .or_default() - .0 - .push((rank(p), i)); + for (i, (class, r)) in classes(targets).into_iter().enumerate() { + by_class.entry(class).or_default().0.push((r, i)); } - for p in decoys.values() { - by_class - .entry(class_of(&p.proteins, &kinds)) - .or_default() - .1 - .push(rank(p)); + for (class, r) in classes(decoys) { + by_class.entry(class).or_default().1.push(r); } let single = by_class.len() < 2; let mut pooled: Vec = decoys.values().map(rank).collect(); - pooled.sort_by(f64::total_cmp); + pooled.par_sort_unstable_by(f64::total_cmp); let n = pooled.len(); let p_of = |s: f64| -> f64 { let ge = n - pooled.partition_point(|&x| x < s); diff --git a/crates/output/src/protein/inference.rs b/crates/output/src/protein/inference.rs index 9e8a07d9d..6a8dbb814 100644 --- a/crates/output/src/protein/inference.rs +++ b/crates/output/src/protein/inference.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use model::fdr::{ranked_q, Counts, Eval}; use model::{EntryKind, Protein}; +use rayon::prelude::*; use search::SearchIndex; use crate::percolator::PercolatorPsm; @@ -249,34 +250,40 @@ pub fn infer_protein_groups( }; let knockoff = |acc: &str| proteins.get(acc).is_some_and(|p| p.is_knockoff()); let rows = |map: &HashMap, decoy: bool| { + let psms: Vec<&PercolatorPsm> = map.values().collect(); + let found: Vec)>> = psms + .par_iter() + .map(|p| { + let score = p.score?; + let fams: BTreeSet = p + .proteins + .split(';') + .filter(|a| !a.is_empty()) + .filter(|a| decoy || !idx.is_decoy_accession(a)) + .map(|a| if decoy { target_of(a) } else { a.to_string() }) + .filter(|a| !knockoff(a)) + .map(|a| family_of(&a)) + .collect(); + (!fams.is_empty()).then(|| (bare_sequence(&p.peptide), score, fams)) + }) + .collect(); let mut best: HashMap)> = HashMap::new(); - for p in map.values() { - let Some(score) = p.score else { continue }; - let fams: BTreeSet = p - .proteins - .split(';') - .filter(|a| !a.is_empty()) - .filter(|a| decoy || !idx.is_decoy_accession(a)) - .map(|a| if decoy { target_of(a) } else { a.to_string() }) - .filter(|a| !knockoff(a)) - .map(|a| family_of(&a)) - .collect(); - if fams.is_empty() { - continue; - } + for (pep, score, fams) in found.into_iter().flatten() { let e = best - .entry(bare_sequence(&p.peptide)) + .entry(pep) .or_insert_with(|| (f64::NEG_INFINITY, BTreeSet::new())); e.0 = e.0.max(score); e.1.extend(fams); } let mut out: Vec<(String, f64, BTreeSet)> = best.into_iter().map(|(pep, (s, f))| (pep, s, f)).collect(); - out.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.total_cmp(&a.1))); + out.par_sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.total_cmp(&a.1))); out }; - let target = parsimony(rows(targets, false)); - let decoy = parsimony(rows(decoys, true)); + let (target, decoy) = rayon::join( + || parsimony(rows(targets, false)), + || parsimony(rows(decoys, true)), + ); let member = |s: &Side| -> HashMap { let mut m = s.family_group.clone(); diff --git a/crates/rescore/src/svm.rs b/crates/rescore/src/svm.rs index f10f5059c..bb61586e6 100644 --- a/crates/rescore/src/svm.rs +++ b/crates/rescore/src/svm.rs @@ -774,6 +774,13 @@ fn each_row(m: usize, sc: Option<&Screen<'_>>, mut f: impl FnMut(usize)) { } } +/// A line-search breakpoint: the step at which a row's loss changes, the row, and the sign of +/// the change. +type Breakpoint = (f64, usize, f64); + +/// One chunk of rows' line-search slope terms and breakpoints, in row order. +type RowTerms = (Vec<(f64, f64)>, Vec); + #[allow(clippy::too_many_arguments)] fn line_search( t: &Train, @@ -795,20 +802,38 @@ fn line_search( let mut l = lambda * omega_l; let mut r = lambda * omega_r; deltas.clear(); - each_row(t.len(), sc, |i| { + let visit = |i: usize, terms: &mut Vec<(f64, f64)>, found: &mut Vec| { let y = t.y(i); let diff = y * (o_bar[i] - o[i]); if y * o[i] < 1.0 { let d2 = t.c(i) * (o_bar[i] - o[i]); - l += (o[i] - y) * d2; - r += (o_bar[i] - y) * d2; + terms.push(((o[i] - y) * d2, (o_bar[i] - y) * d2)); if diff > 0.0 { - deltas.push(((1.0 - y * o[i]) / diff, i, -1.0)); + found.push(((1.0 - y * o[i]) / diff, i, -1.0)); } } else if diff < 0.0 { - deltas.push(((1.0 - y * o[i]) / diff, i, 1.0)); + found.push(((1.0 - y * o[i]) / diff, i, 1.0)); } - }); + }; + let n = sc.map_or(t.len(), |sc| sc.live.len()); + let row = |k: usize| sc.map_or(k, |sc| sc.live[k] as usize); + let parts: Vec = (0..n.div_ceil(CHUNK)) + .into_par_iter() + .map(|c| { + let (mut terms, mut found) = (Vec::new(), Vec::new()); + for k in c * CHUNK..((c + 1) * CHUNK).min(n) { + visit(row(k), &mut terms, &mut found); + } + (terms, found) + }) + .collect(); + for (terms, found) in parts { + for (dl, dr) in terms { + l += dl; + r += dr; + } + deltas.extend(found); + } if deltas.len() >= PAR_SORT_MIN { deltas.par_sort_by(|a, b| a.0.total_cmp(&b.0)); } else { diff --git a/crates/scoring/src/gbdt.rs b/crates/scoring/src/gbdt.rs index f4eebfb34..68694b8ba 100644 --- a/crates/scoring/src/gbdt.rs +++ b/crates/scoring/src/gbdt.rs @@ -308,8 +308,9 @@ mod simd { use std::arch::x86_64::*; const BLOCK: usize = 256; + const LANES: usize = 8; const GROUPS: usize = 4; - const STEP: usize = 8 * GROUPS; + const STEP: usize = LANES * GROUPS; #[target_feature(enable = "avx2")] pub(super) unsafe fn add_all(packed: &PackedTrees, rows: &[&[f32]], out: &mut [f32]) { @@ -332,7 +333,8 @@ mod simd { let mut acc = [0.0f32; BLOCK]; for (rows, out) in rows.chunks(BLOCK).zip(out.chunks_mut(BLOCK)) { let n = rows.len(); - let n_pad = n.div_ceil(STEP) * STEP; + let n_pad = n.div_ceil(LANES) * LANES; + let full = n_pad / STEP * STEP; table.clear(); table.resize(nf * n_pad, f32::NAN); for f in 0..nf { @@ -345,8 +347,11 @@ mod simd { for (t, perfect) in packed.trees.iter().zip(&packed.perfect) { match perfect { Some(p) => { - for row0 in (0..n_pad).step_by(STEP) { - walk(p, table.as_ptr(), n_pad as i32, row0, acc.as_mut_ptr()); + for row0 in (0..full).step_by(STEP) { + walk::(p, table.as_ptr(), n_pad as i32, row0, acc.as_mut_ptr()); + } + for row0 in (full..n_pad).step_by(LANES) { + walk::<1>(p, table.as_ptr(), n_pad as i32, row0, acc.as_mut_ptr()); } } None => { @@ -362,19 +367,25 @@ mod simd { #[inline] #[target_feature(enable = "avx2")] - unsafe fn walk(p: &PerfectTree, xs: *const f32, n_pad: i32, row0: usize, acc: *mut f32) { + unsafe fn walk( + p: &PerfectTree, + xs: *const f32, + n_pad: i32, + row0: usize, + acc: *mut f32, + ) { let nodes = p.nodes.as_ptr() as *const i32; let lane = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7); let two = _mm256_set1_epi32(2); let all_but_sign = _mm256_set1_epi32(!(DEFAULT_LEFT_BIT as i32)); let stride = _mm256_set1_epi32(n_pad); - let mut idx = [_mm256_setzero_si256(); GROUPS]; - let mut row = [_mm256_setzero_si256(); GROUPS]; + let mut idx = [_mm256_setzero_si256(); G]; + let mut row = [_mm256_setzero_si256(); G]; for (g, r) in row.iter_mut().enumerate() { - *r = _mm256_add_epi32(_mm256_set1_epi32((row0 + 8 * g) as i32), lane); + *r = _mm256_add_epi32(_mm256_set1_epi32((row0 + LANES * g) as i32), lane); } for _ in 0..p.depth { - for g in 0..GROUPS { + for g in 0..G { let threshold = _mm256_i32gather_ps::<8>(nodes as *const f32, idx[g]); let feature = _mm256_i32gather_epi32::<8>(nodes.add(1), idx[g]); let at = _mm256_add_epi32( @@ -396,7 +407,7 @@ mod simd { let first_leaf = _mm256_set1_epi32(p.nodes.len() as i32); for (g, &i) in idx.iter().enumerate() { let leaf = _mm256_i32gather_ps::<4>(p.leaves.as_ptr(), _mm256_sub_epi32(i, first_leaf)); - let a = acc.add(row0 + 8 * g); + let a = acc.add(row0 + LANES * g); _mm256_storeu_ps(a, _mm256_add_ps(_mm256_loadu_ps(a), leaf)); } } diff --git a/crates/search/src/engine/features.rs b/crates/search/src/engine/features.rs index 4f287a938..72a1eccbb 100644 --- a/crates/search/src/engine/features.rs +++ b/crates/search/src/engine/features.rs @@ -83,10 +83,10 @@ pub(super) fn predict_frag_with( peptide: &Peptide, charge: u8, cache: Option<&crate::fragments::predictions::FragPredCache>, -) -> Vec { +) -> std::sync::Arc<[f64]> { match cache { Some(c) => c.intensities(model, peptide, charge), - None => predict_frag_intensities(model, peptide, charge), + None => predict_frag_intensities(model, peptide, charge).into(), } } @@ -155,7 +155,7 @@ pub(crate) fn complete_psm_features( if peptide.length() < 2 { return; } - let frag_pred: Option> = scorer + let frag_pred: Option> = scorer .param() .frag_intensity_model .as_deref() @@ -539,7 +539,7 @@ pub(crate) fn compute_psm_features_with_edge( ); let frag_intensity_model = scorer.param().frag_intensity_model.as_deref(); - let frag_pred: Option> = frag_intensity_model + let frag_pred: Option> = frag_intensity_model .filter(|_| peptide.length() >= 2) .map(|g| predict_frag_with(g, peptide, charge, frag_cache)); let frag_pred_slice = frag_pred.as_deref(); diff --git a/crates/search/src/engine/run.rs b/crates/search/src/engine/run.rs index da7315423..481a46190 100644 --- a/crates/search/src/engine/run.rs +++ b/crates/search/src/engine/run.rs @@ -55,6 +55,54 @@ fn scored_spec<'a, 's>( scored_for_charge(scored_per_charge, z).expect("scored spectrum exists for candidate charge") } +/// Moves the PSMs and pool scores of one charge search's units (`got`, unit `k` of spectrum +/// `owners[k]`) into their spectra's merged queues and pools, the PSMs numbered from +/// `offset`. When the units belong to distinct spectra (one spectrum's charges fall in +/// different searches) the spectra are filled in parallel, each in the same order as the +/// sequential fill; otherwise unit by unit. +fn merge_units( + got: Vec<(TopNQueue, Vec)>, + owners: &[usize], + merged: &mut [TopNQueue], + pools: &mut [Vec], + offset: usize, +) { + let fill = |(mut q, pool): (TopNQueue, Vec), + i: usize, + queue: &mut TopNQueue, + kept: &mut Vec| { + kept.extend(pool); + for mut psm in q.drain_into_vec() { + psm.spectrum_idx = offset + i; + queue.push(psm); + } + }; + let mut seen = vec![false; merged.len()]; + if !owners + .iter() + .all(|&i| !std::mem::replace(&mut seen[i], true)) + { + for (unit, &i) in got.into_iter().zip(owners) { + fill(unit, i, &mut merged[i], &mut pools[i]); + } + return; + } + let mut slot: Vec)>> = (0..merged.len()).map(|_| None).collect(); + for (unit, &i) in got.into_iter().zip(owners) { + slot[i] = Some(unit); + } + merged + .par_iter_mut() + .zip(pools.par_iter_mut()) + .zip(slot.into_par_iter()) + .enumerate() + .for_each(|(i, ((queue, kept), unit))| { + if let Some(unit) = unit { + fill(unit, i, queue, kept); + } + }); +} + /// What finishing a spectrum's scoring carries over from its candidate loop: the scorer and scored /// spectra, the candidates, the top-N queue and the per-charge queues, and the loop's statistics. struct SpectrumTail<'a, 's> { @@ -150,22 +198,16 @@ impl<'a> PreparedSearch<'a> { while !units.is_empty() { let take = crate::fragments::index::index_chunk_len(&units, |u| mass(&u.1), span_da); let (owners, chunk): (Vec, Vec) = units.drain(..take).unzip(); - for ((mut q, pool), i) in self - .run_chunk_inner(&chunk, 0, params, complete_later) - .into_iter() - .zip(owners) - { - pools[i].extend(pool); - for mut psm in q.drain_into_vec() { - psm.spectrum_idx = spectrum_idx_offset + i; - merged[i].push(psm); - } - } - } - for (queue, pool) in merged.iter_mut().zip(&pools) { - queue.trim_to_capacity(params.top_n_psms_per_spectrum); - recalibrate_strong_over_spectrum(queue, pool); + let got = self.run_chunk_inner(&chunk, 0, params, complete_later); + merge_units(got, &owners, &mut merged, &mut pools, spectrum_idx_offset); } + merged + .par_iter_mut() + .zip(pools.par_iter()) + .for_each(|(queue, pool)| { + queue.trim_to_capacity(params.top_n_psms_per_spectrum); + recalibrate_strong_over_spectrum(queue, pool); + }); if complete_later { self.complete_kept_features(spectra, &mut merged); } @@ -184,9 +226,10 @@ impl<'a> PreparedSearch<'a> { .zip(queues.chunks_mut(KEPT_FEATURE_BATCH_SPECTRA)) { let peptides: Vec> = { - let accum = self.mmap_accum.lock().unwrap(); + let guard = self.mmap_accum.lock().unwrap(); + let accum = &*guard; batch - .iter() + .par_iter() .map(|q| { q.iter_psms() .map(|p| { diff --git a/crates/search/src/fragments/predictions.rs b/crates/search/src/fragments/predictions.rs index 18f1eacde..c31496854 100644 --- a/crates/search/src/fragments/predictions.rs +++ b/crates/search/src/fragments/predictions.rs @@ -5,65 +5,89 @@ //! candidate of many spectra (on DIA, every cycle of its window around its retention time), //! so its prediction is computed once per chunk here and reused. +use std::hash::BuildHasher; use std::sync::{Arc, Mutex}; use model::peptide::Peptide; use rustc_hash::FxHashMap; use scoring_crate::gbdt::GbdtPeakModel; -use scoring_crate::psm::{frag_intensities_from_raw, predict_frag_raw}; +use scoring_crate::psm::predict_frag_intensities; /// Shards of the cache; well above the thread count, so lock waits stay rare. const SHARDS: usize = 64; -/// Key: the model's address, the precursor charge and the peptidoform's text (residues, -/// modifications and flanks, a superset of what the model reads). -type Key = (usize, u8, String); +/// One cached prediction: the model's address, the precursor charge, the peptidoform (its +/// equality compares residues, residue masses, modifications, flanks and charge, a superset +/// of what the model reads) and the predicted intensities. +struct Entry { + model: usize, + charge: u8, + peptide: Peptide, + intensities: Arc<[f64]>, +} + +/// Entries by the hash of their model, charge and peptidoform; a bucket holds every entry +/// whose hash collides. +type Shard = FxHashMap>; pub struct FragPredCache { - shards: Vec>>>, + shards: Vec>, } impl Default for FragPredCache { fn default() -> Self { Self { - shards: (0..SHARDS) - .map(|_| Mutex::new(FxHashMap::default())) - .collect(), + shards: (0..SHARDS).map(|_| Mutex::new(Shard::default())).collect(), } } } +fn find( + bucket: Option<&Vec>, + model: usize, + charge: u8, + peptide: &Peptide, +) -> Option> { + bucket? + .iter() + .find(|e| e.model == model && e.charge == charge && e.peptide == *peptide) + .map(|e| Arc::clone(&e.intensities)) +} + impl FragPredCache { - /// The intensities of [`scoring_crate::psm::predict_frag_intensities`] for `peptide` - /// at `charge`, predicted on the first request of the chunk. - pub fn intensities(&self, model: &GbdtPeakModel, peptide: &Peptide, charge: u8) -> Vec { - use std::hash::BuildHasher; - let key: Key = ( - model as *const GbdtPeakModel as usize, - charge, - peptide.to_string(), - ); - let h = rustc_hash::FxBuildHasher.hash_one(&key); + /// The intensities of [`predict_frag_intensities`] for `peptide` at `charge`, predicted + /// on the first request of the chunk. + pub fn intensities(&self, model: &GbdtPeakModel, peptide: &Peptide, charge: u8) -> Arc<[f64]> { + let addr = model as *const GbdtPeakModel as usize; + let h = rustc_hash::FxBuildHasher.hash_one((addr, charge, peptide)); let shard = &self.shards[(h >> 58) as usize % SHARDS]; - let hit = shard.lock().expect("frag cache lock").get(&key).cloned(); - let raw = match hit { - Some(raw) => raw, - None => { - let raw: Arc<[f32]> = predict_frag_raw(model, peptide, charge).into(); - shard - .lock() - .expect("frag cache lock") - .insert(key, Arc::clone(&raw)); - raw - } - }; - frag_intensities_from_raw(&raw) + if let Some(hit) = find( + shard.lock().expect("frag cache lock").get(&h), + addr, + charge, + peptide, + ) { + return hit; + } + let intensities: Arc<[f64]> = predict_frag_intensities(model, peptide, charge).into(); + let mut map = shard.lock().expect("frag cache lock"); + let bucket = map.entry(h).or_default(); + if let Some(raced) = find(Some(bucket), addr, charge, peptide) { + return raced; + } + bucket.push(Entry { + model: addr, + charge, + peptide: peptide.clone(), + intensities: Arc::clone(&intensities), + }); + intensities } /// Drops every cached prediction. pub fn clear(&self) { for s in &self.shards { - *s.lock().expect("frag cache lock") = FxHashMap::default(); + *s.lock().expect("frag cache lock") = Shard::default(); } } }