about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-17 16:05:11 +0000
committerPjotr <wrk@bosa.lan>2026-11-17 16:05:11 +0000
commit14622e57629d19451cad03f4a69fdd89e81a433f (patch)
tree917814c2ca825f983bb9a06fca1ec1301e6f1024 /src
parentdf7fb3dd11be0a27de8904f7a4cb1309bdb64575 (diff)
downloadgenenetwork4-14622e57629d19451cad03f4a69fdd89e81a433f.tar.gz
qtl2: the .geno conversion is an R script now, and the Rust writer is gone
The conversion wrote qtl2's control file and CSVs by hand in Rust.  Its
output is an R/qtl2 cross, so the script does it and write_control_file
describes it: one implementation of the format, qtl2's.  What Rust keeps
is the endpoint's own limit -- a .geno panel carries no founder
genotypes, so a multiparent crosstype is a 422 with a reason, and the
cross type follows @type and the heterozygous policy.

prepare_cross now runs

  Rscript scripts/qtl2-convert-geno.R --geno GROUP.geno --out DIR
                                     --het drop|keep --crosstype riself|f2

writes the cross into the same versioned cache directory (now v6: the
files it writes are qtl2's own layout), and reads back the report the
script leaves beside it -- markers, non-autosomal, individuals,
het_dropped, cells -- instead of counting them itself.  A failed
conversion reports R's own complaint.  New configuration key
QTL2_CONVERT_SCRIPT (default scripts/qtl2-convert-geno.R).

The Rust writer's 250 lines are deleted, along with count_calls and
metadata_het.

Measured, BXD trait 10001 on the same request:

  before (Rust, alleles 1/3)   top rsm10000005730 chr8 LOD 3.685
  after  (R/qtl2, alleles 1/2) top rs32579649 chr8 LOD 3.8917,
                               rsm10000005700 3.8916
  GEMMA LMM, same trait        rsm10000005700 p 5.90e-07

so the wrong allele code was flattening this endpoint's own scan too: it
still found chromosome 8, at a neighbouring marker and 0.21 LOD lower,
with the marker GEMMA picks not in its top three.  The two engines now
agree on the locus.  Cost: 38.3 s cold for 20453 autosomal markers (the
R conversion is ~35 s of it), 3.5 s with the cross cached.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs9
-rw-r--r--src/qtl2.rs350
-rw-r--r--src/routes/gemma.rs10
-rw-r--r--src/routes/qtl2.rs10
4 files changed, 128 insertions, 251 deletions
diff --git a/src/config.rs b/src/config.rs
index 118b12b..ce2b038 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -139,6 +139,9 @@ pub struct Config {
     pub fitqtl_script_path: String,
     /// Path to scripts/qtl2_scan.R, which POST /compute/qtl2 runs.
     pub qtl2_script_path: String,
+    /// The `.geno` -> qtl2-cross conversion, an R script (`Qt l2` owns its
+    /// own file format; see `src/qtl2.rs`).
+    pub qtl2_convert_script: String,
     /// Directory POST /compute/qtl2 keeps converted crosses and scan
     /// output in. Defaults to a "gn4-qtl2" directory under the temp dir.
     pub qtl2_cache_dir: String,
@@ -344,6 +347,10 @@ impl Config {
             "scripts/qtl2_scan.R".to_string(),
         );
         values.insert(
+            "QTL2_CONVERT_SCRIPT".to_string(),
+            "scripts/qtl2-convert-geno.R".to_string(),
+        );
+        values.insert(
             "QTL2_CACHE_DIR".to_string(),
             std::env::temp_dir()
                 .join("gn4-qtl2")
@@ -493,6 +500,7 @@ impl Config {
             "RQTL_WRAPPER_PATH",
             "FITQTL_SCRIPT_PATH",
             "QTL2_SCRIPT_PATH",
+            "QTL2_CONVERT_SCRIPT",
             "QTL2_CACHE_DIR",
             "RQTL_CACHE_DIR",
             "WIKIDATA_CACHE_DIR",
@@ -576,6 +584,7 @@ impl Config {
             rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(),
             fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(),
             qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(),
+            qtl2_convert_script: values["QTL2_CONVERT_SCRIPT"].clone(),
             qtl2_cache_dir: values["QTL2_CACHE_DIR"].clone(),
             rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(),
             wikidata_cache_dir: values["WIKIDATA_CACHE_DIR"].clone(),
diff --git a/src/qtl2.rs b/src/qtl2.rs
index 44011de..0c0622f 100644
--- a/src/qtl2.rs
+++ b/src/qtl2.rs
@@ -155,47 +155,22 @@ pub struct Qtl2Output {
     pub permutation_note: Option<String>,
 }
 
-/// How many genotype cells carry one code -- the count a cached conversion
-/// needs to say what it dropped, without re-converting.
-fn count_calls(text: &str, code: &str) -> usize {
-    let mut seen_header = false;
-    let mut start = 3usize;
-    let mut count = 0usize;
-    for line in text.lines() {
-        let line = line.trim_end_matches('\r');
-        if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') {
-            continue;
-        }
-        let columns: Vec<&str> = line.split('\t').collect();
-        if !seen_header {
-            seen_header = true;
-            start = if columns.len() > 3 && columns[3] == "Mb" { 4 } else { 3 };
-            continue;
-        }
-        count += columns.iter().skip(start).filter(|cell| cell.trim() == code).count();
-    }
-    count
-}
-
-/// The header's `@het` code, if it declares one.
-fn metadata_het(text: &str) -> Option<String> {
-    text.lines()
-        .find_map(|line| line.strip_prefix("@het:"))
-        .map(|value| value.trim().to_string())
-}
-
-fn io_error(path: &Path, error: io::Error) -> Qtl2Error {
-    Qtl2Error::Io(io::Error::new(
-        error.kind(),
-        format!("{}: {error}", path.display()),
-    ))
-}
+/// The conversion, as an R script.
+pub const CONVERT_SCRIPT: &str = "scripts/qtl2-convert-geno.R";
 
 /// Convert `resolved`'s `.geno` into a cached qtl2 cross.
+///
+/// The conversion itself is [`CONVERT_SCRIPT`], an R script: the output is an
+/// R/qtl2 cross, and qtl2's own `write_control_file` describes it. Doing that
+/// here meant a second implementation of the format in Rust, and one of its
+/// conventions -- the genotype codes -- was wrong in a way that silently
+/// destroyed the scan (see the script's own comment). Reading the report the
+/// script leaves beside the cross is all this side needs to do.
 pub fn prepare_cross(
     resolved: &Resolved,
     cache_dir: &Path,
     het: Het,
+    convert_script: &Path,
 ) -> Result<PreparedCross, Qtl2Error> {
     let geno = &resolved.geno;
     let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?;
@@ -209,45 +184,20 @@ pub fn prepare_cross(
             .map(|since| since.as_secs())
             .unwrap_or(0)
     );
-    // The version tag is part of the key: a change to this conversion (the
-    // heterozygous calls dropped for a riself panel, say) must not silently
-    // reuse the previous cross's probabilities and kinship.
-    // v3 keyed the heterozygous policy in as well: a cross converted with the
-    // calls kept is a different cross from one with them dropped.
-    // v4: the allele *codes*.  With H=2, B=3 in a cross where the
-    // heterozygous class is dropped, the surviving pair is 1/3 -- and qtl2's
-    // two-state riself HMM cannot use an allele code outside 1..2.  It treats
-    // that allele as unusable: measured, P(BB) never rose above 0.5, every
-    // individual was called AA at a marker where 125 of 235 are BB, and a scan
-    // built on those calls had nothing left of the signal (p 2.0e-01 where the
-    // same marker is 5.9e-07 from the BIMBAM).  Recoding to 1/2 fixed it
-    // completely: agreement with the calls 209 of 209.
-    const CONVERSION_VERSION: &str = "v5";
-    let directory = cache_dir.join("crosses").join(format!(
-        "{CONVERSION_VERSION}-{}-{}-{stamp}",
-        het.as_str(),
-        resolved.version.replace(['/', '.'], "_")
-    ));
-    let control = directory.join("control.json");
     let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?;
 
-    // Metadata: the genotype codes, and the cross type.
-    let mut codes: BTreeMap<String, String> = BTreeMap::new();
-    let mut cross_type = String::new();
+    // The cross type is checked here rather than in R: this is the endpoint's
+    // own limit (a `.geno` panel carries no founder genotypes, so it cannot be
+    // a multiparent cross), and the answer is a 422 with a reason, not a
+    // script failure.
+    let mut declared = String::new();
     for line in text.lines() {
-        if let Some(rest) = line.strip_prefix('@') {
-            let Some((key, value)) = rest.split_once(':') else { continue };
-            let value = value.trim().to_string();
-            match key.trim() {
-                "mat" => { codes.insert(value, "A".to_string()); }
-                "het" => { codes.insert(value, "H".to_string()); }
-                "pat" => { codes.insert(value, "B".to_string()); }
-                "type" => cross_type = value,
-                _ => {}
-            }
+        if let Some(rest) = line.strip_prefix("@type:") {
+            declared = rest.trim().to_string();
+            break;
         }
     }
-    let crosstype = match cross_type.as_str() {
+    let crosstype = match declared.as_str() {
         // A riset panel read as `f2` is a riset panel whose H calls are kept:
         // qtl2 needs a cross type that has a heterozygous state for that.
         "riset" if het == Het::Keep => "f2",
@@ -261,205 +211,106 @@ pub fn prepare_cross(
             )))
         }
     };
-    // A riself panel is inbred lines: a heterozygous call is an error in the
-    // genotyping, not a third allele. R/qtl's `convert2riself` omits those
-    // genotypes, and qtl2 needs the same treatment -- left in, it reads the
-    // cross as multiparent and its scan1 takes a path this panel cannot
-    // satisfy ("scan1_pg ...").
-    let mut het_kept: Option<String> = None;
-    if crosstype == "riself" {
-        let het_code = metadata_het(&text);
-        if let Some(het_code) = het_code {
-            codes.remove(&het_code);
-            het_kept = Some(het_code);
-        }
-    }
-    if codes.len() < 2 {
-        return Err(Qtl2Error::Unsupported(
-            "the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded"
-                .to_string(),
-        ));
-    }
 
-    // Header row: Chr, Locus, cM, Mb?, then the individuals.
-    let mut lines = text.lines();
-    let Some(header) = lines.find(|line| line.to_lowercase().starts_with("chr\t")) else {
-        return Err(Qtl2Error::Unsupported(
-            "the .geno file has no 'Chr' header row".to_string(),
-        ));
-    };
-    let fields: Vec<&str> = header.split('\t').collect();
-    let first_individual = if fields.get(3).copied() == Some("Mb") { 4 } else { 3 };
-    let individuals: Vec<String> = fields[first_individual..]
-        .iter()
-        .map(|name| name.trim().to_string())
-        .collect();
-    if individuals.is_empty() {
-        return Err(Qtl2Error::Unsupported(
-            "the .geno header names no individuals".to_string(),
-        ));
-    }
+    // The version tag is part of the key: a change to the conversion must not
+    // silently reuse the previous cross's probabilities and kinship. v3 keyed
+    // the heterozygous policy in; v4/v5 were the allele codes; v6 is the
+    // conversion itself moving to R, which changes the files it writes (qtl2's
+    // own genotype layout, individuals in rows).
+    const CONVERSION_VERSION: &str = "v6";
+    let directory = cache_dir.join("crosses").join(format!(
+        "{CONVERSION_VERSION}-{}-{}-{stamp}",
+        het.as_str(),
+        resolved.version.replace(['/', '.'], "_")
+    ));
+    let control = directory.join("control.json");
 
     if !control.is_file() {
         std::fs::create_dir_all(&directory).map_err(|e| io_error(&directory, e))?;
-        let mut geno_csv = String::new();
-        let mut gmap_csv = String::from("marker,chr,pos\n");
-        let mut pmap_csv = String::from("marker,chr,pos\n");
-        geno_csv.push_str("marker,");
-        geno_csv.push_str(&individuals.join(","));
-        geno_csv.push('\n');
-        let mut markers = 0usize;
-        let mut non_autosomal = 0usize;
-        let mut het_dropped = 0usize;
-        for line in lines {
-            let line = line.trim_end_matches('\r');
-            if line.trim().is_empty() || line.starts_with('#') {
-                continue;
-            }
-            let row: Vec<&str> = line.split('\t').collect();
-            if row.len() < first_individual {
-                continue;
-            }
-            let (chromosome, marker, centimorgans, megabases) =
-                (row[0].trim(), row[1].trim(), row[2].trim(), row.get(3).copied().unwrap_or(""));
-            // Autosomes only: see the module comment.
-            if !chromosome.chars().all(|c| c.is_ascii_digit()) {
-                non_autosomal += 1;
-                continue;
-            }
-            markers += 1;
-            geno_csv.push_str(marker);
-            for value in &row[first_individual..] {
-                let call = codes.get(value.trim()).map(String::as_str).unwrap_or("");
-                if call.is_empty() && het_kept.as_deref() == Some(value.trim()) {
-                    het_dropped += 1;
+        let het_arg = het.as_str();
+        let output = std::process::Command::new("Rscript")
+            .arg(convert_script)
+            .arg("--geno")
+            .arg(geno)
+            .arg("--out")
+            .arg(&directory)
+            .arg("--het")
+            .arg(het_arg)
+            .arg("--crosstype")
+            .arg(crosstype)
+            .output()
+            .map_err(Qtl2Error::Io)?;
+        if !output.status.success() {
+            let stderr = String::from_utf8_lossy(&output.stderr);
+            let interesting = |line: &&str| {
+                let line = line.trim();
+                !line.is_empty()
+                    && !line.starts_with("Warning")
+                    && !line.starts_with("In ")
+                    && line != "Execution halted"
+            };
+            let complaint: Vec<&str> = stderr.lines().filter(interesting).collect();
+            return Err(Qtl2Error::CommandFailed(format!(
+                "converting {} failed: {}",
+                geno.display(),
+                if complaint.is_empty() {
+                    "R/qtl2 gave no reason".to_string()
+                } else {
+                    complaint.join(" ")
                 }
-                geno_csv.push(',');
-                geno_csv.push_str(call);
-            }
-            geno_csv.push('\n');
-            gmap_csv.push_str(&format!("{marker},{chromosome},{centimorgans}\n"));
-            let base_pairs = megabases.parse::<f64>().map(|mb| (mb * 1e6).round() as i64).unwrap_or(0);
-            pmap_csv.push_str(&format!("{marker},{chromosome},{base_pairs}\n"));
-        }
-        if markers == 0 {
-            return Err(Qtl2Error::Unsupported(
-                "the panel has no autosomal markers to scan".to_string(),
-            ));
-        }
-        // The cross needs a phenotype file of its own to be readable; the
-        // trait comes from the request, through the script's --pheno.
-        let mut pheno_csv = String::from("id,trait\n");
-        for name in &individuals {
-            pheno_csv.push_str(&format!("{name},1\n"));
-        }
-        for (path, contents) in [
-            (directory.join("geno.csv"), &geno_csv),
-            (directory.join("gmap.csv"), &gmap_csv),
-            (directory.join("pmap.csv"), &pmap_csv),
-            (directory.join("pheno.csv"), &pheno_csv),
-        ] {
-            std::fs::write(&path, contents).map_err(|e| io_error(&path, e))?;
+            )));
         }
-        let control_json = serde_json::json!({
-            // Paths are relative to the control file: qtl2 joins its own
-            // directory onto whatever it finds here.
-            "crosstype": crosstype,
-            "geno": "geno.csv",
-            "gmap": "gmap.csv",
-            "pmap": "pmap.csv",
-            "pheno": "pheno.csv",
-            "sep": ",",
-            "na.strings": [""],
-                    // The codes must be 1..n over the genotypes the CSV actually
-            // carries.  A riself cross with the heterozygous class dropped
-            // (the default) carries only A and B, so they are 1 and 2: leaving
-            // B as 3 hands qtl2 an allele code outside 1..2, which its
-            // two-state HMM cannot use -- it then reads that allele as
-            // unusable, P(BB) never rises above 0.5, every individual is
-            // called AA, and a scan built on those calls loses the signal
-            // (measured: 2.0e-01 where the same marker is 5.9e-07 from the
-            // BIMBAM; recoded, agreement with the calls is 209 of 209).
-            "genotypes": if crosstype != "riself" || het == Het::Keep {
-                serde_json::json!({"A": 1, "H": 2, "B": 3})
-            } else {
-                serde_json::json!({"A": 1, "B": 2})
-            },
-            // Our own CSVs are markers-in-rows, individuals-in-columns.
-            "geno_transposed": true,
-        });
-        std::fs::write(&control, control_json.to_string()).map_err(|e| io_error(&control, e))?;
-        // What the conversion discarded, kept beside the cross: a cached cross
-        // must be able to say how many calls it dropped.
-        let report = serde_json::json!({
-            "het_dropped": het_dropped,
-            "cells": individuals.len() * markers,
-        });
-        let report_path = directory.join("conversion.json");
-        let _ = std::fs::write(&report_path, report.to_string());
-        return Ok(PreparedCross {
-            control,
-            individuals: individuals.clone(),
-            markers,
-            non_autosomal,
-            crosstype: crosstype.to_string(),
-            het_dropped,
-            cells: individuals.len() * markers,
-            founders: 0,
-            multiparent: false,
-        });
     }
 
-    // Cached: count what the conversion produced, without re-reading the
-    // panel. The marker counts come from the maps it wrote.
-    let markers = std::fs::read_to_string(directory.join("pmap.csv"))
-        .map_err(|e| io_error(&directory.join("pmap.csv"), e))?
-        .lines()
-        .filter(|line| !line.trim().is_empty())
-        .count()
-        .saturating_sub(1);
+    // The script's report is the cross's own account of itself: what it
+    // dropped, and which individuals it holds. A cross converted before the
+    // report existed is measured once from the panel.
     let report_path = directory.join("conversion.json");
-    let mut report: Value = std::fs::read_to_string(&report_path)
+    let report: Value = std::fs::read_to_string(&report_path)
         .ok()
         .and_then(|text| serde_json::from_str(&text).ok())
-        .unwrap_or_else(|| serde_json::json!({}));
-    if report.get("het_dropped").is_none() {
-        // A cross converted before the count was kept: measure it once from the
-        // panel and record it beside the cross, so later replies are free.
-        let het_code = if crosstype == "riself" {
-            metadata_het(&text)
-        } else {
-            None
-        };
-        let dropped = het_code
-            .as_deref()
-            .map(|code| count_calls(&text, code))
-            .unwrap_or(0);
-        report = serde_json::json!({
-            "het_dropped": dropped,
-            "cells": individuals.len() * markers,
-        });
-        let _ = std::fs::write(&report_path, report.to_string());
+        .ok_or_else(|| {
+            Qtl2Error::CommandFailed(format!(
+                "{} wrote no conversion report; can this convert {}?",
+                convert_script.display(),
+                geno.display()
+            ))
+        })?;
+    let want = |key: &str| report.get(key).and_then(Value::as_u64).unwrap_or(0) as usize;
+    let individuals: Vec<String> = report
+        .get("individuals")
+        .and_then(Value::as_array)
+        .map(|names| {
+            names
+                .iter()
+                .filter_map(|name| name.as_str().map(str::to_string))
+                .collect()
+        })
+        .unwrap_or_default();
+    if individuals.is_empty() {
+        return Err(Qtl2Error::Unsupported(
+            "the .geno header names no individuals".to_string(),
+        ));
+    }
+    let markers = want("markers");
+    if markers == 0 {
+        return Err(Qtl2Error::Unsupported(
+            "the panel has no autosomal markers to scan".to_string(),
+        ));
     }
-    let het_dropped = report
-        .get("het_dropped")
-        .and_then(Value::as_u64)
-        .unwrap_or(0) as usize;
-    let cells = report.get("cells").and_then(Value::as_u64).unwrap_or(0) as usize;
     Ok(PreparedCross {
         control,
         individuals,
         markers,
-        non_autosomal: 0,
+        non_autosomal: want("non_autosomal"),
         crosstype: crosstype.to_string(),
-        het_dropped,
-        cells,
+        het_dropped: want("het_dropped"),
+        cells: want("cells"),
         founders: 0,
         multiparent: false,
     })
 }
 
-/// Find the control file of a cross named in a request.
 pub fn resolve_control_file(root: &Path, requested: &str) -> Result<PathBuf, Qtl2Error> {
     let name = requested.trim();
     if name.is_empty() {
@@ -509,6 +360,13 @@ fn control_path(control: &Path, json: &Value, key: &str) -> Option<PathBuf> {
         .map(|name| directory.join(name))
 }
 
+fn io_error(path: &Path, error: io::Error) -> Qtl2Error {
+    Qtl2Error::Io(io::Error::new(
+        error.kind(),
+        format!("{}: {error}", path.display()),
+    ))
+}
+
 /// The data lines of a CSV: comments and blank lines skipped, header dropped.
 fn data_lines(path: &Path, comment: &str) -> Result<Vec<String>, Qtl2Error> {
     let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?;
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 31d5538..baf4d6d 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -997,6 +997,7 @@ async fn prepare_genotypes(
         let directory = config.genotype_files_dir.clone();
         let cache = config.qtl2_cache_dir.clone();
         let version = version.map(|v| v.to_string());
+        let convert = config.qtl2_convert_script.clone();
         let prepared = tokio::task::spawn_blocking(move || {
             let resolved = genotypes::resolve(
                 std::path::Path::new(&directory),
@@ -1007,8 +1008,13 @@ async fn prepare_genotypes(
             // Drop is the default genotype model: the heterozygous calls a
             // riset panel carries are exactly the ones the HMM is asked to
             // re-predict, so predicting from the kept calls would be circular.
-            qtl2::prepare_cross(&resolved, std::path::Path::new(&cache), qtl2::Het::Drop)
-                .map_err(|error| error.to_string())
+            qtl2::prepare_cross(
+                &resolved,
+                std::path::Path::new(&cache),
+                qtl2::Het::Drop,
+                std::path::Path::new(&convert),
+            )
+            .map_err(|error| error.to_string())
         })
         .await
         .map_err(|error| {
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
index 896c0e9..bf2ba06 100644
--- a/src/routes/qtl2.rs
+++ b/src/routes/qtl2.rs
@@ -675,10 +675,14 @@ pub async fn compute_qtl2(
     let genotype_root = config.genotype_files_dir.clone();
     let cache_dir_for_cross = cache_dir.clone();
     let het_for_cross = het;
+    let convert_for_cross = config.qtl2_convert_script.clone();
     let cross = tokio::task::spawn_blocking(move || match source_for_cross {
-        Source::Convert(resolved) => {
-            qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir_for_cross), het_for_cross)
-        }
+        Source::Convert(resolved) => qtl2::prepare_cross(
+            &resolved,
+            std::path::Path::new(&cache_dir_for_cross),
+            het_for_cross,
+            std::path::Path::new(&convert_for_cross),
+        ),
         Source::Control(name) => {
             qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name)
         }