about summary refs log tree commit diff
path: root/src
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 /src
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 'src')
-rw-r--r--src/qtl2.rs326
-rw-r--r--src/routes/qtl2.rs169
2 files changed, 460 insertions, 35 deletions
diff --git a/src/qtl2.rs b/src/qtl2.rs
index 7b79c3d..0cab607 100644
--- a/src/qtl2.rs
+++ b/src/qtl2.rs
@@ -61,6 +61,7 @@ impl std::fmt::Display for Qtl2Error {
 }
 
 /// A converted cross, ready for `read_cross2`.
+#[derive(Debug, Clone)]
 pub struct PreparedCross {
     /// The control file, in the cross's own directory (qtl2 joins the
     /// control file's directory onto every path it finds, so absolute paths
@@ -72,10 +73,31 @@ pub struct PreparedCross {
     pub markers: usize,
     /// Markers left out as non-autosomal.
     pub non_autosomal: usize,
-    /// `riself` or `f2`.
-    pub crosstype: &'static str,
+    /// qtl2's name for the cross: `riself`, `f2`, `do`, `4way`, …
+    pub crosstype: String,
+    /// Founder alleles the cross fits (8 for the DO). Zero when the cross
+    /// carries no founder genotypes, which is every `.geno` panel here.
+    pub founders: usize,
+    /// True when qtl2 fits one coefficient per founder allele, so a LOD
+    /// asks whether *any* founder differs rather than which allele at a
+    /// biallelic marker does.
+    pub multiparent: bool,
 }
 
+/// 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.
+const MULTIPARENT_CROSSTYPES: [&str; 8] = ["do", "cc", "hs", "magic", "mp", "ail", "4way", "ri4way"];
+
+/// Where a named cross's control file may live, under the genotype files
+/// root: the rqtl2 directory GeneNetwork shares, then the panel's own
+/// directory (`do/do.json`), then the root itself.
+const CONTROL_LOCATIONS: [&str; 3] = [
+    "genotype/rqtl2/{name}.json",
+    "{name}/{name}.json",
+    "{name}.json",
+];
+
 /// One finished scan.
 pub struct Qtl2Output {
     pub rows: Value,
@@ -267,7 +289,9 @@ pub fn prepare_cross(
             individuals,
             markers,
             non_autosomal,
-            crosstype,
+            crosstype: crosstype.to_string(),
+            founders: 0,
+            multiparent: false,
         });
     }
 
