about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-16 21:23:45 +0000
committerPjotr <wrk@bosa.lan>2026-11-16 21:23:45 +0000
commitbce93d3deedfc4f0a00a931b1b06ee1c9e8520d1 (patch)
tree4628a096992c2a943fcef8214e68200c13b29d81 /src
parent7f6d92b546892ea5dba5a3f5df541c77c229f1e4 (diff)
downloadgenenetwork4-bce93d3deedfc4f0a00a931b1b06ee1c9e8520d1.tar.gz
impute: make the hmm path able to run at all -- three bugs
impute=none and impute=mean already worked; impute=hmm died every time with
"gemma-wrapper's response listed no association output files", which named
neither the cause nor the place.  Three separate faults, each measured:

1. chromosomes_from split the SNP map on whitespace only.  The panel's own
   file reads "marker, 3001490, 1" (spaces after the commas) and the HMM file
   scripts/qtl2-impute-bimbam.R writes reads "marker,3001490,1" -- one token --
   so the chromosome list came back empty and ravanan was handed an empty
   scatter.  It now splits on commas and whitespace both.
2. The HMM calls come from the qtl2 cross, whose individuals are the whole
   panel: 235 for BXD.8 against the 198 animals that carry trait values.
   Passing the panel's positional values against those columns makes every
   individual missing -- GEMMA says "no individuals in common", ravanan says
   "no association output files".  The R script now also writes
   <prefix>.individuals.txt and the ravanan path re-aligns the trait values to
   it by name; the reply says how many individuals the HMM calls carry.
3. A relative PREPARE_GENOTYPES ("scripts/prepare-genotypes.sh") is only found
   when the server runs from its checkout.  An instance started elsewhere
   answered "could not run scripts/prepare-genotypes.sh: No such file or
   directory".  A relative default is now resolved against the checkout that
   GEMMA_RAVANAN_WORKFLOW points into.

State after these: none 200 (21 055 rows), mean 200 (21 056 rows, with its
note), hmm now runs the whole workflow (the run took 32 minutes single-machine
before failing) and stops on ravanan's own manifest cache -- "source file
.../manifest.scm newer than compiled .../ccache" -- which is the next thing to
fix and is not about genotypes.

