about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-09 18:21:00 +0000
committerPjotr <wrk@bosa.lan>2026-11-09 18:21:00 +0000
commiteb5320d6f51279acf0b65e5bc9755eec927c93ea (patch)
tree9c928ea111cea1151cc96c1d17da0521b831ef79 /src
parent971a619fd28e247bf89057c0a72d1b4f51272a31 (diff)
downloadgenenetwork4-eb5320d6f51279acf0b65e5bc9755eec927c93ea.tar.gz
gemma: leave out individuals with no genotypes, which make the kinship singular
Asking whether the singular matrices could be fixed turned out to have two
answers, one of them a real bug on our side.

The bug: a panel can name individuals whose genotype row is empty, and an
empty row makes the kinship matrix singular. GEMMA then reports
"eigenvalues close to zero" and dies in LAPACK with
`LUDecomp ... input domain error` -- a message about linear algebra for a
problem that is a missing genotype. Measured on this deployment's own files:

  BXD-AE.4             136 of 344 individuals have no genotypes
  MDP                   93 of 178
  BXD-Heart-Metals.4   200 of 481
  HET3-ITP.3          2867 of 2867  (the whole file is empty)

Dropping them makes those panels map: BXD-AE.4's GWA step goes from a
failure to 3.2 s, and MDP's kinship step from a failure to success. The
individuals contribute nothing to a scan either way, so nothing is lost;
`notes` counts them, and the "Genotype:" line no longer blames parents/F1s
for them (`prepared.excluded` is "panel minus kept", which now includes
both, so the two counts are separated).

Not the cause, but worth naming: `AXB` fails earlier still, on its
annotation -- `ERROR: Enforce failed for D1Mit296 in src/gemma_io.cpp ...
ReadFile_anno` -- which is a broken `.snps` file, not a matrix. That wants a
pre-flight check of the annotation (report the offending marker) rather
than a GEMMA failure, and is not in this commit.

Considered and rejected: a ridge on K (`K + epsilon*I`) would work
mathematically but GEMMA has no option for it and the wrapper caches K by
content hash, so it would mean patching the wrapper's cached matrix; `-gk 2`
and dropping markers do not add rank; and the non-LOCO path is the one that
does not run at all here.

* src/genotypes.rs: `individuals_with_genotypes`, one pass over the bimbam
  file marking the individuals with any genotype at all.
* src/routes/gemma.rs: filter `keep` by it before alignment (so the trait
  values drop with them), and say so in `notes`.
* tests/gemma.rs: `individuals_with_no_genotypes_are_left_out` -- BXD-AE.4
  maps, the note names the drop and the reason, and the genotype line no
  longer claims 344 individuals.
* README.md: the behaviour and why it exists, under /compute/gemma.

307 tests pass; the same four as before do not.
Diffstat (limited to 'src')
-rw-r--r--src/genotypes.rs43
-rw-r--r--src/routes/gemma.rs36
2 files changed, 75 insertions, 4 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs
index 335fceb..a2586f0 100644
--- a/src/genotypes.rs
+++ b/src/genotypes.rs
@@ -860,3 +860,46 @@ mod tests {
         assert_eq!(prepared.excluded, 1);
     }
 }