@@ -284,7 +308,182 @@ pub fn prepare_cross(
         individuals,
         markers,
         non_autosomal: 0,
+        crosstype: crosstype.to_string(),
+        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() {
+        return Err(Qtl2Error::Unsupported(
+            "name a cross, e.g. \"do\" -- see /groups/{group}/genotypes".to_string(),
+        ));
+    }
+    // A path the caller spelled out is taken as given: `genotype_file`
+    // already accepts absolute paths, so this grants nothing new.
+    if name.contains('/') || name.ends_with(".json") {
+        let stated = Path::new(name);
+        let path = if stated.is_absolute() {
+            stated.to_path_buf()
+        } else {
+            root.join(stated)
+        };
+        if path.is_file() {
+            return Ok(path);
+        }
+    }
+    let stem = name.trim_end_matches(".json");
+    for template in CONTROL_LOCATIONS {
+        let path = root.join(template.replace("{name}", stem));
+        if path.is_file() {
+            return Ok(path);
+        }
+    }
+    Err(Qtl2Error::Unsupported(format!(
+        "no R/qtl2 control file for '{name}' under {}; looked for {}. Only a cross that ships \
+         founder genotypes can be analysed as multiparent -- do/ is the one this deployment has. \
+         A .geno panel can be scanned, but only as biallelic: give `group` instead.",
+        root.display(),
+        CONTROL_LOCATIONS
+            .iter()
+            .map(|template| template.replace("{name}", stem))
+            .collect::<Vec<_>>()
+            .join(", ")
+    )))
+}
+
+/// A path a control file names, joined onto the control file's own directory
+/// (qtl2 reads every path relative to the file that names it).
+fn control_path(control: &Path, json: &Value, key: &str) -> Option<PathBuf> {
+    let directory = control.parent()?;
+    json.get(key)
+        .and_then(Value::as_str)
+        .map(|name| directory.join(name))
+}
+
+/// 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))?;
+    Ok(text
+        .lines()
+        .map(|line| line.trim_end_matches('\r').to_string())
+        .filter(|line| !line.trim().is_empty() && !line.starts_with(comment))
+        .skip(1)
+        .collect())
+}
+
+/// How many founders a `founder_geno` file has: their names are its header
+/// when it is transposed (the DO's is), its rows when it is not.
+fn count_founders(
+    path: &Path,
+    json: &Value,
+    sep: &str,
+    comment: &str,
+) -> Result<usize, Qtl2Error> {
+    let transposed = json
+        .get("founder_geno_transposed")
+        .and_then(Value::as_bool)
+        .unwrap_or(false);
+    let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?;
+    let mut lines = text.lines().map(str::trim_end).filter(|line| {
+        !line.trim().is_empty() && !line.starts_with(comment)
+    });
+    let Some(first) = lines.next() else { return Ok(0) };
+    Ok(if transposed {
+        first.split(sep).count().saturating_sub(1)
+    } else {
+        lines.count()
+    })
+}
+
+/// Read a cross that ships as a qtl2 control file, founder genotypes and
+/// all. Nothing is converted, which is exactly what makes a multiparent scan
+/// possible: a `.geno` panel carries two codes per marker, not a founder
+/// allele.
+pub fn prepare_control_cross(root: &Path, requested: &str) -> Result<PreparedCross, Qtl2Error> {
+    let control = resolve_control_file(root, requested)?;
+    let text = std::fs::read_to_string(&control).map_err(|e| io_error(&control, e))?;
+    let json: Value = serde_json::from_str(&text).map_err(|error| {
+        Qtl2Error::Unsupported(format!(
+            "{} is not a JSON control file: {error}",
+            control.display()
+        ))
+    })?;
+    let comment = json
+        .get("comment.char")
+        .and_then(Value::as_str)
+        .unwrap_or("#")
+        .to_string();
+    let sep = json
+        .get("sep")
+        .and_then(Value::as_str)
+        .unwrap_or(",")
+        .to_string();
+    let crosstype = json
+        .get("crosstype")
+        .and_then(Value::as_str)
+        .unwrap_or("unknown")
+        .to_string();
+
+    let pheno = control_path(&control, &json, "pheno").ok_or_else(|| {
+        Qtl2Error::Unsupported(format!(
+            "{}: the cross declares no `pheno` file, so it names no individuals",
+            control.display()
+        ))
+    })?;
+    let individuals: Vec<String> = data_lines(&pheno, &comment)?
+        .iter()
+        .filter_map(|line| line.split(&sep).next())
+        .map(|name| name.trim().to_string())
+        .filter(|name| !name.is_empty())
+        .collect();
+    if individuals.is_empty() {
+        return Err(Qtl2Error::Unsupported(format!(
+            "{}: the phenotype file names no individuals",
+            pheno.display()
+        )));
+    }
+
+    // Markers and chromosomes, from whichever map the cross declares.
+    let map = control_path(&control, &json, "pmap").or_else(|| control_path(&control, &json, "gmap"));
+    let mut markers = 0usize;
+    let mut non_autosomal = 0usize;
+    if let Some(map) = map {
+        for line in data_lines(&map, &comment)? {
+            let fields: Vec<&str> = line.split(&sep).collect();
+            let Some(chromosome) = fields.get(1) else { continue };
+            if chromosome.trim().chars().all(|c| c.is_ascii_digit()) {
+                markers += 1;
+            } else {
+                non_autosomal += 1;
+            }
+        }
+    }
+
+    let founders = match control_path(&control, &json, "founder_geno") {
+        Some(path) => count_founders(&path, &json, &sep, &comment)?,
+        None => 0,
+    };
+    let multiparent = MULTIPARENT_CROSSTYPES.contains(&crosstype.as_str());
+    if multiparent && founders < 3 {
+        return Err(Qtl2Error::Unsupported(format!(
+            "{}: crosstype '{crosstype}' is multiparent, but the cross declares no founder \
+             genotypes, so qtl2 cannot say which allele a genotype is. Point `founder_geno` at a \
+             founder genotype file, as do/do.json does.",
+            control.display()
+        )));
+    }
+    Ok(PreparedCross {
+        control,
+        individuals,
+        markers,
+        non_autosomal,
         crosstype,
+        founders,
+        multiparent,
     })
 }
 
