diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-11 15:54:15 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-11 15:54:15 +0000 |
| commit | cd3e65b6a03827d328aecb88c94406e85e5c161b (patch) | |
| tree | e1e9eeeea62db5abcac7bfd466a05bfce5547e1d /src | |
| parent | 54d704ab7a6ec6e39ccb66e08c2334652a437cfa (diff) | |
| download | genenetwork4-cd3e65b6a03827d328aecb88c94406e85e5c161b.tar.gz | |
gemma: report GEMMA's own pve for the null model
The GWA step now passes -pve, and the reply gains a note with the variance components GEMMA computed for the null model. Under --loco there is one per chromosome, so the note gives their range and names the two that bound it: GEMMA -pve, null model, per chromosome (LOCO): pve 0.3118 to 0.9549 over 20 chromosomes -- lowest 8 pve 0.3118 +/- 0.5009 (vg 23.3659, ve 12.3389), highest 7 pve 0.9549 +/- 0.3570 (vg 76.0933, ve 0.8661). That is BXD::10001 measured, not assumed. pve is the proportion of variance the kinship explains -- the same quantity as /compute/bulklmm's h2, per chromosome rather than genome-wide -- which is what the 16627/16769 comparison against BulkLMM needed. Reading the numbers took three decisions worth stating: - Four decimals is wrong for variance components. The first live run reported 'vg 0.0000, ve 0.0000' for a BXD::16769 null fit whose real components are 3.411e-5 and 3.411e-10 -- both rounded to zero, which reads as 'no variance' when the split is 1.0. Components are printed with four significant figures, scientific when the magnitude needs it, the way GEMMA's own logs do with %g. - se(pve) is -nan on a boundary, and Rust parses -nan as a NaN f64, so the numeric parse alone let it through as NaN. Non-finite values are now 'not available': a boundary estimate has no standard error. - Twenty chromosomes of values bury the other notes, and every value is in the .log.txt beside the archive anyway, so the note names the ends. Requires gemma-wrapper 5eb53fa, which keeps each run's .log.txt beside its archive instead of only inside the .tar.xz. Docs: README's /compute/gemma section, SKILL's gemma bullet (compare pve with h2, never vg with sigma2_e -- pve is scale-free), and docs/bulklmm.md's 'what would settle it', which now says the plumbing is in rather than pending.
Diffstat (limited to 'src')
| -rw-r--r-- | src/gemma.rs | 331 |
1 files changed, 330 insertions, 1 deletions
diff --git a/src/gemma.rs b/src/gemma.rs index c48e3fd..32670e6 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -301,6 +301,198 @@ fn assoc_file_basenames(record: &Value) -> Vec<&str> { .unwrap_or_default() } +/// The per-chromosome `.log.txt` basenames gemma-wrapper recorded for a +/// step, taken from the second element of every `files` entry. +fn log_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(1)?.as_str()) + .collect() + }) + .unwrap_or_default() +} + +/// GEMMA's own variance components for one chromosome, as `-pve` writes +/// them: +/// +/// ```text +/// ## pve estimate in the null model = 0.612 +/// ## se(pve) in the null model = 0.031 +/// ## vg estimate in the null model = 1.4 +/// ## ve estimate in the null model = 0.9 +/// ``` +/// +/// All four are optional individually: GEMMA prints `-nan` for `se(pve)` +/// when the estimate sits on a boundary (`h2 = 0` or `1`), and older +/// builds print nothing at all without `-pve`. +#[derive(Debug, Clone, PartialEq)] +pub struct VarianceComponents { + pub pve: Option<f64>, + pub se_pve: Option<f64>, + pub vg: Option<f64>, + pub ve: Option<f64>, +} + +fn parse_variance_components(log: &str) -> VarianceComponents { + fn value_after<'a>(log: &'a str, marker: &str) -> Option<&'a str> { + log.lines() + .find_map(|line| line.trim().strip_prefix(marker)) + .map(|rest| rest.trim_start_matches([' ', '=']).trim()) + } + fn number(text: Option<&str>) -> Option<f64> { + // GEMMA prints `-nan` (and `nan`) on a boundary, and Rust parses both + // as a NaN f64 -- so the finite check is what rejects them. A boundary + // estimate has no standard error to report, and `None` says so; a NaN + // in the reply would be worse than nothing. + text.and_then(|t| t.parse::<f64>().ok()) + .filter(|value| value.is_finite()) + } + VarianceComponents { + pve: number(value_after(log, "## pve estimate in the null model")), + se_pve: number(value_after(log, "## se(pve) in the null model")), + vg: number(value_after(log, "## vg estimate in the null model")), + ve: number(value_after(log, "## ve estimate in the null model")), + } +} + +/// Read the variance components gemma-wrapper left beside the archive, one +/// per chromosome. Missing logs (an older wrapper, a cache hit from before +/// the logs were kept) yield an empty vector rather than an error: the +/// association scan is the result, these are commentary on it. +fn read_variance_components( + cache_dir: &str, + record: &Value, +) -> Vec<(Option<String>, VarianceComponents)> { + let chromosomes: Vec<Option<String>> = record + .get("files") + .and_then(Value::as_array) + .map(|files| { + files + .iter() + .map(|entry| entry.as_array().and_then(|e| e.first()).and_then(|c| { + // `null` for the whole-genome (non-LOCO) case. + match c { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + } + })) + .collect() + }) + .unwrap_or_default(); + log_file_basenames(record) + .into_iter() + .enumerate() + .filter_map(|(index, basename)| { + let path = Path::new(cache_dir).join(basename); + let log = std::fs::read_to_string(&path).ok()?; + let components = parse_variance_components(&log); + if components.pve.is_none() && components.vg.is_none() && components.ve.is_none() { + return None; + } + Some((chromosomes.get(index).cloned().flatten(), components)) + }) + .collect() +} + +/// Four significant figures, scientific when the magnitude needs it. +/// +/// Variance components are not all O(1): a null fit with a near-zero +/// residual prints `vg = 3.4e-05` and `ve = 3.4e-10`, and rounding those to +/// four decimals reports 0.0000 for both -- which would read as "GEMMA found +/// no variance" when what it found was that the split is 1.0. GEMMA's own +/// logs use `%g` for the same reason. +fn format_component(value: f64) -> String { + let magnitude = value.abs(); + if magnitude == 0.0 { + "0".to_string() + } else if (1e-3..1e4).contains(&magnitude) { + format!("{value:.4}") + } else { + format!("{value:.3e}") + } +} + +/// 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. +/// +/// `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. +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 describe = |chr: &Option<String>, c: &VarianceComponents| { + let pve = c + .pve + .map(format_component) + .unwrap_or_else(|| "not reported".to_string()); + let se = c + .se_pve + .map(|se| format!(" ± {}", format_component(se))) + .unwrap_or_default(); + match (c.vg, c.ve) { + (Some(vg), Some(ve)) => format!( + "{} pve {pve}{se} (vg {}, ve {})", + label(chr), + format_component(vg), + format_component(ve) + ), + _ => format!("{} pve {pve}{se}", label(chr)), + } + }; + + 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), + ) + } + }; + Some(note) +} + /// 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: @@ -497,6 +689,12 @@ fn gwa_args<'a>( } args.push("-lmm"); args.push(lmm_str); + // Ask GEMMA for its own variance components in the null model. It writes + // them into the per-run `.log.txt`, which gemma-wrapper keeps beside the + // archive; `-pve` is accepted alongside `-lmm 9` (verified against GEMMA + // 0.98.6 on a BIMBAM fixture). It changes nothing in `.assoc.txt`, so it + // costs four log lines and no recomputation of the scan. + args.push("-pve"); args } @@ -646,6 +844,10 @@ pub async fn compute( 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)) + { + output_notes.push(note); + } Ok(GemmaOutput { columns, rows: Value::Array(rows), @@ -1073,6 +1275,132 @@ mod tests { } #[test] + fn variance_components_are_read_from_gemmas_pve_block() { + let log = "## Command Line Input = gemma -lmm 9 -pve\n\ + total computation time = 12.5 s\n\ + ## pve estimate in the null model = 0.61702\n\ + ## se(pve) in the null model = 0.0306283\n\ + ## vg estimate in the null model = 1.4402\n\ + ## ve estimate in the null model = 0.8941\n"; + let components = parse_variance_components(log); + assert!((components.pve.unwrap() - 0.61702).abs() < 1e-12); + assert!((components.se_pve.unwrap() - 0.0306283).abs() < 1e-12); + assert!((components.vg.unwrap() - 1.4402).abs() < 1e-12); + assert!((components.ve.unwrap() - 0.8941).abs() < 1e-12); + } + + /// GEMMA prints `-nan` for the standard error when the estimate sits on a + /// boundary. That is not a number to report, and reporting it as 0 would + /// be a lie: `None` says "not available". + #[test] + fn a_boundary_estimate_reports_no_standard_error() { + let log = "## pve estimate in the null model = 1.62846e-06\n\ + ## se(pve) in the null model = -nan\n\ + ## vg estimate in the null model = 0\n\ + ## ve estimate in the null model = 0\n"; + let components = parse_variance_components(log); + assert!(components.pve.is_some()); + assert_eq!(components.se_pve, None); + } + + /// The case that made this necessary: GEMMA reported vg = 3.4e-05 and + /// ve = 3.4e-10 on a boundary null fit, and four decimals says 0.0000 for + /// both. + #[test] + fn tiny_variance_components_are_not_rounded_to_zero() { + assert_eq!(format_component(3.41066e-05), "3.411e-5"); + assert_eq!(format_component(3.41066e-10), "3.411e-10"); + assert_eq!(format_component(0.0), "0"); + assert_eq!(format_component(0.61702), "0.6170"); + assert_eq!(format_component(1.0), "1.0000"); + } + + #[test] + fn a_log_without_the_block_yields_nothing() { + let components = parse_variance_components("total computation time = 1 s\n"); + assert_eq!( + components, + VarianceComponents { + pve: None, + se_pve: None, + vg: None, + ve: None + } + ); + } + + /// The range, with the two chromosomes that bound it -- not all twenty. + #[test] + fn the_note_gives_the_range_and_names_the_extremes() { + let components = vec![ + ( + Some("1".to_string()), + VarianceComponents { + pve: Some(0.4), + se_pve: Some(0.02), + vg: Some(1.0), + ve: Some(1.5), + }, + ), + ( + Some("2".to_string()), + VarianceComponents { + pve: Some(0.62), + se_pve: None, + vg: None, + ve: None, + }, + ), + ( + Some("3".to_string()), + VarianceComponents { + pve: Some(0.51), + se_pve: Some(0.01), + vg: Some(2.0), + ve: Some(1.0), + }, + ), + ]; + let note = variance_components_note(&components).unwrap(); + 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}"); + assert!(note.contains("LOCO"), "{note}"); + } + + /// One chromosome (a non-LOCO run, or a panel with one chromosome) + /// reports the single value rather than a range of one. + #[test] + fn a_single_chromosome_reports_one_value() { + let components = vec![( + Some("1".to_string()), + VarianceComponents { + pve: Some(0.61702), + se_pve: Some(0.0306), + vg: Some(1.4402), + ve: Some(0.8941), + }, + )]; + let note = variance_components_note(&components).unwrap(); + assert!(note.contains("1 pve 0.6170 ± 0.0306"), "{note}"); + assert!(!note.contains(" to "), "{note}"); + } + + #[test] + fn no_logs_yields_no_note() { + assert_eq!(variance_components_note(&[]), None); + } + + #[test] + fn log_basenames_read_the_second_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!(log_file_basenames(&record), vec!["a.log.txt", "b.log.txt"]); + } + + #[test] fn parse_wrapper_output_rejects_non_zero_errno() { use std::os::unix::process::ExitStatusExt; let output = Output { @@ -1144,7 +1472,8 @@ mod tests { "-a", "snps.txt", "-lmm", - "9" + "9", + "-pve" ] ); assert!( |