+
+/// Which individuals in a BIMBAM genotype file have any genotype at all.
+///
+/// GEMMA imputes a *missing* genotype with the SNP mean, but an individual
+/// with no genotypes anywhere contributes an empty row to the kinship
+/// matrix, and the resulting K is singular: the run dies inside LAPACK
+/// ("eigenvalues close to zero" then `LUDecomp ... input domain error`), a
+/// message that says nothing about the cause. Measured on this deployment:
+/// `BXD-AE.4` has 136 of 344 individuals like that, `MDP` 93 of 178,
+/// `BXD-Heart-Metals.4` 200 of 481 -- and dropping them makes those panels
+/// map in seconds.
+///
+/// Returns one flag per individual, in the file's column order; `None` when
+/// the file cannot be read (the caller then proceeds as before rather than
+/// refusing the run).
+pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> {
+    let text = std::fs::read_to_string(geno).ok()?;
+    let mut mask: Option<Vec<bool>> = None;
+    for line in text.lines() {
+        let line = line.trim();
+        if line.is_empty() || line.starts_with('#') || line.starts_with('@') {
+            continue;
+        }
+        let fields: Vec<&str> = line
+            .split(|c: char| c == ',' || c.is_whitespace())
+            .filter(|field| !field.is_empty())
+            .collect();
+        if fields.len() < 4 {
+            continue;
+        }
+        let genotypes = &fields[3..];
+        let mask = mask.get_or_insert_with(|| vec![false; genotypes.len()]);
+        if genotypes.len() != mask.len() {
+            continue;
+        }
+        for (index, value) in genotypes.iter().enumerate() {
+            if !matches!(*value, "NA" | "na" | "." | "") {
+                mask[index] = true;
+            }
+        }
+    }
+    mask
+}
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index a00aaf6..f31ffef 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -282,7 +282,7 @@ pub async fn compute_gemma(
                 let wanted = group.clone();
                 let had_samples = request.samples.is_some();
                 let supplied_values = request.trait_values.clone();
-                let (prepared, aligned, matched, resolved, kept_names) =
+                let (prepared, aligned, matched, resolved, kept_names, dropped_empty) =
                     tokio::task::spawn_blocking(move || {
                         let resolved = genotypes::resolve(&directory, &wanted, version.as_deref())?;
                         let excluded = if include_parents_f1 {
@@ -297,6 +297,22 @@ pub async fn compute_gemma(
                             .filter(|(_, name)| !excluded.contains(*name))
                             .map(|(index, _)| index)
                             .collect();
+                        // An individual with no genotypes at all makes the
+                        // kinship singular (see genotypes::individuals_with_genotypes),
+                        // so leave those out before anything else is aligned:
+                        // they contribute nothing to the fit either.
+                        let empty = resolved
+                            .bimbam_geno
+                            .as_deref()
+                            .and_then(genotypes::individuals_with_genotypes);
+                        let keep: Vec<usize> = match empty {
+                            Some(mask) => keep
+                                .into_iter()
+                                .filter(|index| mask.get(*index).copied().unwrap_or(true))
+                                .collect(),
+                            None => keep,
+                        };
+                        let dropped_empty = resolved.panel.len() - excluded.len() - keep.len();
                         let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values);
                         let kept_names: Vec<String> = keep
                             .iter()
@@ -310,7 +326,7 @@ pub async fn compute_gemma(
                             &cache_dir,
                         )?;
                         Ok::<_, genotypes::GenotypeError>((
-                            prepared, aligned, matched, resolved, kept_names,
+                            prepared, aligned, matched, resolved, kept_names, dropped_empty,
                         ))
                     })
                     .await
@@ -378,9 +394,21 @@ pub async fn compute_gemma(
                     }
                     supplied
                 };
+                // `prepared.excluded` is "panel minus kept", which now also
+                // counts the genotype-less individuals; keep the two apart so
+                // the note never blames parents/F1s for a missing-genotype
+                // panel.
+                let parents_f1s = prepared.excluded.saturating_sub(dropped_empty);
+                let empty_clause = if dropped_empty > 0 {
+                    format!(
+                        ", {dropped_empty} left out with no genotypes at all (an empty kinship                          row makes the matrix singular)"
+                    )
+                } else {
+                    String::new()
+                };
                 extra_notes.push(format!(
-                    "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped); {} values used.",
-                    prepared.note, resolved.version, individuals, prepared.excluded,
+                    "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped{empty_clause}); {} values used.",
+                    prepared.note, resolved.version, individuals, parents_f1s,
                     trait_values.iter().filter(|value| value.is_some()).count()
                 ));
                 (