From 9c1fea133cfe4fd0a16571153d9a937c3c8277f1 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:04:59 +0000 Subject: [PATCH 01/21] search: key the fragment-intensity cache by peptidoform, cache intensities The chunk cache of fragment-intensity predictions built its key with peptide.to_string() on every lookup (about 115 M lookups on a diaPASEF run) and turned the cached raw values into intensities (one exp per ion) on every hit. It now hashes the peptidoform in place, compares it with Peptide equality (residues, residue masses, modifications, flanks: a superset of the text the key used) and stores the intensities, shared by Arc. The peptidoform is cloned only on a miss. --- crates/search/src/engine/features.rs | 8 +- crates/search/src/fragments/predictions.rs | 88 ++++++++++++++-------- 2 files changed, 60 insertions(+), 36 deletions(-) diff --git a/crates/search/src/engine/features.rs b/crates/search/src/engine/features.rs index 4f287a93..72a1eccb 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/fragments/predictions.rs b/crates/search/src/fragments/predictions.rs index 18f1eacd..c3149685 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(); } } } From 346adb8c815fe576812d4f2c086a27165a919118 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:19:19 +0000 Subject: [PATCH 02/21] search: recalibrate the merged charge queues of a chunk in parallel After the charge searches of a chargeless chunk, each spectrum's merged queue is trimmed and its strong scores recalibrated leave-one-out over the spectrum's pool, O(kept x pool) per spectrum. The loop ran on one thread for 20,000 spectra per chunk; it now runs per spectrum on the thread pool (each spectrum's result depends only on its own queue and pool). --- crates/search/src/engine/run.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/search/src/engine/run.rs b/crates/search/src/engine/run.rs index da731542..86ce7c31 100644 --- a/crates/search/src/engine/run.rs +++ b/crates/search/src/engine/run.rs @@ -162,10 +162,13 @@ impl<'a> PreparedSearch<'a> { } } } - 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); - } + 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); } From 0c9423c4e25ba3e19c485f713b807aff7e00f348 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:29:24 +0000 Subject: [PATCH 03/21] dia: sort the re-rank order on the thread pool The keep-10-per-scan step sorted 75 M PIN rows by (scan group, re-rank score) with a stable sort on one thread, and looked the scan groups up in a SipHash map. The sort is now par_sort_unstable_by with the row index as the last key (the order the stable sort gives, ties included) and the group map uses FxHash (group ids still number the groups in first-appearance order). --- crates/andes/src/bin/andes/dia.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index cee8260d..7b7e4d3e 100644 --- a/crates/andes/src/bin/andes/dia.rs +++ b/crates/andes/src/bin/andes/dia.rs @@ -105,7 +105,7 @@ 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 group = Vec::new(); @@ -225,7 +225,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() { From 8acfa6767204c8b06cceb66d62975e867f2a493e Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:29:24 +0000 Subject: [PATCH 04/21] dia: pick the pass-2 nominee rows with one parallel sort Nomination walked the 75 M pool rows on one thread to keep, per (peptidoform, charge, run), the first row of the highest pool LLR. The rows are now ranked by a parallel sort on (key, LLR descending, row index) and the first row of each key is kept: the same rows. With a NaN LLR (where the walk's result depends on the order) the walk stays. --- crates/andes/src/bin/andes/dia/pass2.rs | 68 ++++++++++++++++++++----- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/andes/src/bin/andes/dia/pass2.rs b/crates/andes/src/bin/andes/dia/pass2.rs index 14864070..089ca30d 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; From 6b28b4e1c33f818bac264513772577c93ef9e252 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:30:18 +0000 Subject: [PATCH 05/21] dia: FxHash maps in the co-elution and re-rank passes, parallel transpose The co-elution columns built two maps over the kept 9.5 M PIN rows and the re-rank looked up each of 75 M rows' run name in SipHash maps on one thread; they use FxHash now (only lookups and in-order pushes, no iteration order leaks out). The co-elution feature columns are transposed one column per task. --- crates/andes/src/bin/andes/dia.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index 7b7e4d3e..1b37b4da 100644 --- a/crates/andes/src/bin/andes/dia.rs +++ b/crates/andes/src/bin/andes/dia.rs @@ -107,7 +107,7 @@ pub(crate) fn rerank_pin( + 1; 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(); @@ -449,14 +449,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; @@ -528,6 +529,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)?; From 7fdace709ffe21489d7d57950038c8e738b0ccbe Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:30:55 +0000 Subject: [PATCH 06/21] dia: train the RT refit folds together and predict the rows in parallel The RT refit trained its three cross-fitted regression GBDTs one after the other and predicted the 9.5 M PIN rows on one thread. The folds now train on the thread pool together, each row is predicted by its fold's model in parallel, and the median sort runs in parallel (an f64 sort by total_cmp gives the same sequence stable or not). --- crates/andes/src/bin/andes/dia.rs | 59 ++++++++++++++++++------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index 1b37b4da..29116e55 100644 --- a/crates/andes/src/bin/andes/dia.rs +++ b/crates/andes/src/bin/andes/dia.rs @@ -1079,32 +1079,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(); @@ -1127,7 +1136,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() { From ca5aacf72f827acfc1391af05d1a6b13da85cd28 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:34:50 +0000 Subject: [PATCH 07/21] dia: FxHash map for the best pass-1 row of each precursor The precursor PIN reads the 9.5 M pass-1 rows into a map of the best row per (FileName, Peptide, charge); the map is only looked up and updated in row order, so FxHash replaces SipHash without changing the result. --- crates/andes/src/bin/andes/dia/score.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/andes/src/bin/andes/dia/score.rs b/crates/andes/src/bin/andes/dia/score.rs index f57c25ba..33de1d4c 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, } @@ -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, From 833360be65180a098d1e81aa4d91d453bf9a8237 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 15:59:55 +0000 Subject: [PATCH 08/21] search: merge the charge-search units of a chunk in parallel On a chargeless DIA chunk each spectrum is searched at every charge in separate charge searches; their units' PSMs were moved into the spectra's merged queues on one thread, 14 % of a chunk's time at 46 threads (1.65 s of 12 s per chunk). When the units of a charge search belong to distinct spectra (the usual case: one spectrum's charges have precursor masses further apart than a chunk spans) each spectrum is now filled on the thread pool, in the same order as before; otherwise the units are merged one by one as before. --- crates/search/src/engine/run.rs | 61 +++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/crates/search/src/engine/run.rs b/crates/search/src/engine/run.rs index 86ce7c31..5324ee55 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,17 +198,8 @@ 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); - } - } + 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() From a3bd75685f37ccb7c63e3b500d6ebf7b3c3c9622 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:02:47 +0000 Subject: [PATCH 09/21] dia: parallel peptidoform lookup when reading the PIN, FxHash maps Every DIA pass that reads the 75 M-row PIN (predict, pool scores, co-elution, RT refit, precursor q) looked up each row's peptide in SipHash maps on one thread; at 48 threads the predict step ran 80 s on about 3 cores before its RT predictions and 33 s on one core before its MS2 predictions. The rows' known/new peptide test and their form ids are now looked up on the thread pool, and only the new peptides are walked in order (form ids keep their first-appearance numbering). The MS2 (peptidoform, charge) pairs are found the same way (eligibility in parallel, numbering in row order), the row-to-pair map is parallel, and the maps (spectrum bases, forms, pairs, anchors, folds) use FxHash; none is iterated in an order that reaches the output. --- crates/andes/src/bin/andes/dia/pin.rs | 36 ++++++++++------- crates/andes/src/bin/andes/dia/rt.rs | 58 +++++++++++++++------------ 2 files changed, 55 insertions(+), 39 deletions(-) diff --git a/crates/andes/src/bin/andes/dia/pin.rs b/crates/andes/src/bin/andes/dia/pin.rs index 1717e23a..f8e74258 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/rt.rs b/crates/andes/src/bin/andes/dia/rt.rs index acc25b88..d3e566ce 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] From 1a267954e60be05c53b988ef3f898e107007b350 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:04:24 +0000 Subject: [PATCH 10/21] search: copy the kept PSMs' peptides out of the candidate store in parallel The kept-feature completion copies each batch's peptides (2,048 spectra, about 90 k peptides) out of the candidate store under its lock on one thread, 3 % of a chunk's time at 46 threads. The copy now runs on the thread pool while the lock is held; nothing else takes that lock while a chunk completes its kept features (the chunk's scoring has finished and chunks are scored one at a time), so the parallel copy cannot wait on it. --- crates/search/src/engine/run.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/search/src/engine/run.rs b/crates/search/src/engine/run.rs index 5324ee55..481a4619 100644 --- a/crates/search/src/engine/run.rs +++ b/crates/search/src/engine/run.rs @@ -226,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| { From 11c15dbdecb760f756282cc8945028f75e81f2db Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:13:11 +0000 Subject: [PATCH 11/21] output: classify the rescored PSMs on the thread pool The class-wise FDR and the cutoffs classify every rescored PSM (5 M targets and their decoys on a diaPASEF run) by its proteins' entry kinds on one thread, several times after rescoring. The classification now runs in parallel over the rows in the map's iteration order (rows keep their indices), and the pooled decoy scores sort in parallel (an f64 sort by total_cmp gives the same sequence). --- crates/output/src/fdr/class.rs | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/crates/output/src/fdr/class.rs b/crates/output/src/fdr/class.rs index 4594df12..c2e5b321 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); From aa51f6965d5ec9de87fff74dd3e2cc474aad17ef Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:15:08 +0000 Subject: [PATCH 12/21] dia: build the pass-1 row keys while parsing, FxHash nominee map Reading the pass-1 PIN for the precursor PIN allocated each row's (FileName, Peptide, charge) key and looked up its SpecId in a SipHash map on one thread (18 s on about 3 cores at 48 threads). The keys are now built in the parallel parse and the nominee map uses FxHash; the best row per key is still chosen in row order. --- crates/andes/src/bin/andes/dia/score.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/andes/src/bin/andes/dia/score.rs b/crates/andes/src/bin/andes/dia/score.rs index 33de1d4c..442890ec 100644 --- a/crates/andes/src/bin/andes/dia/score.rs +++ b/crates/andes/src/bin/andes/dia/score.rs @@ -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, @@ -324,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| { @@ -344,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) { @@ -366,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, @@ -490,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) @@ -784,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"]); From 43c40d91d3df75c67c92d54a9e5cab821ac7cdc6 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:28:24 +0000 Subject: [PATCH 13/21] dia: check and split each PIN block's lines in parallel The block reader of the DIA passes validated each 64 MB block as UTF-8 and split it into lines on the consumer thread, then handed the lines to the parallel parse. The 75 M-row pass-1 PIN is about 60 GB of text and is read by several passes (predict, pool scores, nomination, re-rank, co-elution), so this serial step cost tens of seconds per run. A block is now cut after newlines into 64 pieces that are checked and split on the thread pool and concatenated in order: the same lines. --- crates/andes/src/bin/andes/dia/blocks.rs | 67 +++++++++++++++++++++--- 1 file changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/andes/src/bin/andes/dia/blocks.rs b/crates/andes/src/bin/andes/dia/blocks.rs index 217c7e8d..357d6de9 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(); From 50f2ddeebd3656eadd3eebf5d6e29b85282c7b4e Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:29:30 +0000 Subject: [PATCH 14/21] rescore: compute the line search's row terms on the thread pool In each SVM fit the line search walked the training rows on one thread to sum the two slopes and collect the breakpoints; at 48 threads it was a third of the fit time on the diaPASEF pass-1 PIN (39 of 119 s summed over the fits; gram 43 s, screened passes 27 s). The rows' slope terms and breakpoints are now computed per chunk of rows in parallel, then added and concatenated in row order: the same sums (same additions in the same order) and the same breakpoint list before the stable sort. --- crates/rescore/src/svm.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/rescore/src/svm.rs b/crates/rescore/src/svm.rs index f10f5059..aaf1f64b 100644 --- a/crates/rescore/src/svm.rs +++ b/crates/rescore/src/svm.rs @@ -795,20 +795,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<(f64, usize, f64)>| { 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<(Vec<(f64, f64)>, Vec<(f64, usize, f64)>)> = (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 { From 7f3afbcd80fb1c9c23b40939efb8c4894dce9cd1 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:30:21 +0000 Subject: [PATCH 15/21] scoring: pad GBDT batches to 8 rows, not 32 The AVX2 tree walk evaluates rows in steps of 32 (four 8-lane groups), padding a batch's row count up to a multiple of 32 with copies of its last row. The rich-ion and fragment-intensity models are evaluated per PSM on tens of ion rows, so the padding was a large share of the walk. The rows are now padded to a multiple of 8: full 32-row steps as before, then single 8-lane groups for the rest. Each row's value is still the sum of its leaves over the trees in tree order, so the outputs are the same. --- crates/scoring/src/gbdt.rs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/scoring/src/gbdt.rs b/crates/scoring/src/gbdt.rs index f4eebfb3..68694b8b 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)); } } From 59f3259038277519c18d415e640e58f296f18fff Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:32:32 +0000 Subject: [PATCH 16/21] model-train: split histogram features over enough tasks for every thread A tree node's histograms are built in tasks of 4 features. The DIA learned score trains on about 45 features in 3 folds at once, so a node gave about 11 tasks per fold and the 48-thread runs used about 20 cores for its rounds. A task now takes fewer features (down to 1) when the blocks of 4 would not give every thread one. Each bin still adds its rows in row order, so the histograms are the same. --- crates/model-train/src/gbdt/tree.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/model-train/src/gbdt/tree.rs b/crates/model-train/src/gbdt/tree.rs index 13ca03e4..29cfae59 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 { From f9a192ce9157b3e9d005ecce76bdf46821f3d664 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:33:36 +0000 Subject: [PATCH 17/21] output: build the protein-inference peptide rows in parallel Protein inference turned each rescored PSM (5 M targets, and the decoys) into its peptide's protein families on one thread, then ran the target and decoy parsimony one after the other. The families are now found per PSM on the thread pool and merged per peptide in a map (the best score and the union of families do not depend on the merge order), the rows sort in parallel (their peptides are distinct), and the target and decoy sides run together. --- crates/output/src/protein/inference.rs | 43 +++++++++++++++----------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/crates/output/src/protein/inference.rs b/crates/output/src/protein/inference.rs index 9e8a07d9..6a8dbb81 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(); From b0a59a20b21421e262f94dcafd60370a545b5c22 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:35:51 +0000 Subject: [PATCH 18/21] dia: start the precursor learned score as soon as pass 2 has its table The learned score of the precursor PIN (three cross-fitted GBDT rounds) was started with pass-1 rescoring and its later rounds outlasted pass 1, so it set the end of rescoring. It depends only on the pass-2 table and the seed, so it now starts on its own thread right after pass 2, beside the per-scan cut and the co-elution columns, and rescoring joins it after pass 1 (the table moves into the thread and back). Same score; the memory it holds (about 5 GB) now overlaps those steps, which hold less than the search did. --- crates/andes/src/bin/andes/search/finish.rs | 2 + .../andes/src/bin/andes/search/rescoring.rs | 75 +++++++++++++------ 2 files changed, 54 insertions(+), 23 deletions(-) diff --git a/crates/andes/src/bin/andes/search/finish.rs b/crates/andes/src/bin/andes/search/finish.rs index 523431f5..016cd724 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 aa50d3f2..db0ccdf0 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, From fceed4653648a120c52e59ddfea2c288b484dab0 Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 16:50:00 +0000 Subject: [PATCH 19/21] rescore: name the line-search breakpoint and row-term types --- crates/rescore/src/svm.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/rescore/src/svm.rs b/crates/rescore/src/svm.rs index aaf1f64b..bb61586e 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,7 +802,7 @@ fn line_search( let mut l = lambda * omega_l; let mut r = lambda * omega_r; deltas.clear(); - let visit = |i: usize, terms: &mut Vec<(f64, f64)>, found: &mut Vec<(f64, usize, f64)>| { + 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 { @@ -810,7 +817,7 @@ fn line_search( }; 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<(Vec<(f64, f64)>, Vec<(f64, usize, f64)>)> = (0..n.div_ceil(CHUNK)) + let parts: Vec = (0..n.div_ceil(CHUNK)) .into_par_iter() .map(|c| { let (mut terms, mut found) = (Vec::new(), Vec::new()); From ca8d6df5f211f1e1b8c9a1e4b16dfce5614f6c9a Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 18:50:22 +0000 Subject: [PATCH 20/21] dia: precursor-level q-values in dia/qvalue.rs, keeping dia.rs under the file budget --- crates/andes/src/bin/andes/dia.rs | 323 +---------------------- crates/andes/src/bin/andes/dia/qvalue.rs | 321 ++++++++++++++++++++++ 2 files changed, 326 insertions(+), 318 deletions(-) create mode 100644 crates/andes/src/bin/andes/dia/qvalue.rs diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index 29116e55..e2957e2b 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::{classwise_q_values, precursor_q, precursor_q_by_class}; +#[cfg(test)] +use qvalue::{curve_at, precursor_q_values, q_curve}; + use std::collections::HashMap; use std::path::Path; use std::time::Instant; @@ -1181,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/qvalue.rs b/crates/andes/src/bin/andes/dia/qvalue.rs new file mode 100644 index 00000000..401fcef4 --- /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) +} From 9b0d056de1d82b8033fae0c9a2ca5c62cf23f96a Mon Sep 17 00:00:00 2001 From: Yasset Perez-Riverol Date: Wed, 25 Nov 2026 19:11:28 +0000 Subject: [PATCH 21/21] dia: classwise_q_values re-exported for the tests only --- crates/andes/src/bin/andes/dia.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/andes/src/bin/andes/dia.rs b/crates/andes/src/bin/andes/dia.rs index e2957e2b..bd4f26bf 100644 --- a/crates/andes/src/bin/andes/dia.rs +++ b/crates/andes/src/bin/andes/dia.rs @@ -10,9 +10,9 @@ pub(crate) mod score; pub(crate) mod study; pub(crate) mod transfer; -pub(crate) use qvalue::{classwise_q_values, precursor_q, precursor_q_by_class}; +pub(crate) use qvalue::{precursor_q, precursor_q_by_class}; #[cfg(test)] -use qvalue::{curve_at, precursor_q_values, q_curve}; +use qvalue::{classwise_q_values, curve_at, precursor_q_values, q_curve}; use std::collections::HashMap; use std::path::Path;