@@ -374,12 +573,22 @@ pub async fn compute(
             .chain(stdout.lines())
             .filter(interesting)
             .collect();
+        // R wraps a long call across lines, so the sentence that matters is
+        // often the line *after* "Error in foo(...) :". Take the Error line
+        // and its continuation rather than half a complaint.
         let complaint = lines
             .iter()
-            .rev()
-            .find(|line| line.trim_start().starts_with("Error") || line.contains("Error in"))
-            .or_else(|| lines.last())
-            .map(|line| line.trim().to_string())
+            .position(|line| line.trim_start().starts_with("Error") || line.contains("Error in"))
+            .map(|start| {
+                lines[start..]
+                    .iter()
+                    .take(3)
+                    .map(|line| line.trim())
+                    .filter(|line| !line.starts_with("Calls:"))
+                    .collect::<Vec<_>>()
+                    .join(" ")
+            })
+            .or_else(|| lines.last().map(|line| line.trim().to_string()))
             .unwrap_or_else(|| "R/qtl2 failed without saying why".to_string());
         return Err(Qtl2Error::CommandFailed(complaint));
     }
@@ -435,6 +644,109 @@ mod tests {
         assert_eq!(row[3], serde_json::json!(4.85));
     }
 
+    /// A cross directory shaped like `do/`: a control file that names its
+    /// own files, founder genotypes and all.
+    fn founder_cross(root: &Path, crosstype: &str, with_founders: bool) -> PathBuf {
+        let directory = root.join("do");
+        std::fs::create_dir_all(&directory).unwrap();
+        let mut control = serde_json::json!({
+            "crosstype": crosstype,
+            "sep": ",",
+            "comment.char": "#",
+            "geno": "geno.csv",
+            "gmap": "gmap.csv",
+            "pmap": "pmap.csv",
+            "pheno": "pheno.csv",
+        });
+        if with_founders {
+            control["founder_geno"] = serde_json::json!("founder.csv");
+            control["founder_geno_transposed"] = serde_json::json!(true);
+            std::fs::write(
+                directory.join("founder.csv"),
+                "# founder genotype data\nmarker,A,B,C,D,E,F,G,H\nm1,0,1,3,0,1,3,0,1\n",
+            )
+            .unwrap();
+        }
+        std::fs::write(
+            directory.join("pheno.csv"),
+            "# phenotype data\nid,WBC\nS1,4.3\nS2,5.1\n",
+        )
+        .unwrap();
+        std::fs::write(
+            directory.join("pmap.csv"),
+            "# physical map\nmarker,chr,pos\nm1,1,3000000\nm2,1,9000000\nm3,X,4000000\n",
+        )
+        .unwrap();
+        let path = directory.join("do.json");
+        std::fs::write(&path, control.to_string()).unwrap();
+        path
+    }
+
+    fn scratch_dir(name: &str) -> PathBuf {
+        let directory = std::env::temp_dir().join(format!(
+            "gn4-qtl2-test-{name}-{}-{:?}",
+            std::process::id(),
+            std::thread::current().id()
+        ));
+        let _ = std::fs::remove_dir_all(&directory);
+        std::fs::create_dir_all(&directory).unwrap();
+        directory
+    }
+
+    #[test]
+    fn a_named_cross_is_found_where_qtl2_keeps_it() {
+        let root = scratch_dir("resolve");
+        founder_cross(&root, "do", true);
+        let found = resolve_control_file(&root, "do").unwrap();
+        assert!(found.ends_with("do/do.json"), "{}", found.display());
+        // The rqtl2 directory GeneNetwork shares comes first.
+        std::fs::create_dir_all(root.join("genotype/rqtl2")).unwrap();
+        std::fs::write(root.join("genotype/rqtl2/cc.json"), "{}").unwrap();
+        assert!(resolve_control_file(&root, "cc")
+            .unwrap()
+            .ends_with("genotype/rqtl2/cc.json"));
+        // A name nobody has: the refusal says where it looked.
+        let error = resolve_control_file(&root, "nonesuch").unwrap_err().to_string();
+        assert!(error.contains("no R/qtl2 control file"), "{error}");
+        assert!(error.contains("genotype/rqtl2/nonesuch.json"), "{error}");
+        std::fs::remove_dir_all(&root).ok();
+    }
+
+    #[test]
+    fn a_multiparent_cross_reports_its_founders() {
+        let root = scratch_dir("multiparent");
+        founder_cross(&root, "do", true);
+        let cross = prepare_control_cross(&root, "do").unwrap();
+        assert_eq!(cross.crosstype, "do");
+        assert!(cross.multiparent, "the DO is multiparent");
+        assert_eq!(cross.founders, 8, "eight founder alleles, from the founder header");
+        assert_eq!(cross.individuals, vec!["S1".to_string(), "S2".to_string()]);
+        assert_eq!(cross.markers, 2, "autosomal markers only");
+        assert_eq!(cross.non_autosomal, 1, "the X is counted, not scanned");
+        std::fs::remove_dir_all(&root).ok();
+    }
+
+    #[test]
+    fn a_multiparent_crosstype_without_founder_genotypes_is_refused() {
+        let root = scratch_dir("no-founders");
+        founder_cross(&root, "do", false);
+        let error = prepare_control_cross(&root, "do").unwrap_err().to_string();
+        assert!(error.contains("no founder genotypes"), "{error}");
+        std::fs::remove_dir_all(&root).ok();
+    }
+
+    #[test]
+    fn a_biallelic_cross_is_not_mistaken_for_multiparent() {
+        let root = scratch_dir("biallelic");
+        founder_cross(&root, "riself", false);
+        // The file lives in do/ either way; the *crosstype inside* is what
+        // decides whether founder alleles are fitted.
+        let cross = prepare_control_cross(&root, "do").unwrap();
+        assert!(!cross.multiparent);
+        assert_eq!(cross.founders, 0);
+        std::fs::remove_dir_all(&root).ok();
+    }
+
     #[test]
     fn a_broken_row_is_skipped_rather_than_reported_as_zero() {
         let rows = parse_rows("marker,chr,pos,lod\nrs1,1,not-a-number,2.0\nrs2,1,3.0,4.0\n");
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
index 6cc2346..649600d 100644
--- a/src/routes/qtl2.rs
+++ b/src/routes/qtl2.rs
@@ -54,6 +54,12 @@ pub struct Qtl2Request {
     pub genotype_version: Option<String>,
     /// Explicit `.geno` path on the server, instead of `group`.
     pub genotype_file: Option<String>,
+    /// A cross that ships its own R/qtl2 control file, by name (e.g. "do").
+    /// This is the only route to a multiparent scan: a `.geno` panel carries
+    /// two codes per marker, not the founder alleles a multiparent model
+    /// fits. The cross's individuals are the population, so `samples` are
+    /// matched to it by name and anything outside it is left out.
+    pub rqtl2_cross: Option<String>,
     /// Include parents and F1s; off by default, as elsewhere.
     pub include_parents_f1: Option<bool>,
     /// The trait's values by individual name, or `trait_values` positionally
@@ -155,7 +161,49 @@ pub async fn compute_qtl2(
     let request_group = request.group.clone();
     let include_parents_f1 = request.include_parents_f1.unwrap_or(false);
     let mut notes: Vec<String> = Vec::new();
-    let (resolved, samples) = match (request.genotype_file.clone(), request.group.clone()) {
+    /// Where the scan's genotypes come from.
+    #[derive(Clone)]
+    enum Source {
+        /// A panel the server converts into a cross and caches.
+        Convert(genotypes::Resolved),
+        /// A cross that ships a qtl2 control file of its own.
+        Control(String),
+    }
+    let (source, samples) = if let Some(name) = request.rqtl2_cross.clone() {
+        if request.group.is_some() || request.genotype_file.is_some() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give rqtl2_cross, or group, or genotype_file -- one of the three.".to_string(),
+                "compute_qtl2",
+            )
+            .with_request_id(rid));
+        }
+        let given: Vec<Sample> = request
+            .samples
+            .clone()
+            .unwrap_or_default()
+            .into_iter()
+            .map(|sample| Sample {
+                name: sample.name,
+                value: sample.value,
+            })
+            .collect();
+        if given.is_empty() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "missing_samples",
+                "No trait values",
+                "a shipped cross names its own individuals, so give `samples` (name and value,                  as /groups/{group}/traits/{id}/values returns them)."
+                    .to_string(),
+                "compute_qtl2",
+            )
+            .with_request_id(rid));
+        }
+        (Source::Control(name), given)
+    } else {
+        match (request.genotype_file.clone(), request.group.clone()) {
         (None, Some(group)) => {
             let wanted = group.clone();
             let version = request.genotype_version.clone();
@@ -237,7 +285,7 @@ pub async fn compute_qtl2(
                 .zip(aligned)
                 .map(|(name, value)| Sample { name, value })
                 .collect();
-            (resolved, samples)
+            (Source::Convert(resolved), samples)
         }
         (Some(file), None) => {
             let values = request.trait_values.clone().unwrap_or_default();
@@ -277,7 +325,7 @@ pub async fn compute_qtl2(
                     value,
                 })
                 .collect();
-            (resolved, samples)
+            (Source::Convert(resolved), samples)
         }
         (Some(_), Some(_)) => {
             return Err(ApiError::new(
@@ -294,11 +342,13 @@ pub async fn compute_qtl2(
                 StatusCode::UNPROCESSABLE_ENTITY,
                 "missing_genotype",
                 "No genotype input",
-                "give genotype_file, or group (see /groups/{group}/genotypes).".to_string(),
+                "give rqtl2_cross, genotype_file, or group (see /groups/{group}/genotypes)."
+                    .to_string(),
                 "compute_qtl2",
             )
             .with_request_id(rid));
         }
+        }
     };
 
     // Normalise after alignment, over the individuals that enter the scan.
@@ -336,10 +386,16 @@ pub async fn compute_qtl2(
 
     // The cross: converted from the .geno once, then cached.
     let cache_dir = config.qtl2_cache_dir.clone();
-    let cross = tokio::task::spawn_blocking({
-        let cache_dir = cache_dir.clone();
-        let resolved = resolved.clone();
-        move || qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir))
+    let source_for_cross = source.clone();
+    let genotype_root = config.genotype_files_dir.clone();
+    let cache_dir_for_cross = cache_dir.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))
+        }
+        Source::Control(name) => {
+            qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name)
+        }
     })
     .await
     .map_err(|e| {
@@ -370,22 +426,60 @@ pub async fn compute_qtl2(
         )
         .with_request_id(rid.clone()),
     })?;
