Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a26e9e3
dia: read and rewrite the PIN in blocks of lines parsed in parallel (…
ypriverol Nov 25, 2026
80e102c
dia: parse the pass-2 nominee rows and the pass-1 rows of the precurs…
ypriverol Nov 25, 2026
d6dc8d3
dia: block reader keeps each block's lines in the block's scope
ypriverol Nov 25, 2026
2dccde0
dia: parse the PIN of the RT refit in parallel blocks instead of read…
ypriverol Nov 25, 2026
77ece5b
dia: format the precursor PIN rows and read the pass-1 SpecIds in par…
ypriverol Nov 25, 2026
10bb58f
dia: precursor-level q parses the PIN in parallel blocks instead of r…
ypriverol Nov 25, 2026
9d159eb
dia: drop unused imports in the precursor PIN module
ypriverol Nov 25, 2026
d05a3d6
predict: calibrate each PIN row's RT in parallel
ypriverol Nov 25, 2026
e2354f3
predict: impute the missing values of four feature columns at a time
ypriverol Nov 25, 2026
2e93974
dia: evidence traces walk each scan once in fragment m/z order instea…
ypriverol Nov 25, 2026
72b823c
pool scores: compute the ions of only the rows each pass uses (anchor…
ypriverol Nov 25, 2026
337d175
dia: the PIN reader in its own module, dia/pin.rs, keeping dia/rt.rs …
ypriverol Nov 25, 2026
2fd7eac
dia: trailing blank line in dia/pin.rs
ypriverol Nov 25, 2026
26e1fbf
rescore: free the DIA peaks before pass-1 Percolator and train the pr…
ypriverol Nov 25, 2026
7ba7d52
statistics and finish: the run statistics read each spectrum's best P…
ypriverol Nov 25, 2026
b556050
output: the RT and provenance PSM features of the PIN are filled per …
ypriverol Nov 25, 2026
da48e53
predict: on DIA the MS2 features read the observed intensities from t…
ypriverol Nov 25, 2026
dd71b8d
dia: test that the centre-trace MS2 features equal a search of the scan
ypriverol Nov 25, 2026
2235d06
dia: test formatting
ypriverol Nov 25, 2026
f539751
statistics: name the per-spectrum best-PSM type
ypriverol Nov 25, 2026
fe987fd
dia pass 2: a nominee ion's weight is +0 when its prediction is not p…
ypriverol Nov 25, 2026
f59ea3e
dia: evidence() is only used by the tests
ypriverol Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
476 changes: 321 additions & 155 deletions crates/andes/src/bin/andes/dia.rs

Large diffs are not rendered by default.

155 changes: 155 additions & 0 deletions crates/andes/src/bin/andes/dia/blocks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! Reading a large text table (a PIN) in blocks of whole lines: a reader thread fills the next
//! block while the caller works on the current one, so the caller can parse or rewrite each
//! block's lines in parallel and still see them in file order.

use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::mpsc::sync_channel;

/// Bytes read per block.
const BLOCK_BYTES: usize = 64 << 20;
/// Lines per parallel work unit of a block.
pub(crate) const LINES_PER_TASK: usize = 4096;

/// Splits `text` into its lines the way [`std::io::BufRead::lines`] does (a trailing `\n` or
/// `\r\n` taken off each), leaving out empty lines.
fn push_lines<'a>(text: &'a str, out: &mut Vec<&'a str>) {
for line in text.split_terminator('\n') {
let line = line.strip_suffix('\r').unwrap_or(line);
if !line.is_empty() {
out.push(line);
}
}
}

/// 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.
pub(crate) fn read_blocks(
path: &Path,
on_header: impl FnOnce(&str) -> Result<(), String>,
mut on_block: impl FnMut(usize, &[&str]) -> Result<(), String>,
) -> Result<(), String> {
let err = |e: &dyn std::fmt::Display| format!("{}: {e}", path.display());
let mut f = File::open(path).map_err(|e| err(&e))?;
let (tx, rx) = sync_channel::<std::io::Result<Vec<u8>>>(1);
std::thread::scope(|scope| {
scope.spawn(move || {
let mut carry: Vec<u8> = Vec::new();
loop {
let mut buf = std::mem::take(&mut carry);
let start = buf.len();
buf.resize(start + BLOCK_BYTES, 0);
let mut filled = start;
while filled < buf.len() {
match f.read(&mut buf[filled..]) {
Ok(0) => break,
Ok(n) => filled += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => {
let _ = tx.send(Err(e));
return;
}
}
}
buf.truncate(filled);
let eof = filled < start + BLOCK_BYTES;
if !eof {
match buf.iter().rposition(|&b| b == b'\n') {
Some(cut) => carry = buf.split_off(cut + 1),
None => {
carry = buf;
continue;
}
}
}
if !buf.is_empty() && tx.send(Ok(buf)).is_err() {
return;
}
if eof {
return;
}
}
});
let mut header: Option<_> = Some(on_header);
let mut first = 0usize;
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;
if let Some(h) = header.take() {
let (line, rest) = text.split_once('\n').unwrap_or((text, ""));
h(line.strip_suffix('\r').unwrap_or(line))?;
body = rest;
}
let mut lines: Vec<&str> = Vec::new();
push_lines(body, &mut lines);
on_block(first, &lines)?;
first += lines.len();
}
match header {
Some(_) => Err(err(&"empty PIN")),
None => Ok(()),
}
})
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::BufRead;

fn lines_of(path: &Path) -> (String, Vec<(usize, String)>) {
let mut head = String::new();
let mut rows = Vec::new();
read_blocks(
path,
|h| {
head = h.to_string();
Ok(())
},
|first, lines| {
rows.extend(
lines
.iter()
.enumerate()
.map(|(i, l)| (first + i, l.to_string())),
);
Ok(())
},
)
.unwrap();
(head, rows)
}

#[test]
fn blocks_give_the_lines_bufread_gives_without_the_empty_ones() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("t.pin");
let text = "h1\th2\r\na\t1\n\nb\t2\r\nc\t3";
std::fs::write(&p, text).unwrap();
let (head, rows) = lines_of(&p);
let want: Vec<String> = std::io::BufReader::new(text.as_bytes())
.lines()
.map(Result::unwrap)
.collect();
assert_eq!(head, want[0]);
let body: Vec<(usize, String)> = want[1..]
.iter()
.filter(|l| !l.is_empty())
.cloned()
.enumerate()
.collect();
assert_eq!(rows, body);
}

