about summary refs log tree commit diff
path: root/src/gemma.rs
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-08 15:39:12 +0000
committerPjotr <wrk@bosa.lan>2026-11-08 15:39:12 +0000
commit336f18e1bc22cb330052dc1ff45d1d06073bfcc3 (patch)
tree4c029b46500edab067b35424b9e9ebbc7156221a /src/gemma.rs
parentfb41143226f7e0231f863a8226ba077c7415b71f (diff)
downloadgenenetwork4-336f18e1bc22cb330052dc1ff45d1d06073bfcc3.tar.gz
compute: fit covariates in GEMMA, and share them with R/qtl
`POST /compute/gemma` now takes the same `covariates` list `/compute/rqtl`
does -- `{"case_attribute": "Status"}`, an explicit `map`, or per-sample
numbers -- and fits it with `-c` on the association step only. That needed
a covariate file of GEMMA's own, which is not R/qtl's: no header, no sample
names, positional over the genotype panel, numbers only. GEMMA has no
factors, so a categorical covariate is dummy-expanded here into k-1
columns named after their levels (`Status.Live`, the first level being the
reference), where R/qtl's wrapper does that expansion for itself.

The spec shape, the alignment onto the panel and the text coding are now
one module, `src/covariates.rs`, called by both routes; `/compute/rqtl`
behaves as before except that its note also reports the complete cases
(`... 34 with both the trait and the covariate`), which README and the
instructions had been promising all along.

A missing covariate value is written `NA`, which GEMMA treats exactly as
it treats a missing phenotype -- that individual leaves the fit (measured:
one fewer "number of analyzed individuals"). Deliberately not GeneNetwork2's
`-9`, which GEMMA fits as the value minus nine.

Found on live data, not in the fixtures: a level that exists in the panel
but that none of the *fitted* individuals carries becomes an all-zero dummy
column, and GEMMA stops with `LUDecomp ... input domain error` rather than
dropping the term the way R would. Columns that do not vary among the
individuals with both a trait and a covariate are now left out, and the
response names them (`Status.Cyro`, the `Cyro`/`Cryo` typo in BXD); a
covariate left with no columns runs without one, with a note saying so.

Covariates reach only the GWA step, never `-gk`, and gemma-wrapper hashes
its file arguments, so a different covariate set is a different cache entry
while the kinship already computed is still reused. Covariates need a
`group`: individuals are aligned by name, which an explicit
`genotype_file`/`snps_file` request does not carry (`422
covariate_unavailable`), and an attribute the group does not define lists
the ones it has.

* src/covariates.rs (new): `Spec`/`NamedValue` (the request shape, now
  `CovariateSpec`/`CovariateValue` in the OpenAPI document), `Level`,
  `Covariate`, `code_case_attribute`, `resolve`, `write_covarstruct_file`
  (moved out of src/rqtl.rs) and `write_gemma_covariates_file`.
* src/gemma.rs (gwa_args, compute, compute_gwa): the optional covariate
  file, `-c` after `-a` and before `-lmm`, and the notes about dropped
  individuals and dropped columns.
* src/routes/gemma.rs: the `covariates` field, resolved after the trait
  values so the note can count complete cases; `RqtlCovariate` replaced by
  the shared spec.
* tests: six new -- the GEMMA file (numerical with `NA`; two and three
  levels; inline codes; a dropped degenerate column) and an end-to-end
  `compute_gemma_fits_a_case_attribute_as_a_covariate` on BXD/BXD.4 with
  `Status`, which also pins that `-c` is in the GWA command and not in the
  kinship one, and that the covariate changes the fit rather than reusing
  the plain run's cache. The gemma tests now take a lock: the gate answers
  a second job from the same caller with 409 instead of queueing it.
* README.md (/compute/gemma covariates rewritten for GEMMA, /compute/rqtl
  points at the shared shape and explains `x` vs `NA`), docs/www/
  ai-instruction.md (both endpoints; what differs in `notes`).

Also in the instructions: `/version` reporting a `git` value you have not
seen before now says explicitly to pull the repository and re-read
`docs/www/ai-instruction.md` before the next call. This deployment is
updated in place and a stale page does not announce itself -- the API
accepts the request without the new option, or answers with fields the old
text never mentions.

