about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/qtl2.rs54
-rw-r--r--src/routes/qtl2.rs38
2 files changed, 86 insertions, 6 deletions
diff --git a/src/qtl2.rs b/src/qtl2.rs
index 0cab607..c234150 100644
--- a/src/qtl2.rs
+++ b/src/qtl2.rs
@@ -84,6 +84,43 @@ pub struct PreparedCross {
     pub multiparent: bool,
 }
 
+/// What the conversion does with a heterozygous call on a `riself` panel.
+///
+/// R/qtl's `convert2riself` drops them, and so does the default here: an
+/// inbred line has no heterozygotes, so an `H` is a genotyping error or a
+/// residual one. But "drop" also means qtl2 never *sees* that call -- the HMM
+/// re-imputes it from flanking markers -- and on a panel where a marker is
+/// 14 % H (BXD.8's `rs33299937`) that is a different predictor from the one
+/// R/qtl fits. [`Het::Keep`] keeps the call as a third genotype, which makes
+/// the cross an `f2` for qtl2: a diagnostic, not a recommendation, because the
+/// het state is then modeled as a real genotype.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Het {
+    /// Heterozygous calls become missing (the default; R/qtl's behaviour).
+    Drop,
+    /// Heterozygous calls become a third genotype (an `f2` cross).
+    Keep,
+}
+
+impl Het {
+    pub fn parse(value: Option<&str>) -> Result<Het, String> {
+        match value.unwrap_or("drop").trim().to_ascii_lowercase().as_str() {
+            "drop" | "missing" => Ok(Het::Drop),
+            "keep" | "f2" => Ok(Het::Keep),
+            other => Err(format!(
+                "het '{other}' not recognized; use 'drop' (default) or 'keep'"
+            )),
+        }
+    }
+
+    pub fn as_str(self) -> &'static str {
+        match self {
+            Het::Drop => "drop",
+            Het::Keep => "keep",
+        }
+    }
+}
+
 /// Cross types qtl2 fits one coefficient per founder allele for. Such a
 /// cross needs founder genotypes; without them qtl2 cannot resolve alleles
 /// and the scan is biallelic whatever the file is called.
@@ -124,6 +161,7 @@ fn io_error(path: &Path, error: io::Error) -> Qtl2Error {
 pub fn prepare_cross(
     resolved: &Resolved,
     cache_dir: &Path,
+    het: Het,
 ) -> Result<PreparedCross, Qtl2Error> {
     let geno = &resolved.geno;
     let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?;
@@ -140,9 +178,12 @@ pub fn prepare_cross(
     // 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.
-    const CONVERSION_VERSION: &str = "v2";
+    // v3 keyed the heterozygous policy in as well: a cross converted with the
+    // calls kept is a different cross from one with them dropped.
+    const CONVERSION_VERSION: &str = "v3";
     let directory = cache_dir.join("crosses").join(format!(
-        "{CONVERSION_VERSION}-{}-{stamp}",
+        "{CONVERSION_VERSION}-{}-{}-{stamp}",
+        het.as_str(),
         resolved.version.replace(['/', '.'], "_")
     ));
     let control = directory.join("control.json");
@@ -165,6 +206,9 @@ pub fn prepare_cross(
         }
     }
     let crosstype = match cross_type.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",
         "riset" => "riself",
         "f2" => "f2",
         other => {
@@ -181,9 +225,9 @@ pub fn prepare_cross(
     // cross as multiparent and its scan1 takes a path this panel cannot
     // satisfy ("scan1_pg ...").
     if crosstype == "riself" {
-        let het = metadata_het(&text);
-        if let Some(het) = het {
-            codes.remove(&het);
+        let het_code = metadata_het(&text);
+        if let Some(het_code) = het_code {
+            codes.remove(&het_code);
         }
     }
     if codes.len() < 2 {
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
index 5ebde1d..b2b882c 100644
--- a/src/routes/qtl2.rs
+++ b/src/routes/qtl2.rs
@@ -82,6 +82,11 @@ pub struct Qtl2Request {
     pub kinship: Option<String>,
     /// `normal` (default) or `binary`.
     pub model: Option<String>,
+    /// What to do with heterozygous calls on a `riset` panel: `drop` (default;
+    /// R/qtl's `convert2riself`, the HMM re-imputes them) or `keep` (a third
+    /// genotype, i.e. an `f2` cross -- a diagnostic, since an inbred line has
+    /// no heterozygotes). Ignored for a cross that ships its own control file.
+    pub het: Option<String>,
     /// Cores for the per-chromosome steps (default 4, capped at 16).
     pub cores: Option<u32>,
     /// Covariates, as on `/compute/rqtl`: a case attribute of the group by
@@ -190,6 +195,28 @@ pub async fn compute_qtl2(
         )
         .with_request_id(rid));
     }
+    let het = qtl2::Het::parse(request.het.as_deref()).map_err(|detail| {
+        ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_het",
+            "Invalid heterozygous-call policy",
+            detail,
+            "compute_qtl2",
+        )
+        .with_request_id(rid.clone())
+    })?;
+    if het == qtl2::Het::Keep && request.rqtl2_cross.is_some() {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_het",
+            "Invalid heterozygous-call policy",
+            "`het` applies to a panel this server converts; a shipped cross carries its own \
+             genotype coding."
+                .to_string(),
+            "compute_qtl2",
+        )
+        .with_request_id(rid));
+    }
     let cores = request.cores.unwrap_or(4).clamp(1, 16);
 
     let request_group = request.group.clone();
@@ -470,9 +497,10 @@ pub async fn compute_qtl2(
     let source_for_cross = source.clone();
     let genotype_root = config.genotype_files_dir.clone();
     let cache_dir_for_cross = cache_dir.clone();
+    let het_for_cross = het;
     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))
+            qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir_for_cross), het_for_cross)
         }
         Source::Control(name) => {
             qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name)
@@ -609,6 +637,14 @@ pub async fn compute_qtl2(
     if let Some(note) = basket_note {
         notes.push(note);
     }
+    if het == qtl2::Het::Keep {
+        notes.push(
+            "Heterozygous calls were kept as a third genotype, so the cross is fitted as `f2` \
+             rather than `riself`. That is a diagnostic: an inbred line has no heterozygotes, \
+             and a het state modeled as real is only meaningful where the calls are."
+                .to_string(),
+        );
+    }
     // A multiparent cross is fitted per founder allele: the DO's scan is
     // eight times the work of the same panel scanned biallelically, so the
     // gate is handed that weight rather than the individual count.