#[test]
fn an_empty_file_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("e.pin");
std::fs::write(&p, "").unwrap();
assert!(read_blocks(&p, |_| Ok(()), |_, _| Ok(())).is_err());
}
}
10 changes: 6 additions & 4 deletions crates/andes/src/bin/andes/dia/llr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ pub(crate) fn add_to_pin(
};

let layout = &predicted.ions;
let spec_rows = |s: usize, cals: &[Calib]| -> Vec<(u32, Vec<IonObs>)> {
type SpecRows = Vec<(u32, Vec<IonObs>)>;
let spec_rows = |s: usize, cals: &[Calib], want: &dyn Fn(usize) -> bool| -> SpecRows {
let cal = cals[run_of(s).min(n_runs - 1)];
let (w, p) = slot[s];
let win = &windows[w as usize];
Expand All @@ -394,6 +395,7 @@ pub(crate) fn add_to_pin(
let here = spectra[s].peaks.as_slice();
by_spec[s]
.iter()
.filter(|&&i| want(i as usize))
.map(|&i| {
let r = &table.rows[i as usize];
let (_, mass) = &table.forms[r.form as usize];
Expand All @@ -420,7 +422,7 @@ pub(crate) fn add_to_pin(
|| vec![Vec::new(); n_runs],
|mut acc, s| {
let run = run_of(s).min(n_runs - 1);
for (i, ions) in spec_rows(s, &first) {
for (i, ions) in spec_rows(s, &first, &|i| anchor[i]) {
if anchor[i as usize] {
acc[run].extend(
ions.iter()
Expand Down Expand Up @@ -469,7 +471,7 @@ pub(crate) fn add_to_pin(
|| vec![Counts::default(); n_runs * 2],
|mut acc, s| {
let run = run_of(s).min(n_runs - 1);
for (i, ions) in spec_rows(s, &cals) {
for (i, ions) in spec_rows(s, &cals, &|i| anchor[i] || table.rows[i].decoy) {
let i = i as usize;
let r = &table.rows[i];
let c = &mut acc[run * 2 + fold(r.form)];
Expand Down Expand Up @@ -518,7 +520,7 @@ pub(crate) fn add_to_pin(
.filter(|&s| !by_spec[s].is_empty())
.map(|s| {
let run = run_of(s).min(n_runs - 1);
let rows = spec_rows(s, &cals);
let rows = spec_rows(s, &cals, &|_| true);
let mut outs = Vec::with_capacity(rows.len());
let mut terms: Vec<Vec<(f64, f64)>> = Vec::with_capacity(rows.len());
for (i, ions) in &rows {
Expand Down
93 changes: 47 additions & 46 deletions crates/andes/src/bin/andes/dia/pass2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
//! the trace) or that has no signal has no quantity; a quantity is never 0.

use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::ops::Range;
use std::path::Path;

Expand Down Expand Up @@ -243,7 +242,7 @@ pub(crate) fn nominate(
let neutral = if is_b { prefix } else { total - prefix + H2O };
let mz = (neutral + f64::from(z) * PROTON) / f64::from(z);
let p = pred.get(site * layout.len() + k).copied().unwrap_or(0.0);
ions.push((mz, p.max(0.0)));
ions.push((mz, if p > 0.0 { p } else { 0.0 }));
}
}
ions.sort_by(|a, b| b.1.total_cmp(&a.1));
Expand Down Expand Up @@ -287,52 +286,54 @@ fn pin_fields(
pin: &Path,
want: &[usize],
) -> Result<Vec<PinFields>, String> {
let f = std::fs::File::open(pin).map_err(|e| format!("{}: {e}", pin.display()))?;
let mut lines = BufReader::new(f).lines();
let header = lines
.next()
.ok_or_else(|| format!("{}: empty PIN", pin.display()))?
.map_err(|e| format!("{}: {e}", pin.display()))?;
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_rt, c_miss, c_pep, c_prot) = (
at("SpecId")?,
at("andesrt_predicted_rt")?,
at("andesrt_missing")?,
at("Peptide")?,
at("Proteins")?,
);
let cols: std::cell::OnceCell<[usize; 5]> = std::cell::OnceCell::new();
let mut out = Vec::with_capacity(want.len());
let mut w = 0usize;
let mut idx = 0usize;
for line in lines {
if w == want.len() {
break;
}
let line = line.map_err(|e| format!("{}: {e}", pin.display()))?;
if line.is_empty() {
continue;
}
if want[w] == idx {
let x: Vec<&str> = line.split('\t').collect();
if x.len() <= c_prot.max(c_pep).max(c_rt).max(c_miss) {
return Err(format!("{}: PIN row {} is short", pin.display(), idx + 2));
crate::dia::blocks::read_blocks(
pin,
|header| {
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 _ = cols.set([
at("SpecId")?,
at("andesrt_predicted_rt")?,
at("andesrt_missing")?,
at("Peptide")?,
at("Proteins")?,
]);
Ok(())
},
|first, lines| {
let Some(&[c_id, c_rt, c_miss, c_pep, c_prot]) = cols.get() else {
return Err(format!("{}: empty PIN", pin.display()));
};
let lo = want.partition_point(|&i| i < first);
let hi = want.partition_point(|&i| i < first + lines.len());
let rows: Vec<Result<PinFields, String>> = want[lo..hi]
.par_iter()
.map(|&idx| {
let x: Vec<&str> = lines[idx - first].split('\t').collect();
if x.len() <= c_prot.max(c_pep).max(c_rt).max(c_miss) {
return Err(format!("{}: PIN row {} is short", pin.display(), idx + 2));
}
Ok((
x[c_rt].trim().parse().unwrap_or(f64::NAN),
x[c_miss].trim().parse::<f64>() != Ok(0.0),
x[c_pep].to_string(),
x[c_prot..].join(";"),
x[c_id].to_string(),
))
})
.collect();
for r in rows {
out.push(r?);
}
out.push((
x[c_rt].trim().parse().unwrap_or(f64::NAN),
x[c_miss].trim().parse::<f64>() != Ok(0.0),
x[c_pep].to_string(),
x[c_prot..].join(";"),
x[c_id].to_string(),
));
w += 1;
}
idx += 1;
}
Ok(())
},
)?;
if out.len() != want.len() {
return Err(format!(
"{}: {} of {} nominee rows found",
Expand Down
Loading
Loading