Same-genotype agreement, measured separately (gemma on the HMM BIMBAM versus
pangemma on an LMDB store built from that same file): identical top marker
(rsm10000010578, p 1.04e-05), Spearman rho 0.999971, top-50 overlap 50/50,
median |difference in -log10 p| 0.00000.  The engines agree; what was left was
plumbing.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs20
-rw-r--r--src/gemma.rs12
-rw-r--r--src/routes/gemma.rs62
3 files changed, 90 insertions, 4 deletions
diff --git a/src/config.rs b/src/config.rs
index b937ce5..118b12b 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -554,7 +554,25 @@ impl Config {
             ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(),
             ravanan_batch: parse_ravanan_batch(&values),
             ravanan_scratch: values["RAVANAN_SCRATCH"].clone(),
-            prepare_genotypes: values["PREPARE_GENOTYPES"].clone(),
+            prepare_genotypes: {
+                // A relative default is fine when the server runs from its
+                // checkout, and silently fatal when it does not (measured: an
+                // instance started elsewhere answered "could not run
+                // scripts/prepare-genotypes.sh").  The workflow path already
+                // points into that checkout, so it is used to locate the
+                // scripts directory when the relative name does not resolve.
+                let configured = values["PREPARE_GENOTYPES"].clone();
+                let path = std::path::Path::new(&configured);
+                if path.is_absolute() || path.exists() {
+                    configured
+                } else {
+                    let workflow = std::path::Path::new(&values["GEMMA_RAVANAN_WORKFLOW"]);
+                    match workflow.parent().and_then(|cwl| cwl.parent()).and_then(|repo| repo.parent()) {
+                        Some(repo) => repo.join(&configured).to_string_lossy().into_owned(),
+                        None => configured,
+                    }
+                }
+            },
             rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(),
             fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(),
             qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(),
diff --git a/src/gemma.rs b/src/gemma.rs
index 02a2456..c502903 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -1255,8 +1255,18 @@ fn trait_input_key(kinship_key: &str, trait_values: &TraitValues) -> String {
 fn chromosomes_from(contents: &str) -> Vec<String> {
     let mut seen = std::collections::HashSet::new();
     let mut chromosomes = Vec::new();
+    // The SNP map is `marker, pos, chr` in the panel's own files (spaces after
+    // the commas) and `marker,pos,chr` in the ones scripts/qtl2-impute-bimbam.R
+    // writes.  Splitting on whitespace alone read the second form as one token
+    // and returned no chromosomes at all, which reaches ravanan as an empty
+    // scatter and comes back as "no association output files" -- a genotype
+    // problem that was really a delimiter problem.
     for line in contents.lines() {
-        if let Some(chr) = line.split_whitespace().nth(2) {
+        let fields: Vec<&str> = line
+            .split(|c: char| c.is_whitespace() || c == ',')
+            .filter(|field| !field.is_empty())
+            .collect();
+        if let Some(chr) = fields.get(2) {
             if seen.insert(chr.to_string()) {
                 chromosomes.push(chr.to_string());
             }
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 8c2c543..329158a 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -1113,6 +1113,33 @@ async fn prepare_genotypes(
     })
 }
 
+/// Re-order trait values to the individual order of a prepared genotype file.
+///
+/// `hmm` genotypes come from the qtl2 cross, whose individuals are the whole
+/// panel -- 235 for BXD.8 against the 198 that have trait values.  Passing the
+/// panel's positional values against those columns makes every individual
+/// missing, which GEMMA reports as "no individuals in common" and ravanan as
+/// "no association output files"; the fix is to write the phenotype by name in
+/// the genotype file's order.
+fn align_to_individuals(
+    individuals_path: &str,
+    names: &[String],
+    values: &[Option<f64>],
+) -> Result<Vec<Option<f64>>, std::io::Error> {
+    let by_name: std::collections::HashMap<&str, Option<f64>> = names
+        .iter()
+        .map(String::as_str)
+        .zip(values.iter().copied())
+        .collect();
+    let text = std::fs::read_to_string(individuals_path)?;
+    Ok(text
+        .lines()
+        .map(str::trim)
+        .filter(|name| !name.is_empty())
+        .map(|name| by_name.get(name).copied().flatten())
+        .collect())
+}
+
 #[utoipa::path(post, path = "/compute/gemma/ravanan",
     summary = "Map a QTL with GEMMA, run via ravanan instead of gemma-wrapper directly",
     description = "Same computation and request/response shape as POST \
@@ -1184,9 +1211,9 @@ pub async fn compute_gemma_ravanan(
     let ResolvedInputs {
         genotype_file,
         snps_file,
-        trait_values,
+        mut trait_values,
         individuals: panel_individuals,
-        names: _,
+        names: resolved_names,
         group: resolved_group,
         notes: input_notes,
     } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?;
@@ -1268,6 +1295,37 @@ pub async fn compute_gemma_ravanan(
         )
         .await?;
         impute_notes = prepared.notes;
+        if impute == "hmm" {
+            let individuals = format!(
+                "{}.individuals.txt",
+                prepared
+                    .genotype_file
+                    .trim_end_matches(".bimbam.txt")
+            );
+            if let Some(names) = resolved_names.as_deref() {
+                match align_to_individuals(&individuals, names, &trait_values) {
+                    Ok(aligned) => {
+                        impute_notes.push(format!(
+                            "genotypes: trait values aligned by name to the {} individuals of the \
+                             HMM calls ({} had a value in the panel)",
+                            aligned.len(),
+                            trait_values.iter().filter(|v| v.is_some()).count()
+                        ));
+                        trait_values = aligned;
+                    }
+                    Err(error) => {
+                        return Err(ApiError::new(
+                            StatusCode::INTERNAL_SERVER_ERROR,
+                            "internal_error",
+                            "Could not align individuals",
+                            format!("reading {individuals} failed: {error}"),
+                            "compute_gemma_ravanan",
+                        )
+                        .with_request_id(rid));
+                    }
+                }
+            }
+        }
         (prepared.genotype_file, prepared.snps_file)
     };