diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-11 19:49:57 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-11 19:49:57 +0000 |
| commit | 9e03cf40b875790c19d3fa1623297841b72b553e (patch) | |
| tree | 95b891af0f3015fbdd74243c23c4533fee97ae24 /src/gemma.rs | |
| parent | 8e13f31ceca05aa06b8a98b76e1141763b6a4140 (diff) | |
| download | genenetwork4-9e03cf40b875790c19d3fa1623297841b72b553e.tar.gz | |
gemma: add POST /compute/gemma, backed by the real gemma-wrapper/GEMMA
Maps a QTL from a genotype file, a SNP annotation file and trait
values, by running gemma-wrapper's K-matrix step then its LMM
association step, both synchronously (axum/tokio awaits the subprocess
directly, no job queue needed) and returning the parsed .assoc.txt
rows in the standard envelope.
Both steps use a bare --loco (gemma-wrapper derives the chromosome
list from the SNP annotation file). This was arrived at empirically,
not from GeneNetwork3's or GeneNetwork2's own gemma code: run for real
against the BXD fixtures,
- GeneNetwork3's gn3/computations/gemma.py composes a GWA command that
always keeps "-gk" alongside "-lmm"; real GEMMA rejects that
combination outright ("only one of -gk ... -lmm ... options is
allowed"), so none of its gwa-compute/k-gwa-compute endpoints can
produce output. Unsurprising: tests/integration/test_gemma.py is
entirely @unittest.skip, so this was never exercised.
- GeneNetwork2's wqflask/marker_regression/gemma_mapping.py correctly
omits "-gk" from the GWA step, but its non-LOCO branch fails too,
the same way my own first (non-LOCO) attempt did: gemma-wrapper only
ever archives a non-LOCO kinship matrix into a .tar.xz, with no
loose file at the path its own non-LOCO GWA code assumes
("Enforce failed for file_kin ... open file"). Only --loco, which
gemma-wrapper's own USAGE banner documents and which does unpack
that archive, actually works.
A --loco run's .assoc.txt files (one per chromosome) are themselves
only ever inside gemma-wrapper's own output archive, never loose, so
gemma.rs shells out to `tar` (one of gemma-wrapper's own propagated
dependencies) to extract them before concatenating all chromosomes'
rows into the response.
guix.scm now depends on (gn packages gemma) from guix-bioinformatics
for gemma-wrapper (propagated-input: it's invoked as a subprocess, not
linked, and this makes it land in a consuming profile too, same as
GeneNetwork3's and GeneNetwork2's own packages do it). That dependency
needed guix-bioinformatics' own gn/packages/gemma.scm fixed first (see
that repo's fix/gemma-which-shadowing branch) -- gemma-gn2 would not
build at all before that fix.
Verified end to end: `cargo test` passes in full, including a real
(non-mocked, non-skipped) run of gemma-wrapper/GEMMA against the BXD
fixtures copied from genenetwork3/tests/test_data, producing exactly
7320 association rows (one per marker in BXD_snps.txt) in ~19s.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'src/gemma.rs')
| -rw-r--r-- | src/gemma.rs | 406 |
1 files changed, 406 insertions, 0 deletions
diff --git a/src/gemma.rs b/src/gemma.rs new file mode 100644 index 0000000..b1f17ed --- /dev/null +++ b/src/gemma.rs @@ -0,0 +1,406 @@ +//! Core logic for POST /compute/gemma: compose and run gemma-wrapper +//! against a genotype file, a SNP annotation file and trait values, and +//! parse the resulting GEMMA association output into QTL mapping rows. +//! +//! Mirrors gn3/computations/gemma.py and gn3/api/gemma.py +//! (GeneNetwork3), but synchronously: axum/tokio can await an external +//! process directly, so there is no need for GeneNetwork3's Redis job +//! queue. The actual invocation also differs from GeneNetwork3's in two +//! respects, both found by running the real gemma-wrapper/GEMMA binaries +//! against the BXD fixtures rather than trusting GeneNetwork3's own +//! (entirely @unittest.skip'd) integration tests -- see `compute_gwa` +//! and `compute` below. + +use std::io; +use std::path::Path; +use std::process::Output; + +use serde_json::Value; +use tokio::process::Command; + +/// One phenotype value per strain (genotype-file order), or `None` for +/// a missing ("NA") sample. +pub type TraitValues = Vec<Option<f64>>; + +#[derive(Debug)] +pub enum GemmaError { + /// Failed to spawn or run a child process. + Io(io::Error), + /// gemma-wrapper exited non-zero; carries its stderr. + CommandFailed { step: &'static str, stderr: String }, + /// gemma-wrapper's own --json stdout record was not valid JSON, or + /// reported an error (its own `errno` field was non-zero). + WrapperError { step: &'static str, detail: String }, + /// The real GEMMA `.assoc.txt` file gemma-wrapper pointed to could + /// not be found or read. + AssocFile(io::Error), + /// gemma-wrapper's GWA output archive did not list any files. + NoAssocFiles, +} + +impl std::fmt::Display for GemmaError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + GemmaError::Io(e) => write!(f, "failed to run gemma-wrapper: {e}"), + GemmaError::CommandFailed { step, stderr } => { + write!(f, "gemma-wrapper ({step}) failed: {stderr}") + } + GemmaError::WrapperError { step, detail } => { + write!(f, "gemma-wrapper ({step}) reported an error: {detail}") + } + GemmaError::AssocFile(e) => write!(f, "could not read GEMMA association output: {e}"), + GemmaError::NoAssocFiles => { + write!(f, "gemma-wrapper's response listed no association output files") + } + } + } +} + +/// Write `values` as a GEMMA/BIMBAM phenotype file: one value per line, +/// "NA" for a missing sample. Mirrors +/// gn3.computations.gemma.generate_pheno_txt_file, minus its hash-based +/// cache filename (the caller picks the path; see `compute`). +pub fn write_pheno_file(path: &Path, values: &TraitValues) -> io::Result<()> { + let mut contents = String::new(); + for value in values { + match value { + Some(v) => contents.push_str(&v.to_string()), + None => contents.push_str("NA"), + } + contents.push('\n'); + } + std::fs::write(path, contents) +} + +async fn run(cmd: &str, args: &[&str]) -> io::Result<Output> { + Command::new(cmd).args(args).output().await +} + +fn parse_wrapper_output(step: &'static str, output: Output) -> Result<Value, GemmaError> { + if !output.status.success() { + return Err(GemmaError::CommandFailed { + step, + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }); + } + let stdout = String::from_utf8_lossy(&output.stdout); + let record: Value = serde_json::from_str(&stdout).map_err(|e| GemmaError::WrapperError { + step, + detail: format!("could not parse gemma-wrapper's --json output: {e}"), + })?; + if record.get("errno").and_then(Value::as_i64).unwrap_or(0) != 0 { + return Err(GemmaError::WrapperError { + step, + detail: record + .get("error") + .and_then(Value::as_str) + .unwrap_or("gemma-wrapper reported a non-zero errno") + .to_string(), + }); + } + Ok(record) +} + +/// Run gemma-wrapper's `--json` K-matrix step and return its stdout +/// record (parsed JSON). +/// +/// `--loco` (bare, no chromosome list) is required here: confirmed by +/// actually running gemma-wrapper against the BXD fixtures, a plain +/// (non-LOCO) `-gk` only ever leaves its kinship matrix inside a +/// `.tar.xz` archive in `--cache-dir`, with no loose file at the path +/// the non-LOCO branch of gemma-wrapper's own GWA step later assumes -- +/// that combination errors out (`gemma: ... open file ... CheckParam`). +/// `--loco` is the combination gemma-wrapper's own USAGE banner +/// documents and the one whose GWA-side code path actually unpacks the +/// archive it needs (see `compute_gwa` and `compute`). Passing it with +/// no chromosome list makes gemma-wrapper derive the full chromosome +/// list from the SNP annotation file itself. +async fn compute_kinship( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + pheno_file: &str, + snps_file: &str, +) -> Result<Value, GemmaError> { + let output = run( + gemma_wrapper_cmd, + &[ + "--json", + "--cache-dir", + cache_dir, + "--loco", + "--", + "-g", + genotype_file, + "-p", + pheno_file, + "-a", + snps_file, + "-gk", + ], + ) + .await + .map_err(GemmaError::Io)?; + parse_wrapper_output("kinship", output) +} + +/// Run gemma-wrapper's `--json` GWA (association) step, given the +/// K-step's JSON record written to `k_json_path` (gemma-wrapper's +/// `--input` takes a file path, not stdin), and return its stdout +/// record. `--loco` is required here for the same reason as in +/// `compute_kinship`. +/// +/// Note: unlike GeneNetwork3's `generate_gemma_cmd` +/// (gn3/computations/gemma.py), which always appends a literal "-gk" to +/// the forwarded GEMMA args regardless of whether an LMM run was +/// requested, this passes `-lmm` without `-gk`, matching gemma-wrapper's +/// own documented usage (its USAGE banner in bin/gemma-wrapper). +/// gemma-wrapper decides K-only vs. GWA purely by whether "-gk" is +/// present in those args (`DO_COMPUTE_KINSHIP = +/// gemma_args.include?("-gk")`); passing both flags together, as +/// GeneNetwork3 does, makes every one of its calls a K-only run, and the +/// `-lmm` value is silently ignored. That GeneNetwork3 code path has no +/// non-skipped test covering it (tests/integration/test_gemma.py is +/// `@unittest.skip`), so it is not knowingly replicated here. +async fn compute_gwa( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + pheno_file: &str, + snps_file: &str, + lmm: u8, + k_json_path: &str, +) -> Result<Value, GemmaError> { + let lmm_str = lmm.to_string(); + let output = run( + gemma_wrapper_cmd, + &[ + "--json", + "--cache-dir", + cache_dir, + "--loco", + "--input", + k_json_path, + "--", + "-g", + genotype_file, + "-p", + pheno_file, + "-a", + snps_file, + "-lmm", + &lmm_str, + ], + ) + .await + .map_err(GemmaError::Io)?; + parse_wrapper_output("gwa", output) +} + +/// The association output basenames gemma-wrapper's GWA-step JSON +/// record points at: `record["files"]` is a list of +/// `[chr, log_basename, data_basename]`, one entry per chromosome in a +/// `--loco` run (see `compute`). +fn assoc_file_basenames(record: &Value) -> Vec<&str> { + record + .get("files") + .and_then(Value::as_array) + .map(|files| { + files + .iter() + .filter_map(|entry| entry.as_array()?.get(2)?.as_str()) + .collect() + }) + .unwrap_or_default() +} + +/// One row of a GEMMA `.assoc.txt` file, keyed by its header column +/// names. Columns vary with `-lmm` (1/2/3 run one test; 4 runs all +/// three), so this stays a generic map rather than a fixed struct. +pub type AssocRow = serde_json::Map<String, Value>; + +/// Parse a GEMMA `.assoc.txt` file (tab-separated, header row first) +/// into one row per marker. A value that parses as a number is kept +/// numeric; "NA" and anything else stays a string. +fn parse_assoc_file(contents: &str) -> Vec<AssocRow> { + let mut lines = contents.lines(); + let Some(header) = lines.next() else { + return Vec::new(); + }; + let columns: Vec<&str> = header.split('\t').collect(); + lines + .filter(|line| !line.is_empty()) + .map(|line| { + let mut row = AssocRow::new(); + for (column, value) in columns.iter().zip(line.split('\t')) { + let json_value = value + .parse::<f64>() + .map(|n| serde_json::json!(n)) + .unwrap_or_else(|_| Value::String(value.to_string())); + row.insert((*column).to_string(), json_value); + } + row + }) + .collect() +} + +/// Extract `archive` (a `.tar.xz`, relative to `cache_dir`) into +/// `dest_dir`. Confirmed necessary by actually running the real +/// binaries: a `--loco` GWA run's `.assoc.txt` files (one per +/// chromosome) only ever end up inside this archive, never as loose +/// files in `cache_dir` -- unlike the kinship step's `.cXX.txt` files, +/// which do also appear loose (gemma-wrapper itself is inconsistent +/// about this between the two steps). +async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Result<(), GemmaError> { + let archive_path = Path::new(cache_dir).join(archive); + let output = run( + "tar", + &[ + "xJf", + &archive_path.to_string_lossy(), + "-C", + dest_dir, + ], + ) + .await + .map_err(GemmaError::Io)?; + if !output.status.success() { + return Err(GemmaError::CommandFailed { + step: "extract-archive", + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }); + } + Ok(()) +} + +fn nanos_since_epoch() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) +} + +/// Run the full gemma-wrapper flow -- compute kinship, then run the LMM +/// association test, both `--loco` -- and return the mapped QTL as a +/// JSON array of rows (each a JSON object), concatenated across every +/// chromosome's `.assoc.txt` from the real GEMMA output. The result is +/// one `Value::Array`, not a `Vec<Value>`: utoipa (for the OpenAPI +/// schema) implements `ToSchema` for `serde_json::Value` itself, but +/// `Vec<serde_json::Value>` needs `Value: ComposeSchema`, which it does +/// not implement in this utoipa version. +pub async fn compute( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + snps_file: &str, + trait_values: &TraitValues, + lmm: u8, +) -> Result<Value, GemmaError> { + std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; + let unique = format!("{}-{}", std::process::id(), nanos_since_epoch()); + let pheno_path = Path::new(cache_dir).join(format!("{unique}-pheno.txt")); + write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?; + let pheno_file = pheno_path.to_string_lossy().into_owned(); + + let k_record = compute_kinship( + gemma_wrapper_cmd, + cache_dir, + genotype_file, + &pheno_file, + snps_file, + ) + .await?; + let k_json_path = Path::new(cache_dir).join(format!("{unique}-k.json")); + std::fs::write(&k_json_path, k_record.to_string()).map_err(GemmaError::Io)?; + + let gwa_record = compute_gwa( + gemma_wrapper_cmd, + cache_dir, + genotype_file, + &pheno_file, + snps_file, + lmm, + &k_json_path.to_string_lossy(), + ) + .await?; + + let basenames = assoc_file_basenames(&gwa_record); + if basenames.is_empty() { + return Err(GemmaError::NoAssocFiles); + } + let archive = gwa_record + .get("archive") + .and_then(Value::as_str) + .ok_or_else(|| GemmaError::WrapperError { + step: "gwa", + detail: "gemma-wrapper's response did not list an output archive".to_string(), + })?; + let extract_dir = Path::new(cache_dir).join(format!("{unique}-gwa-extract")); + std::fs::create_dir_all(&extract_dir).map_err(GemmaError::Io)?; + extract_archive(cache_dir, archive, &extract_dir.to_string_lossy()).await?; + + let mut rows = Vec::new(); + for basename in basenames { + let contents = std::fs::read_to_string(extract_dir.join(basename)) + .map_err(GemmaError::AssocFile)?; + rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object)); + } + let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless + Ok(Value::Array(rows)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_pheno_file_writes_one_value_per_line_and_na_for_missing() { + let path = std::env::temp_dir().join(format!("gn4-gemma-test-{}", std::process::id())); + write_pheno_file(&path, &vec![Some(9.944), None, Some(8.572)]).unwrap(); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents, "9.944\nNA\n8.572\n"); + } + + #[test] + fn parse_assoc_file_parses_header_and_numeric_rows() { + let contents = "chr\trs\tps\tp_wald\n1\trs001\t3010274\t0.05\n1\trs002\t3492195\tNA\n"; + let rows = parse_assoc_file(contents); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0]["chr"], serde_json::json!(1.0)); + assert_eq!(rows[0]["rs"], serde_json::json!("rs001")); + assert_eq!(rows[0]["p_wald"], serde_json::json!(0.05)); + assert_eq!(rows[1]["p_wald"], serde_json::json!("NA")); + } + + #[test] + fn parse_assoc_file_empty_contents_yields_no_rows() { + assert_eq!(parse_assoc_file("").len(), 0); + } + + #[test] + fn assoc_file_basenames_reads_the_third_element_of_every_file_entry() { + let record = serde_json::json!({ + "files": [["1", "a.log.txt", "a.assoc.txt"], ["2", "b.log.txt", "b.assoc.txt"]] + }); + assert_eq!(assoc_file_basenames(&record), vec!["a.assoc.txt", "b.assoc.txt"]); + } + + #[test] + fn assoc_file_basenames_missing_files_yields_empty() { + assert_eq!(assoc_file_basenames(&serde_json::json!({})), Vec::<&str>::new()); + } + + #[test] + fn parse_wrapper_output_rejects_non_zero_errno() { + use std::os::unix::process::ExitStatusExt; + let output = Output { + status: std::process::ExitStatus::from_raw(0), + stdout: br#"{"errno": 1, "error": "boom"}"#.to_vec(), + stderr: Vec::new(), + }; + let err = parse_wrapper_output("kinship", output).unwrap_err(); + assert!(matches!(err, GemmaError::WrapperError { step: "kinship", .. })); + assert_eq!(err.to_string(), "gemma-wrapper (kinship) reported an error: boom"); + } +} |
