about summary refs log tree commit diff
path: root/tests
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-10 11:25:49 +0000
committerPjotr <wrk@bosa.lan>2026-11-10 11:25:49 +0000
commit8f4a9512d7fb4ac518341f23a4b062ccf80e2a7d (patch)
tree698de016efbd16f2a659eac3f57c8df40babdf2f /tests
parent7646276e63fb7c4a7433530cfc3314ace3d362d8 (diff)
downloadgenenetwork4-8f4a9512d7fb4ac518341f23a4b062ccf80e2a7d.tar.gz
compute/qtl2: multiparent crosses, by name
A multiparent population cannot come from a .geno. That file carries two
codes per marker (B/D, A/H/B) -- a collapse, not a founder allele -- and
the collapse is not invertible, so DOL's 194 DO animals cannot be fitted
as a DO however much reference data appears. What can be is a cross that
ships its own qtl2 control file with founder genotypes, so the endpoint
now takes one by name:

  {"rqtl2_cross": "do", "trait_name": "DO::10001 (WBC)", "samples": ...}

  * resolve_control_file looks in genotype/rqtl2/{name}.json, then
    {name}/{name}.json (do/do.json), then {name}.json under
    GENOTYPE_FILES; prepare_control_cross reads the cross's pheno, maps
    and founder_geno headers without converting anything. It reports
    crosstype, founders and whether the cross is multiparent, and
    refuses a multiparent crosstype with no founder_geno rather than
    silently scanning it as biallelic.
  * Samples are matched to the cross's own population by name and the
    strays are counted in notes; rqtl2_cross cannot be combined with
    group or genotype_file.
  * The gate is given individuals x founders, because a multiparent scan
    fits one coefficient per founder allele at every marker.
  * Autosomes only now applies to shipped crosses as well: the DO's X is
    left out (369 markers) instead of being fitted without a sex
    covariate, and the script subsets with cross[, chr = autosomal].

Measured on the DO (WBC, 742 individuals, 8 founders, 6044 autosomal
markers): probabilities 174 s / 1.39 GB (cached), LOCO kinship 15 s
(cached), scan 21 s. scan1 runs on one core for a multiparent cross
because its forked path stalls on allele probabilities here -- 25+
minutes at 8 cores with no CPU consumed, against 21 s serial.

Two bugs found by running an actual published trait through it:

  * do_pmap.csv is in Mb, not the bp qtl2 documents, so every DO peak was
    reported at 0.0 Mb. The map's unit is now detected from its largest
    position and printed.
  * The phenotype file was read with the default whitespace separator, so
    a label with a space ("DO::10001 (WBC)") split into three fields and
    read.table stopped with "line 1 did not have 3 elements". Both the
    pheno and covariate reads are tab-separated now.

The R error extraction also joins R's wrapped continuation line, so a
complaint reads as a sentence rather than "Error in scan(...) :".
Diffstat (limited to 'tests')
-rw-r--r--tests/qtl2.rs94
1 files changed, 94 insertions, 0 deletions
diff --git a/tests/qtl2.rs b/tests/qtl2.rs
index 5b3f5fe..eb77e67 100644
--- a/tests/qtl2.rs
+++ b/tests/qtl2.rs
@@ -180,3 +180,97 @@ async fn qtl2_refuses_inputs_it_cannot_scan() {
         assert_eq!(error["code"], code, "{error}");
     }
 }
+
+/// A cross that ships its own control file is the only route to a
+/// multiparent scan, so its refusals matter: the name must exist, the
+/// samples must belong to the cross, and the two genotype sources cannot
+/// both be named.
+#[tokio::test]
+async fn a_shipped_multiparent_cross_is_named_not_guessed() {
+    let Some(token) = ready().await else { return };
+    for (body, code) in [
+        (
+            serde_json::json!({"rqtl2_cross": "nonesuch",
+                              "samples": [{"name": "S1", "value": 1.0}]}),
+            "unsupported_cross",
+        ),
+        (serde_json::json!({"rqtl2_cross": "do"}), "missing_samples"),
+        (
+            serde_json::json!({"rqtl2_cross": "do",
+                              "samples": [{"name": "not-an-individual", "value": 1.0}]}),
+            "no_samples_in_cross",
+        ),
+        (
+            serde_json::json!({"rqtl2_cross": "do", "group": "BXD",
+                              "samples": [{"name": "BXD1", "value": 1.0}]}),
+            "ambiguous_genotype",
+        ),
+    ] {
+        let response =
+            common::post_json_with_token("POST /compute/qtl2 (cross)", "/compute/qtl2", &token, &body)
+                .await;
+        let status = response.status();
+        let bytes = response.into_body().collect().await.unwrap().to_bytes();
+        let error: Value = serde_json::from_slice(&bytes).unwrap();
+        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{error}");
+        assert_eq!(error["code"], code, "{error}");
+    }
+}
+
+/// The real thing: the DO, 8 founder alleles, an LMM with LOCO kinship.
+/// Ignored because the genotype probabilities for 742 individuals over 6 413
+/// markers take minutes the first time (then they are cached); run it with
+/// `cargo test --test qtl2 -- --ignored`.
+#[tokio::test]
+#[ignore]
+async fn a_do_scan_fits_eight_founder_alleles() {
+    let Some(token) = ready().await else { return };
+    let pheno_path = std::path::Path::new(
+        "/home/wrk/tmp/ai-root/factory/gn4-data/genotype-files/do/do_pheno.csv",
+    );
+    let Ok(text) = std::fs::read_to_string(pheno_path) else {
+        eprintln!("skipping: {} is not readable", pheno_path.display());
+        return;
+    };
+    let mut samples = Vec::new();
+    for line in text.lines().filter(|line| !line.starts_with('#')) {
+        let fields: Vec<&str> = line.split(',').collect();
+        if fields.len() < 2 || fields[0] == "id" {
+            continue;
+        }
+        samples.push(serde_json::json!({
+            "name": fields[0],
+            "value": fields[1].parse::<f64>().ok(),
+        }));
+    }
+    assert!(samples.len() > 700, "the DO's 742 individuals: {}", samples.len());
+    let body = serde_json::json!({
+        "rqtl2_cross": "do",
+        "trait_name": "DO::WBC",
+        "samples": samples,
+        "cores": 8,
+    });
+    let response =
+        common::post_json_with_token("POST /compute/qtl2 (DO)", "/compute/qtl2", &token, &body).await;
+    let status = response.status();
+    let bytes = response.into_body().collect().await.unwrap().to_bytes();
+    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
+    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
+    let rows = envelope["data"].as_array().unwrap();
+    assert!(rows.len() > 5000, "the DO's autosomes: {}", rows.len());
+    let notes: Vec<&str> = envelope["notes"]
+        .as_array()
+        .unwrap()
+        .iter()
+        .map(|note| note.as_str().unwrap())
+        .collect();
+    let cross_note = notes.iter().find(|note| note.starts_with("Cross: ")).unwrap();
+    assert!(cross_note.contains("do"), "{cross_note}");
+    assert!(cross_note.contains("8 founder alleles"), "{cross_note}");
+    // WBC's known peak region: the scan says something, not a flat line.
+    let best = rows
+        .iter()
+        .map(|row| row[3].as_f64().unwrap())
+        .fold(0.0_f64, f64::max);
+    assert!(best > 3.0, "a real peak, not noise: {best}");
+}