272 tests pass; the four that do not (benchmark, no_db, and two search
parity/proxy replays) fail identically at the parent commit.
Diffstat (limited to 'src/gemma.rs')
-rw-r--r--src/gemma.rs65
1 files changed, 60 insertions, 5 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 2647d9c..2c6c7d2 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -213,6 +213,7 @@ async fn compute_gwa(
     snps_file: &str,
     lmm: u8,
     k_json_path: &str,
+    covariate_file: Option<&str>,
     log_path: Option<&Path>,
 ) -> Result<Value, GemmaError> {
     let lmm_str = lmm.to_string();
@@ -221,6 +222,7 @@ async fn compute_gwa(
         genotype_file,
         pheno_file,
         snps_file,
+        covariate_file,
         &lmm_str,
         k_json_path,
     );
@@ -374,10 +376,11 @@ fn gwa_args<'a>(
     genotype_file: &'a str,
     pheno_file: &'a str,
     snps_file: &'a str,
+    covariate_file: Option<&'a str>,
     lmm_str: &'a str,
     k_json_path: &'a str,
 ) -> Vec<&'a str> {
-    vec![
+    let mut args = vec![
         "--json",
         "--cache-dir",
         cache_dir,
@@ -391,9 +394,17 @@ fn gwa_args<'a>(
         pheno_file,
         "-a",
         snps_file,
-        "-lmm",
-        lmm_str,
-    ]
+    ];
+    // Covariates reach only the GWA step: -gk (kinship) takes none, and
+    // GEMMA's own key for the K cache drops the phenotype pair, so the
+    // kinship computed once is still shared across covariate sets.
+    if let Some(covariate_file) = covariate_file {
+        args.push("-c");
+        args.push(covariate_file);
+    }
+    args.push("-lmm");
+    args.push(lmm_str);
+    args
 }
 
 /// Run the full gemma-wrapper flow -- compute kinship, then run the LMM
@@ -411,6 +422,7 @@ pub async fn compute(
     genotype_file: &str,
     snps_file: &str,
     trait_values: &TraitValues,
+    covariates: &[crate::covariates::Covariate],
     lmm: u8,
     run_id: Option<&str>,
 ) -> Result<GemmaOutput, GemmaError> {
@@ -420,6 +432,44 @@ pub async fn compute(
     write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?;
     let pheno_file = pheno_path.to_string_lossy().into_owned();
 
+    // GEMMA's own covariate file: positional over the panel, numeric, with
+    // `NA` for a missing value -- which it treats like a missing phenotype
+    // and drops the individual for (see crate::covariates).
+    let covariate_path = Path::new(cache_dir).join(format!("{unique}-covariates.txt"));
+    let mut notes: Vec<String> = Vec::new();
+    let covariate_file = if covariates.is_empty() {
+        None
+    } else {
+        let written = crate::covariates::write_gemma_covariates_file(
+            &covariate_path,
+            covariates,
+            &trait_values.iter().map(Option::is_some).collect::<Vec<bool>>(),
+        )
+        .map_err(GemmaError::Io)?;
+        for (name, absent) in &written.missing {
+            notes.push(format!(
+                "Missing covariate values: {name} has none for {absent} individual(s), which \
+                 GEMMA drops, as it drops a missing phenotype."
+            ));
+        }
+        if !written.dropped.is_empty() {
+            notes.push(format!(
+                "Covariate column(s) left out because they do not vary among the individuals \
+                 fitted: {}.",
+                written.dropped.join(", ")
+            ));
+        }
+        if written.columns.is_empty() {
+            notes.push(
+                "No covariate varies among the individuals fitted, so GEMMA ran without one."
+                    .to_string(),
+            );
+            None
+        } else {
+            Some(covariate_path.to_string_lossy().into_owned())
+        }
+    };
+
     // One log file for the whole request (both steps); see
     // crate::streaming::create_run_log for why this can't silently
     // collide with another run's.
@@ -455,6 +505,7 @@ pub async fn compute(
                 genotype_file,
                 &pheno_file,
                 snps_file,
+                covariate_file.as_deref(),
                 &lmm_str,
                 &k_json_path.to_string_lossy(),
             )
@@ -468,6 +519,7 @@ pub async fn compute(
             snps_file,
             lmm,
             &k_json_path.to_string_lossy(),
+            covariate_file.as_deref(),
             log_path.as_deref(),
         )
         .await?;
@@ -490,10 +542,12 @@ pub async fn compute(
         let (columns, rows) = parse_assoc_files(&extract_dir, basenames)?;
         let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless
 
+        let mut output_notes = vec![kinship_note, gwa_note];
+        output_notes.extend(notes);
         Ok(GemmaOutput {
             columns,
             rows: Value::Array(rows),
-            notes: vec![kinship_note, gwa_note],
+            notes: output_notes,
         })
     }
     .await;
@@ -967,6 +1021,7 @@ mod tests {
             "geno.txt.gz",
             "pheno.txt",
             "snps.txt",
+            None,
             "9",
             "/cache/k.json",
         );