about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-11 17:04:58 +0000
committerPjotr <wrk@bosa.lan>2026-11-11 17:04:58 +0000
commit3a42b5ffae50093a04fbfd62ec463883b9e3f3b5 (patch)
tree1b5628e617949315ff847d068162d33d475ee243 /src
parent0751e56b5f56bca61b3599c0a96cfc5f0fd30f32 (diff)
downloadgenenetwork4-3a42b5ffae50093a04fbfd62ec463883b9e3f3b5.tar.gz
gemma: the pve note carries every chromosome, and the log carries the numbers
The note reported the range and named the two chromosomes that bounded it,
which is not enough to answer the question the numbers exist for. Under
--loco each pve belongs to a *different* kinship matrix, and GEMMA's
per-chromosome .log.txt files live on the server -- so a caller told "0.31
to 0.95" could not ask which chromosome was which, or compare a single
chromosome against BulkLMM.

The note now lists all twenty, compactly, with the range and the two
extremes keeping their vg/ve:

  GEMMA -pve, null model, per chromosome (LOCO): chr1 0.6674±0.3451,
  chr2 0.8426±0.3668, ..., chrX 0.8563±0.3525. That is pve 0.3118 to
  0.9549 over 20 chromosomes; lowest chr8 pve 0.3118 ± 0.5009 (vg
  23.3659, ve 12.3389), highest chr7 pve 0.9549 ± 0.3570 (vg 76.0933,
  ve 0.8661).

and streaming::append_lines puts the unrounded values in the run log as

  variance: chr7 pve=0.954938 se_pve=0.357032 vg=76.0933 ve=0.86612

so a ?id= run's /compute/gemma/status stream carries them while the run is
still in flight, rather than only in a reply someone has to keep. Both
measured on BXD::10001 through the dev server before committing.

The values are printed with four significant figures (scientific when the
magnitude needs it), unchanged: rounding variance components to four
decimals was the earlier bug, and these are the same numbers a reader
compares with BulkLMM's h2.

Docs: README's /compute/gemma section, SKILL's gemma bullet ("quote
per-chromosome values, not an average: they are twenty different kinship
matrices") and docs/bulklmm.md's example.
Diffstat (limited to 'src')
-rw-r--r--src/gemma.rs191
-rw-r--r--src/streaming.rs12
2 files changed, 145 insertions, 58 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 32670e6..e82e617 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -417,24 +417,49 @@ fn format_component(value: f64) -> String {
     }
 }
 
-/// One note for the variance components: a range over the chromosomes, and
-/// the two that bound it. Twenty chromosomes listed in full would bury the
-/// other notes, and every value is in the `.log.txt` beside the archive
-/// anyway -- so name the ends and point at the rest.
+/// One note carrying every chromosome's variance components.
+///
+/// All of them, not just the range: GEMMA's per-chromosome `.log.txt` files
+/// live on the server, so a caller that is told only "0.31 to 0.95" cannot
+/// ask which chromosome is which -- and under `--loco` that is the whole
+/// question, since each value belongs to a different kinship matrix. The
+/// values are written compactly (four significant figures each) so twenty
+/// chromosomes stay one readable sentence, with the two extremes carrying
+/// `vg`/`ve` as well.
 ///
 /// `pve` is the proportion of variance the kinship explains in the *null*
-/// model -- the same quantity as BulkLMM's `h2`, but per chromosome here,
-/// because `--loco` builds one kinship per chromosome.
+/// model -- the same quantity as BulkLMM's `h2`, per chromosome here.
 fn variance_components_note(components: &[(Option<String>, VarianceComponents)]) -> Option<String> {
     if components.is_empty() {
         return None;
     }
-    let label = |chr: &Option<String>| chr.clone().unwrap_or_else(|| "whole genome".to_string());
+    let label = |chr: &Option<String>| {
+        chr.clone()
+            .map(|chr| format!("chr{chr}"))
+            .unwrap_or_else(|| "whole genome".to_string())
+    };
+    let scored: Vec<(&Option<String>, &VarianceComponents)> = components
+        .iter()
+        .filter(|(_, c)| c.pve.is_some())
+        .map(|(chr, c)| (chr, c))
+        .collect();
+    if scored.is_empty() {
+        return None;
+    }
+
+    let per_chromosome: Vec<String> = scored
+        .iter()
+        .map(|(chr, c)| {
+            let se = c
+                .se_pve
+                .map(|se| format!("±{}", format_component(se)))
+                .unwrap_or_default();
+            format!("{} {}{se}", label(chr), format_component(c.pve.unwrap()))
+        })
+        .collect();
+
     let describe = |chr: &Option<String>, c: &VarianceComponents| {
-        let pve = c
-            .pve
-            .map(format_component)
-            .unwrap_or_else(|| "not reported".to_string());
+        let pve = format_component(c.pve.unwrap());
         let se = c
             .se_pve
             .map(|se| format!(" ± {}", format_component(se)))
@@ -450,49 +475,71 @@ fn variance_components_note(components: &[(Option<String>, VarianceComponents)])
         }
     };
 