-    // A path request's values were positional: give them the cross's own
-    // individual names, which is what the script aligns on.
-    let samples: Vec<Sample> = if request_group.is_none() {
-        samples
+    let samples: Vec<Sample> = match &source {
+        // A path request's values were positional: give them the cross's own
+        // individual names, which is what the script aligns on.
+        Source::Convert(_) if request_group.is_none() => samples
             .into_iter()
             .zip(cross.individuals.iter())
             .map(|(sample, name)| Sample {
                 name: name.clone(),
                 value: sample.value,
             })
-            .collect()
-    } else {
-        samples
+            .collect(),
+        Source::Convert(_) => samples,
+        // A shipped cross is its own population: keep the values for the
+        // individuals it holds, and say how many fell outside it.
+        Source::Control(_) => {
+            let in_cross: std::collections::HashSet<&str> =
+                cross.individuals.iter().map(String::as_str).collect();
+            let given = samples.len();
+            let kept: Vec<Sample> = samples
+                .into_iter()
+                .filter(|sample| in_cross.contains(sample.name.as_str()))
+                .collect();
+            if kept.is_empty() {
+                let example = cross
+                    .individuals
+                    .iter()
+                    .take(3)
+                    .cloned()
+                    .collect::<Vec<_>>()
+                    .join(", ");
+                return Err(ApiError::new(
+                    StatusCode::UNPROCESSABLE_ENTITY,
+                    "no_samples_in_cross",
+                    "No trait values for this cross",
+                    format!(
+                        "none of the {given} sample name(s) are individuals of this cross; they                          look like {example}"
+                    ),
+                    "compute_qtl2",
+                )
+                .with_request_id(rid));
+            }
+            if kept.len() < given {
+                notes.push(format!(
+                    "{} of {given} sample(s) are not in the cross and were left out; the scan \
+                     fits {} individuals",
+                    given - kept.len(),
+                    kept.len()
+                ));
+            }
+            kept
+        }
     };
-    notes.push(format!(
-        "Cross: {} ({} individuals, {} autosomal markers{})",
+    let mut cross_note = format!(
+        "Cross: {} ({} individuals, {} autosomal markers{}",
         cross.crosstype,
         cross.individuals.len(),
         cross.markers,
@@ -394,12 +488,29 @@ pub async fn compute_qtl2(
         } else {
             String::new()
         }
-    ));
+    );
+    if cross.multiparent {
+        // Worth saying plainly: a multiparent LOD is a different claim from a
+        // biallelic one, and reading it as a strain effect is the usual mistake.
+        cross_note.push_str(&format!(
+            "; {} founder alleles, so every marker is fitted with one coefficient per founder -- \
+             the LOD asks whether any founder differs, not which. Per-founder effect sizes need \
+             scan1coef, which this endpoint does not return yet",
+            cross.founders
+        ));
+    }
+    cross_note.push(')');
+    notes.push(cross_note);
 
-    let individuals = samples.len();
-    __gn4_claim
-        .claim_slot_or_busy(individuals, rid.clone())
-        .await?;
+    // 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.
+    let weight = if cross.multiparent {
+        samples.len() * cross.founders.max(1)
+    } else {
+        samples.len()
+    };
+    __gn4_claim.claim_slot_or_busy(weight, rid.clone()).await?;
 
     let script = config.qtl2_script_path.clone();
     let kinship_for_note = kinship.clone();
@@ -443,13 +554,15 @@ pub async fn compute_qtl2(
         .with_note(&format!("Trait: {trait_label}"))
         .with_note(&format!(
             "Rows are positional: marker, chr, pos (Mb), lod. R/qtl2's scan1 over genotype \
-             probabilities, with kinship '{kinship_for_note}' and model '{model_for_note}' over \
-             {cores} cores; \
-             LOD is -log10 of the LMM's p-value for that marker. Autosomes only -- the X needs a \
-             sex covariate and the Y and mitochondrion degenerate the per-chromosome kinship."
+             probabilities, with kinship '{kinship_for_note}' and model '{model_for_note}'; the \
+             genotype probabilities use {cores} core(s). LOD is -log10 of the LMM's p-value at \
+             that marker. Autosomes only -- the X needs a sex covariate and the Y and \
+             mitochondrion degenerate the per-chromosome kinship."
         ))
-        .with_note(&output.command)
-        .with_note(&format!("qtl2: {}", output.summary));
+        .with_note(&output.command);
+    if !output.summary.trim().is_empty() {
+        envelope = envelope.with_note(&format!("qtl2: {}", output.summary.trim()));
+    }
     for note in &notes {
         envelope = envelope.with_note(note);
     }