-    let scored: Vec<(Option<String>, &VarianceComponents)> = components
-        .iter()
-        .filter(|(_, c)| c.pve.is_some())
-        .map(|(chr, c)| (chr.clone(), c))
-        .collect();
-    let note = match scored.len() {
-        0 => return None,
-        1 => {
-            let (chr, c) = &scored[0];
-            format!(
-                "GEMMA -pve, null model: {}. This is the proportion of variance the kinship \
-                 explains -- the same quantity as BulkLMM's h2 -- reported here for the null fit, \
-                 so it does not depend on any marker.",
-                describe(chr, c)
-            )
-        }
-        _ => {
-            let lowest = scored
-                .iter()
-                .min_by(|a, b| a.1.pve.unwrap().total_cmp(&b.1.pve.unwrap()))
-                .unwrap();
-            let highest = scored
-                .iter()
-                .max_by(|a, b| a.1.pve.unwrap().total_cmp(&b.1.pve.unwrap()))
-                .unwrap();
-            let min = lowest.1.pve.unwrap();
-            let max = highest.1.pve.unwrap();
-            format!(
-                "GEMMA -pve, null model, per chromosome (LOCO): pve {} to {} over {} chromosomes \
-                 -- lowest {}, highest {}. Each is the proportion of variance that chromosome's \
-                 kinship explains, i.e. BulkLMM's h2 computed per chromosome instead of \
-                 genome-wide; every chromosome's value is in the .log.txt beside the archive.",
-                format_component(min),
-                format_component(max),
-                scored.len(),
-                describe(&lowest.0, lowest.1),
-                describe(&highest.0, highest.1),
-            )
-        }
+    let note = if scored.len() == 1 {
+        format!(
+            "GEMMA -pve, null model: {}. This is the proportion of variance the kinship explains \
+             -- the same quantity as BulkLMM's h2 -- for the null fit, so it does not depend on any \
+             marker.",
+            describe(scored[0].0, scored[0].1)
+        )
+    } else {
+        let lowest = scored
+            .iter()
+            .min_by(|a, b| a.1.pve.unwrap().total_cmp(&b.1.pve.unwrap()))
+            .unwrap();
+        let highest = scored
+            .iter()
+            .max_by(|a, b| a.1.pve.unwrap().total_cmp(&b.1.pve.unwrap()))
+            .unwrap();
+        format!(
+            "GEMMA -pve, null model, per chromosome (LOCO): {}. That is pve {} to {} over {} \
+             chromosomes; lowest {}, highest {}. Each value is the proportion of variance that one \
+             chromosome's kinship explains -- BulkLMM's h2 computed per chromosome instead of \
+             genome-wide -- so they are not expected to agree with each other or to add up. The \
+             same numbers are in the run log and in GEMMA's own .log.txt beside the archive.",
+            per_chromosome.join(", "),
+            format_component(lowest.1.pve.unwrap()),
+            format_component(highest.1.pve.unwrap()),
+            scored.len(),
+            describe(lowest.0, lowest.1),
+            describe(highest.0, highest.1),
+        )
     };
     Some(note)
 }
 
+/// The same table as the note, as log lines, so a `?id=` run's
+/// `/compute/gemma/status` stream carries it too -- the caller watching a long
+/// run sees the variance components as soon as they exist, rather than having
+/// to keep the finished reply.
+fn variance_components_log_lines(
+    components: &[(Option<String>, VarianceComponents)],
+) -> Vec<String> {
+    components
+        .iter()
+        .filter(|(_, c)| c.pve.is_some())
+        .map(|(chr, c)| {
+            let mut line = format!(
+                "variance: {} pve={}",
+                chr.clone()
+                    .map(|chr| format!("chr{chr}"))
+                    .unwrap_or_else(|| "genome".to_string()),
+                c.pve.unwrap()
+            );
+            if let Some(se) = c.se_pve {
+                line.push_str(&format!(" se_pve={se}"));
+            }
+            if let Some(vg) = c.vg {
+                line.push_str(&format!(" vg={vg}"));
+            }
+            if let Some(ve) = c.ve {
+                line.push_str(&format!(" ve={ve}"));
+            }
+            line
+        })
+        .collect()
+}
+
 /// Parse a GEMMA `.assoc.txt` file (tab-separated, header row first)
 /// into its column names and one row per marker, each row a
 /// `Value::Array` in that same column order (not keyed by column name:
@@ -842,12 +889,13 @@ 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 components = read_variance_components(cache_dir, &gwa_record);
         let mut output_notes = vec![kinship_note, gwa_note];
         output_notes.extend(notes);
-        if let Some(note) = variance_components_note(&read_variance_components(cache_dir, &gwa_record))
-        {
+        if let Some(note) = variance_components_note(&components) {
             output_notes.push(note);
         }
+        streaming::append_lines(&log_path, &variance_components_log_lines(&components));
         Ok(GemmaOutput {
             columns,
             rows: Value::Array(rows),
@@ -1329,9 +1377,11 @@ mod tests {
         );
     }
 
-    /// The range, with the two chromosomes that bound it -- not all twenty.
+    /// Every chromosome's value is in the note: GEMMA's per-chromosome logs
+    /// live on the server, so a caller told only "0.40 to 0.62" cannot ask
+    /// which chromosome is which.
     #[test]
-    fn the_note_gives_the_range_and_names_the_extremes() {
+    fn every_chromosome_appears_in_the_note() {
         let components = vec![
             (
                 Some("1".to_string()),
@@ -1362,10 +1412,13 @@ mod tests {
             ),
         ];
         let note = variance_components_note(&components).unwrap();
+        assert!(note.contains("chr1 0.4000±0.0200"), "{note}");
+        assert!(note.contains("chr2 0.6200"), "{note}");
+        assert!(note.contains("chr3 0.5100±0.0100"), "{note}");
         assert!(note.contains("pve 0.4000 to 0.6200 over 3 chromosomes"), "{note}");
-        assert!(note.contains("lowest 1 pve 0.4000 ± 0.0200"), "{note}");
-        assert!(note.contains("highest 2 pve 0.6200"), "{note}");
-        assert!(!note.contains("3 pve"), "the middle one is not listed: {note}");
+        // The extremes also say what they are made of.
+        assert!(note.contains("lowest chr1 pve 0.4000 ± 0.0200 (vg 1.0000, ve 1.5000)"), "{note}");
+        assert!(note.contains("highest chr2 pve 0.6200"), "{note}");
         assert!(note.contains("LOCO"), "{note}");
     }
 
@@ -1383,10 +1436,32 @@ mod tests {
             },
         )];
         let note = variance_components_note(&components).unwrap();
-        assert!(note.contains("1 pve 0.6170 ± 0.0306"), "{note}");
+        assert!(note.contains("chr1 pve 0.6170 ± 0.0306"), "{note}");
         assert!(!note.contains(" to "), "{note}");
     }
 
+    /// The log lines carry the unrounded numbers, because that is what a
+    /// caller comparing engines wants to compute with, and because a
+    /// `?id=` run is watched rather than returned.
+    #[test]
+    fn the_log_lines_carry_every_chromosome_unrounded() {
+        let components = vec![(
+            Some("7".to_string()),
+            VarianceComponents {
+                pve: Some(0.9549),
+                se_pve: Some(0.357),
+                vg: Some(76.0933),
+                ve: Some(0.8661),
+            },
+        )];
+        let lines = variance_components_log_lines(&components);
+        assert_eq!(lines.len(), 1);
+        assert!(lines[0].contains("variance: chr7 pve=0.9549"), "{}", lines[0]);
+        assert!(lines[0].contains("se_pve=0.357"), "{}", lines[0]);
+        assert!(lines[0].contains("vg=76.0933"), "{}", lines[0]);
+        assert!(lines[0].contains("ve=0.8661"), "{}", lines[0]);
+    }
+
     #[test]
     fn no_logs_yields_no_note() {
         assert_eq!(variance_components_note(&[]), None);
diff --git a/src/streaming.rs b/src/streaming.rs
index 5b19501..bba5c54 100644
--- a/src/streaming.rs
+++ b/src/streaming.rs
@@ -110,6 +110,18 @@ pub fn mark_complete(log_path: &Option<PathBuf>) {
     }
 }
 
+/// Append lines to `log_path`, if there is one. Best effort, like the
+/// markers: a caller that asked for a log gets the server's own summary lines
+/// (e.g. `pve:` per chromosome) in the same stream as the child's output.
+pub fn append_lines(log_path: &Option<PathBuf>, lines: &[String]) {
+    let Some(path) = log_path else { return };
+    if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) {
+        for line in lines {
+            let _ = writeln!(f, "{line}");
+        }
+    }
+}
+
 /// Append `FAILURE_MARKER: <error>` to `log_path`, if there is one.
 /// Best effort, like [`mark_complete`]: a failure here (e.g. the log
 /// was deleted mid-run) must never mask the computation error it is