about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-09 22:28:20 +0000
committerPjotr <wrk@bosa.lan>2026-11-09 22:28:22 +0000
commit7646276e63fb7c4a7433530cfc3314ace3d362d8 (patch)
tree18a0e233b30748bb433669716b8b88e502af44d9 /src
parentdc3e0e5ba0fa6f9462d55e9ca9a4802a60eb205f (diff)
downloadgenenetwork4-7646276e63fb7c4a7433530cfc3314ace3d362d8.tar.gz
compute: R/qtl2 as a third scan, POST /compute/qtl2
R/qtl sits between the existing two scans: Haley-Knott on marker
genotypes, no kinship.  GEMMA is an LMM but biallelic BIMBAM with
mean-imputed genotypes.  Neither can analyse a multiparent population,
and neither models relatedness from the actual genotype data.  R/qtl2
does both -- HMM genotype probabilities, then an LMM with
leave-one-chromosome-out kinship -- and it is what names the third peak
on DOL trait 10003 that R/qtl's scan cannot see (chr16, LOD 4.24,
against GEMMA's -log10 p 7.15 there).

  * src/qtl2.rs converts this deployment's own .geno into a qtl2 cross
    under QTL2_CACHE_DIR: control.json plus geno/gmap/pmap/pheno, with
    the genotype-code map, the orientation and the paths written out
    explicitly.  The shipped genotype/rqtl2/ control files cannot be
    used -- they point outside the data directory, declare no code map
    (every genotype reads as missing) and no orientation (individuals
    read as markers) -- and each of those produces a plausible flat
    scan instead of an error, which is why the conversion is ours.
  * Heterozygous calls are dropped on a riself panel, as R/qtl's
    convert2riself does.  Left in, qtl2 reads the cross as multiparent
    and its scan1 takes a path the panel cannot satisfy ("Error in
    scan1_pg ... : No individuals in common").
  * Autosomes only: X needs a sex covariate to be fitted properly and
    Y/MT degenerate the per-chromosome kinship.  GEMMA's LOCO scan is
    restricted the same way.  The note says how many markers were left
    out.
  * scripts/qtl2_scan.R caches genotype probabilities and kinship by a
    hash of the control file *and its directory*; two conversions of
    the same panel can have identical control files and identical file
    sizes, and reusing the first one's probabilities silently scans the
    wrong cross.  It also takes the individual names from whichever
    shape the cross's pheno slot has -- a single-column pheno file
    leaves it a plain matrix, and the resulting empty phenotype reads
    as scan1's "No individuals in common".
  * Rows are marker, chr, pos, lod, so /plot/rqtl draws the reply
    unchanged -- post the same samples as /compute/rqtl.
  * tests/qtl2.rs: the fixture scans and its notes name the cross; BXD
    trait 10001 peaks on chr8 under both scans; refusals carry
    missing_genotype / invalid_kinship.

cost: 2 concurrent scans, gated from RQTL_LARGE_PANEL individuals like
R/qtl; a DO cross costs minutes of genotype probabilities, paid once
per panel.  QTL2_SCRIPT_PATH and QTL2_CACHE_DIR configure it.
Diffstat (limited to 'src')
-rw-r--r--src/compute_gate.rs12
-rw-r--r--src/config.rs20
-rw-r--r--src/genotypes.rs2
-rw-r--r--src/lib.rs2
-rw-r--r--src/qtl2.rs443
-rw-r--r--src/routes/mod.rs1
-rw-r--r--src/routes/qtl2.rs488
7 files changed, 967 insertions, 1 deletions
diff --git a/src/compute_gate.rs b/src/compute_gate.rs
index c3ad1eb..c5fb48c 100644
--- a/src/compute_gate.rs
+++ b/src/compute_gate.rs
@@ -448,6 +448,18 @@ pub fn ravanan() -> &'static Gate {
     RAVANAN.get_or_init(|| Gate::new(1, GEMMA_LARGE_PANEL))
 }
 
+/// The R/qtl2 gate (`POST /compute/qtl2`): two at a time.
+///
+/// Two because a scan is a single-threaded `Rscript` per chromosome and the
+/// probability calculation is the expensive part; more because the whole
+/// point of qtl2 here is the multiparent crosses, whose genotype
+/// probabilities cost minutes and hundreds of megabytes. Gated from
+/// [`RQTL_LARGE_PANEL`] upwards, like R/qtl itself.
+pub fn qtl2() -> &'static Gate {
+    static QTL2: OnceLock<Gate> = OnceLock::new();
+    QTL2.get_or_init(|| Gate::new(2, RQTL_LARGE_PANEL))
+}
+
 /// The GEMMA gate (`POST /compute/gemma`).
 pub fn gemma() -> &'static Gate {
     static GEMMA: OnceLock<Gate> = OnceLock::new();
diff --git a/src/config.rs b/src/config.rs
index 8a95746..b9f46dc 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -123,6 +123,11 @@ pub struct Config {
     /// effect sizes for named markers. Defaults to that path relative to
     /// the working directory the server is started from.
     pub fitqtl_script_path: String,
+    /// Path to scripts/qtl2_scan.R, which POST /compute/qtl2 runs.
+    pub qtl2_script_path: 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,
     /// Directory POST /compute/rqtl uses for phenotype files, run logs
     /// and the "gn3" subdirectory the R script itself writes its
     /// output into (see src/rqtl.rs). Defaults to a "gn4-rqtl"
@@ -259,6 +264,17 @@ impl Config {
             "scripts/qtl_fitqtl.R".to_string(),
         );
         values.insert(
+            "QTL2_SCRIPT_PATH".to_string(),
+            "scripts/qtl2_scan.R".to_string(),
+        );
+        values.insert(
+            "QTL2_CACHE_DIR".to_string(),
+            std::env::temp_dir()
+                .join("gn4-qtl2")
+                .to_string_lossy()
+                .into_owned(),
+        );
+        values.insert(
             "RQTL_CACHE_DIR".to_string(),
             std::env::temp_dir()
                 .join("gn4-rqtl")
@@ -312,6 +328,8 @@ impl Config {
             "RAVANAN_SCRATCH",
             "RQTL_WRAPPER_PATH",
             "FITQTL_SCRIPT_PATH",
+            "QTL2_SCRIPT_PATH",
+            "QTL2_CACHE_DIR",
             "RQTL_CACHE_DIR",
         ] {
             if let Ok(value) = std::env::var(key) {
@@ -351,6 +369,8 @@ impl Config {
             ravanan_scratch: values["RAVANAN_SCRATCH"].clone(),
             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_cache_dir: values["QTL2_CACHE_DIR"].clone(),
             rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(),
             genotype_files_dir: values["GENOTYPE_FILES"].clone(),
             sql_check_health: parse_switch(&values["SQL_CHECK_HEALTH"]),
diff --git a/src/genotypes.rs b/src/genotypes.rs
index da9745d..28d1266 100644
--- a/src/genotypes.rs
+++ b/src/genotypes.rs
@@ -90,7 +90,7 @@ pub enum OrderSource {
 }
 
 /// A resolved genotype file set for one group at one version.
-#[derive(Debug)]
+#[derive(Debug, Clone)]
 pub struct Resolved {
     pub version: String,
     pub title: Option<String>,
diff --git a/src/lib.rs b/src/lib.rs
index 370c612..bd7f964 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,6 +19,7 @@ mod plot;
 mod error;
 mod gemma;
 pub mod indexer;
+pub mod qtl2;
 pub mod response;
 mod routes;
 mod rqtl;
@@ -128,6 +129,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::gemma::compute_gemma_ravanan))
         .routes(routes!(routes::gemma::gemma_status))
         .routes(routes!(routes::fitqtl::compute_fitqtl))
+        .routes(routes!(routes::qtl2::compute_qtl2))
         .routes(routes!(routes::rqtl::compute_rqtl))
         .routes(routes!(routes::rqtl::rqtl_status));
     // Registered -- and so reachable and listed in /openapi.json -- unless
diff --git a/src/qtl2.rs b/src/qtl2.rs
new file mode 100644
index 0000000..7b79c3d
--- /dev/null
+++ b/src/qtl2.rs
@@ -0,0 +1,443 @@
+//! R/qtl2: genome scans with a linear mixed model, including panels whose
+//! relatedness makes `scanone` misleading.
+//!
+//! `/compute/rqtl` runs R/qtl's `scanone` (Haley-Knott, no kinship) and
+//! `/compute/gemma` fits an LMM but only for biallelic BIMBAM input with
+//! mean-imputed genotypes. R/qtl2 sits between them: genotype
+//! *probabilities* from a hidden Markov model, and an LMM with
+//! leave-one-chromosome-out kinship, which is how multiparent populations
+//! (DO, CC, 4-way) are analysed -- and a better-conditioned model than
+//! either of ours for a plain riset panel.
+//!
+//! Two pieces:
+//!
+//! - [`prepare_cross`] converts this deployment's own `.geno` file into the
+//!   `read_cross2` control file and CSVs, in a cache directory, because the
+//!   shipped `genotype/rqtl2/` copies are not usable: they name paths
+//!   relative to a directory the data is not in, declare no genotype-code
+//!   map (so every genotype is read as missing) and no orientation (so the
+//!   individuals are read as markers). Four separate traps, all of which
+//!   produce a plausible-looking flat scan rather than an error;
+//! - [`compute`] runs `scripts/qtl2_scan.R` over that cross and parses its
+//!   `marker,chr,pos,lod` rows, the same shape `/compute/rqtl` returns and
+//!   `/plot/rqtl` draws.
+//!
+//! Claimed: autosomes only. The X needs a sex covariate to be fitted
+//! properly (and `read_cross2` refuses a map it cannot square with one),
+//! and the Y and mitochondrion degenerate the per-chromosome kinship --
+//! the same reasons GEMMA's LOCO run is given autosomal markers only.
+
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+
+use serde_json::Value;
+
+use crate::genotypes::Resolved;
+use crate::rqtl::Sample;
+use crate::streaming;
+
+/// The columns of every row, in order -- `/compute/rqtl`'s shape, so the
+/// plot endpoint needs no changes.
+pub const COLUMNS: [&str; 4] = ["marker", "chr", "pos", "lod"];
+
+#[derive(Debug)]
+pub enum Qtl2Error {
+    Io(io::Error),
+    /// The panel is a cross type this endpoint does not fit.
+    Unsupported(String),
+    /// R/qtl2 (or its script) failed; the message is its own complaint.
+    CommandFailed(String),
+}
+
+impl std::fmt::Display for Qtl2Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Qtl2Error::Io(error) => write!(f, "{error}"),
+            Qtl2Error::Unsupported(detail) => write!(f, "{detail}"),
+            Qtl2Error::CommandFailed(detail) => write!(f, "{detail}"),
+        }
+    }
+}
+
+/// A converted cross, ready for `read_cross2`.
+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
+    /// do not work).
+    pub control: PathBuf,
+    /// Individual names in the cross, in order.
+    pub individuals: Vec<String>,
+    /// Markers fitted (autosomal).
+    pub markers: usize,
+    /// Markers left out as non-autosomal.
+    pub non_autosomal: usize,
+    /// `riself` or `f2`.
+    pub crosstype: &'static str,
+}
+
+/// One finished scan.
+pub struct Qtl2Output {
+    pub rows: Value,
+    pub markers: usize,
+    pub command: String,
+    pub summary: String,
+}
+
+/// 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()),
+    ))
+}
+
+/// Convert `resolved`'s `.geno` into a cached qtl2 cross.
+pub fn prepare_cross(
+    resolved: &Resolved,
+    cache_dir: &Path,
+) -> Result<PreparedCross, Qtl2Error> {
+    let geno = &resolved.geno;
+    let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?;
+    let stamp = format!(
+        "{}-{}",
+        metadata.len(),
+        metadata
+            .modified()
+            .ok()
+            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+            .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.
+    const CONVERSION_VERSION: &str = "v2";
+    let directory = cache_dir.join("crosses").join(format!(
+        "{CONVERSION_VERSION}-{}-{stamp}",
+        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();
+    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,
+                _ => {}
+            }
+        }
+    }
+    let crosstype = match cross_type.as_str() {
+        "riset" => "riself",
+        "f2" => "f2",
+        other => {
+            return Err(Qtl2Error::Unsupported(format!(
+                "R/qtl2 here fits riset and f2 crosses; this panel is '{other}'. A multiparent \
+                 cross needs founder genotypes (see genotype-files/do/), which a .geno file does \
+                 not carry."
+            )))
+        }
+    };
+    // 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 ...").
+    if crosstype == "riself" {
+        let het = metadata_het(&text);
+        if let Some(het) = het {
+            codes.remove(&het);
+        }
+    }
+    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(),
+        ));
+    }
+
+    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;
+        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("");
+                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": [""],
+            "genotypes": {"A": 1, "H": 2, "B": 3},
+            // 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))?;
+        return Ok(PreparedCross {
+            control,
+            individuals,
+            markers,
+            non_autosomal,
+            crosstype,
+        });
+    }
+
+    // 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);
+    Ok(PreparedCross {
+        control,
+        individuals,
+        markers,
+        non_autosomal: 0,
+        crosstype,
+    })
+}
+
+/// Run the scan over a prepared cross.
+#[allow(clippy::too_many_arguments)]
+pub async fn compute(
+    script: &str,
+    cache_dir: &str,
+    cross: &PreparedCross,
+    trait_name: &str,
+    samples: &[Sample],
+    covariates: &[crate::covariates::Covariate],
+    kinship: &str,
+    model: &str,
+    cores: u32,
+) -> Result<Qtl2Output, Qtl2Error> {
+    let out_dir = Path::new(cache_dir);
+    std::fs::create_dir_all(out_dir).map_err(|e| io_error(out_dir, e))?;
+    let unique = format!(
+        "{}-{}",
+        std::process::id(),
+        std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|d| d.as_nanos())
+            .unwrap_or(0)
+    );
+    let pheno_path = out_dir.join(format!("{unique}-pheno.txt"));
+    crate::rqtl::write_pheno_file(&pheno_path, trait_name, samples, covariates)
+        .map_err(Qtl2Error::Io)?;
+    let covarstruct_path = out_dir.join(format!("{unique}-covarstruct.txt"));
+    let covarstruct_arg = if covariates.is_empty() {
+        None
+    } else {
+        crate::covariates::write_covarstruct_file(&covarstruct_path, covariates)
+            .map_err(Qtl2Error::Io)?;
+        Some(covarstruct_path.to_string_lossy().into_owned())
+    };
+    let result_path = out_dir.join(format!("{unique}-qtl2.csv"));
+    let cores_str = cores.to_string();
+    let result_arg = result_path.to_string_lossy().into_owned();
+    let pheno_arg = pheno_path.to_string_lossy().into_owned();
+    let control_arg = cross.control.to_string_lossy().into_owned();
+    let mut args = vec![
+        script.to_string(),
+        "--control".to_string(),
+        control_arg,
+        "--pheno".to_string(),
+        pheno_arg,
+        "--kinship".to_string(),
+        kinship.to_string(),
+        "--model".to_string(),
+        model.to_string(),
+        "--cores".to_string(),
+        cores_str,
+        "--cache-dir".to_string(),
+        cache_dir.to_string(),
+        "--out".to_string(),
+        result_arg,
+        "--quiet".to_string(),
+    ];
+    if let Some(covarstruct) = covarstruct_arg.as_deref() {
+        args.push("--covariates".to_string());
+        args.push(covarstruct_path.to_string_lossy().into_owned());
+        args.push("--covarstruct".to_string());
+        args.push(covarstruct.to_string());
+    }
+    let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
+    let command = format!("Rscript {}", borrowed.join(" "));
+    let output = streaming::run_streaming("Rscript", &borrowed, None)
+        .await
+        .map_err(Qtl2Error::Io)?;
+    if !output.status.success() {
+        let stderr = String::from_utf8_lossy(&output.stderr);
+        let stdout = String::from_utf8_lossy(&output.stdout);
+        // R ends every failure with "Execution halted"; the sentence before
+        // it is the error. Prefer an `Error` line, then the wrapper's own
+        // output, so a caller sees the cause rather than the epilogue.
+        let interesting = |line: &&str| {
+            let line = line.trim();
+            !line.is_empty()
+                && !line.starts_with("Warning")
+                && !line.starts_with("In ")
+                && line != "Execution halted"
+        };
+        let lines: Vec<&str> = stderr
+            .lines()
+            .chain(stdout.lines())
+            .filter(interesting)
+            .collect();
+        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())
+            .unwrap_or_else(|| "R/qtl2 failed without saying why".to_string());
+        return Err(Qtl2Error::CommandFailed(complaint));
+    }
+    let contents = std::fs::read_to_string(&result_path).map_err(|e| io_error(&result_path, e))?;
+    let rows = parse_rows(&contents);
+    Ok(Qtl2Output {
+        markers: rows.len(),
+        rows: Value::Array(rows),
+        command,
+        summary: String::from_utf8_lossy(&output.stdout)
+            .lines()
+            .filter(|line| !line.trim().is_empty())
+            .next_back()
+            .unwrap_or_default()
+            .trim()
+            .to_string(),
+    })
+}
+
+/// Parse the script's `marker,chr,pos,lod` CSV into positional rows.
+fn parse_rows(contents: &str) -> Vec<Value> {
+    contents
+        .lines()
+        .skip(1)
+        .filter(|line| !line.trim().is_empty())
+        .filter_map(|line| {
+            let fields: Vec<&str> = line.split(',').map(str::trim).collect();
+            if fields.len() < 4 {
+                return None;
+            }
+            Some(Value::Array(vec![
+                Value::String(fields[0].to_string()),
+                Value::String(fields[1].to_string()),
+                serde_json::json!(fields[2].parse::<f64>().ok()?),
+                serde_json::json!(fields[3].parse::<f64>().ok()?),
+            ]))
+        })
+        .collect()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn rows_are_positional_marker_chr_pos_lod() {
+        let rows = parse_rows("marker,chr,pos,lod\nrs1,9,74.99,4.85\nrs2,X,3.0,0.5\n");
+        assert_eq!(rows.len(), 2);
+        let row = rows[0].as_array().unwrap();
+        assert_eq!(row[0], Value::String("rs1".to_string()));
+        assert_eq!(row[1], Value::String("9".to_string()));
+        assert_eq!(row[2], serde_json::json!(74.99));
+        assert_eq!(row[3], serde_json::json!(4.85));
+    }
+
+    #[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");
+        assert_eq!(rows.len(), 1);
+    }
+}
diff --git a/src/routes/mod.rs b/src/routes/mod.rs
index b08497f..87486e0 100644
--- a/src/routes/mod.rs
+++ b/src/routes/mod.rs
@@ -15,6 +15,7 @@ pub mod mapping_methods;
 pub mod phewas;
 pub mod plot;
 pub mod publications;
+pub mod qtl2;
 pub mod rqtl;
 pub mod search;
 pub mod species;
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
new file mode 100644
index 0000000..6cc2346
--- /dev/null
+++ b/src/routes/qtl2.rs
@@ -0,0 +1,488 @@
+//! `POST /compute/qtl2`: a genome scan with R/qtl2.
+//!
+//! The middle ground between `/compute/rqtl` (Haley-Knott, no kinship) and
+//! `/compute/gemma` (an LMM, but biallelic BIMBAM with mean-imputed
+//! genotypes): genotype probabilities from a hidden Markov model and a
+//! linear mixed model with leave-one-chromosome-out kinship. That is how
+//! multiparent populations are analysed, and it is a better-conditioned
+//! model than either for a plain riset panel.
+//!
+//! On DOL trait 10003 the three engines tell the same story with different
+//! emphasis: R/qtl's HK scan peaks on chr9 at LOD 5.86 and misses chr16
+//! entirely; GEMMA's LMM prefers chr16 at -log10 p 7.15; R/qtl2's LMM puts
+//! chr9 (LOD 4.85), chr19 (4.76) and chr16 (4.24) on one footing. The two
+//! LMMs agree on which loci exist, which is what modeling relatedness buys.
+
+use axum::Json;
+use axum::extract::Query;
+use axum::http::StatusCode;
+use serde::Deserialize;
+
+use gnauth_macros::{compute_gate, gnauth};
+
+use crate::auth::AuthToken;
+use crate::compute_gate as gate;
+use crate::config::Config;
+use crate::covariates;
+use crate::error::{ApiError, Unauthorized};
+use crate::genotypes;
+use crate::normalize;
+use crate::qtl2;
+use crate::response::{Ctx, Envelope, RequestInfo, path_segment};
+use crate::rqtl::Sample;
+
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct ComputeQtl2Params {
+    /// Log progress for `GET /compute/rqtl/status/{id}` (shared with
+    /// `/compute/rqtl`, since both run R).
+    pub id: Option<String>,
+}
+
+/// One trait value, by individual name.
+#[derive(Clone, Deserialize, utoipa::ToSchema)]
+pub struct Qtl2Sample {
+    pub name: String,
+    pub value: Option<f64>,
+}
+
+#[derive(Deserialize, utoipa::ToSchema)]
+pub struct Qtl2Request {
+    /// Group to scan (an InbredSet name, e.g. "BXD"); the server resolves
+    /// and converts its `.geno` file.
+    pub group: Option<String>,
+    /// A version from `/groups/{group}/genotypes`.
+    pub genotype_version: Option<String>,
+    /// Explicit `.geno` path on the server, instead of `group`.
+    pub genotype_file: 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
+    /// in the genotype file's order.
+    pub samples: Option<Vec<Qtl2Sample>>,
+    /// Positional values, for a `genotype_file` request.
+    pub trait_values: Option<Vec<Option<f64>>>,
+    /// Label for the trait, e.g. "DOL::10003"; reported in `notes`.
+    pub trait_name: Option<String>,
+    /// `loco` (default), `overall` or `none` for the kinship the LMM uses;
+    /// `none` makes the scan a Haley-Knott scan on genotype probabilities.
+    pub kinship: Option<String>,
+    /// `normal` (default) or `binary`.
+    pub model: 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
+    /// name, or inline values.
+    #[serde(default)]
+    pub covariates: Vec<covariates::Spec>,
+    /// Normalisation of the trait values, as on `/compute/rqtl`.
+    pub normalize: Option<String>,
+    /// Winsorise at a tail fraction, as on `/compute/rqtl`.
+    pub winsor_quantile: Option<f64>,
+    /// Winsorise at Tukey fences, as on `/compute/rqtl`.
+    pub winsor_fences: Option<f64>,
+}
+
+#[utoipa::path(post, path = "/compute/qtl2",
+    summary = "Scan a panel with R/qtl2: genotype probabilities and an LMM with LOCO kinship",
+    description = "Fits R/qtl2's `scan1` over genotype probabilities, with a kinship matrix \
+(`loco` by default), which is the model multiparent populations need and a better-conditioned \
+one than R/qtl's Haley-Knott scan. Autosomes only: the X needs a sex covariate and the Y and \
+mitochondrion degenerate the per-chromosome kinship.",
+    params(ComputeQtl2Params),
+    request_body = Qtl2Request,
+    responses(
+        (status = 200, description = "One row per marker, positional (column names in meta.columns)", body = Envelope<serde_json::Value>),
+        Unauthorized,
+        (status = 409, description = "A compute job is already running for this caller", body = ApiError),
+        (status = 422, description = "No usable cross, trait values or normalisation", body = ApiError),
+        (status = 502, description = "R/qtl2 failed", body = ApiError)
+    )
+)]
+#[gnauth(token_only)]
+#[compute_gate(qtl2, label = "R/qtl2", run_id = params.id.as_deref())]
+pub async fn compute_qtl2(
+    ctx: Ctx,
+    token: AuthToken,
+    Query(params): Query<ComputeQtl2Params>,
+    Json(request): Json<Qtl2Request>,
+) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
+    let rid = ctx.request_info();
+    let config = Config::load();
+    let trait_label = request
+        .trait_name
+        .clone()
+        .filter(|name| !name.trim().is_empty())
+        .unwrap_or_else(|| format!("{}::qtl2", request.group.clone().unwrap_or_default()));
+    let pipeline = normalize::Pipeline::parse(
+        request.normalize.as_deref(),
+        request.winsor_quantile,
+        request.winsor_fences,
+    )
+    .map_err(|detail| {
+        ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_normalization",
+            "Invalid normalization",
+            detail,
+            "compute_qtl2",
+        )
+        .with_request_id(rid.clone())
+    })?;
+    let kinship = request.kinship.clone().unwrap_or_else(|| "loco".to_string());
+    if !matches!(kinship.as_str(), "loco" | "overall" | "none") {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_kinship",
+            "Invalid kinship",
+            format!("kinship '{kinship}' not recognized; use 'loco', 'overall' or 'none'."),
+            "compute_qtl2",
+        )
+        .with_request_id(rid));
+    }
+    let model = request.model.clone().unwrap_or_else(|| "normal".to_string());
+    if !matches!(model.as_str(), "normal" | "binary") {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_model",
+            "Invalid model",
+            format!("model '{model}' not recognized; use 'normal' or 'binary'."),
+            "compute_qtl2",
+        )
+        .with_request_id(rid));
+    }
+    let cores = request.cores.unwrap_or(4).clamp(1, 16);
+
+    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()) {
+        (None, Some(group)) => {
+            let wanted = group.clone();
+            let version = request.genotype_version.clone();
+            let values = request
+                .samples
+                .clone()
+                .map(|samples| {
+                    samples
+                        .into_iter()
+                        .map(|sample| (sample.name, sample.value))
+                        .collect::<Vec<_>>()
+                })
+                .unwrap_or_default();
+            let directory = config.genotype_files_dir.clone();
+            let (resolved, aligned, matched, kept_names) =
+                tokio::task::spawn_blocking(move || {
+                    let resolved = genotypes::resolve(
+                        std::path::Path::new(&directory),
+                        &wanted,
+                        version.as_deref(),
+                    )?;
+                    let excluded = if include_parents_f1 {
+                        std::collections::BTreeSet::new()
+                    } else {
+                        genotypes::non_strains(
+                            std::path::Path::new(&directory),
+                            &wanted,
+                            &resolved.panel,
+                        )
+                    };
+                    let keep: Vec<usize> = resolved
+                        .panel
+                        .iter()
+                        .enumerate()
+                        .filter(|(_, name)| !excluded.contains(*name))
+                        .map(|(index, _)| index)
+                        .collect();
+                    let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values);
+                    let kept_names: Vec<String> = keep
+                        .iter()
+                        .filter_map(|index| resolved.panel.get(*index).cloned())
+                        .collect();
+                    Ok::<_, genotypes::GenotypeError>((resolved, aligned, matched, kept_names))
+                })
+                .await
+                .map_err(|e| {
+                    ApiError::new(
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                        "internal_error",
+                        "Internal error",
+                        e.to_string(),
+                        "compute_qtl2",
+                    )
+                    .with_request_id(rid.clone())
+                })?
+                .map_err(|e| genotypes_error(e, rid.clone()))?;
+            if matched == 0 {
+                return Err(ApiError::new(
+                    StatusCode::UNPROCESSABLE_ENTITY,
+                    "no_samples_aligned",
+                    "No samples aligned",
+                    format!(
+                        "none of the supplied samples appear in genotype version '{}'.",
+                        resolved.version
+                    ),
+                    "compute_qtl2",
+                )
+                .with_request_id(rid));
+            }
+            notes.push(format!(
+                "Genotype: {} (version {}, {} individuals); {} values used.",
+                resolved.relative(std::path::Path::new(&config.genotype_files_dir), &resolved.geno),
+                resolved.version,
+                kept_names.len(),
+                aligned.iter().filter(|value| value.is_some()).count()
+            ));
+            let samples: Vec<Sample> = kept_names
+                .into_iter()
+                .zip(aligned)
+                .map(|(name, value)| Sample { name, value })
+                .collect();
+            (resolved, samples)
+        }
+        (Some(file), None) => {
+            let values = request.trait_values.clone().unwrap_or_default();
+            if values.is_empty() {
+                return Err(ApiError::new(
+                    StatusCode::UNPROCESSABLE_ENTITY,
+                    "missing_trait_values",
+                    "No trait values",
+                    "with an explicit genotype_file, give `trait_values` (one per individual, \
+                     in the file's order)."
+                        .to_string(),
+                    "compute_qtl2",
+                )
+                .with_request_id(rid));
+            }
+            // A path request has no panel metadata; the cross carries its own
+            // individual order, so names are placeholders here.
+            let resolved = genotypes::Resolved {
+                version: std::path::Path::new(&file)
+                    .file_stem()
+                    .map(|stem| stem.to_string_lossy().into_owned())
+                    .unwrap_or_default(),
+                title: None,
+                geno: std::path::PathBuf::from(&file),
+                bimbam_geno: None,
+                bimbam_snps: None,
+                panel: Vec::new(),
+            };
+            // The cross's own individual order is the only name source a
+            // path request has; the values are positional over it, so they
+            // are named after the conversion (below), not here.
+            let samples: Vec<Sample> = values
+                .into_iter()
+                .enumerate()
+                .map(|(index, value)| Sample {
+                    name: format!("individual-{}", index + 1),
+                    value,
+                })
+                .collect();
+            (resolved, samples)
+        }
+        (Some(_), Some(_)) => {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give either genotype_file or group, not both.".to_string(),
+                "compute_qtl2",
+            )
+            .with_request_id(rid));
+        }
+        (None, None) => {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "missing_genotype",
+                "No genotype input",
+                "give 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.
+    let samples = if pipeline.is_identity() {
+        samples
+    } else {
+        let raw: Vec<Option<f64>> = samples.iter().map(|sample| sample.value).collect();
+        let (normalized, applied) = pipeline.apply(&raw).map_err(|detail| {
+            ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_normalization",
+                "Invalid normalization",
+                detail,
+                "compute_qtl2",
+            )
+            .with_request_id(rid.clone())
+        })?;
+        notes.push(pipeline.describe(&applied));
+        samples
+            .into_iter()
+            .zip(normalized)
+            .map(|(sample, value)| Sample { name: sample.name, value })
+            .collect()
+    };
+
+    let (covariate_list, covariate_notes) = covariates::resolve(
+        &request.covariates,
+        &samples.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
+        request_group.as_deref(),
+        Some(&samples.iter().map(|s| s.value.is_some()).collect::<Vec<_>>()),
+        rid.clone(),
+    )
+    .await?;
+    notes.extend(covariate_notes);
+
+    // 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))
+    })
+    .await
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            e.to_string(),
+            "compute_qtl2",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map_err(|e| match e {
+        qtl2::Qtl2Error::Unsupported(detail) => ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "unsupported_cross",
+            "Unsupported cross",
+            detail,
+            "compute_qtl2",
+        )
+        .with_request_id(rid.clone()),
+        other => ApiError::new(
+            StatusCode::BAD_GATEWAY,
+            "qtl2_failed",
+            "R/qtl2 failed",
+            other.to_string(),
+            "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
+            .into_iter()
+            .zip(cross.individuals.iter())
+            .map(|(sample, name)| Sample {
+                name: name.clone(),
+                value: sample.value,
+            })
+            .collect()
+    } else {
+        samples
+    };
+    notes.push(format!(
+        "Cross: {} ({} individuals, {} autosomal markers{})",
+        cross.crosstype,
+        cross.individuals.len(),
+        cross.markers,
+        if cross.non_autosomal > 0 {
+            format!(", {} non-autosomal left out", cross.non_autosomal)
+        } else {
+            String::new()
+        }
+    ));
+
+    let individuals = samples.len();
+    __gn4_claim
+        .claim_slot_or_busy(individuals, rid.clone())
+        .await?;
+
+    let script = config.qtl2_script_path.clone();
+    let kinship_for_note = kinship.clone();
+    let model_for_note = model.clone();
+    let trait_label_for_job = trait_label.clone();
+    let rid_for_job = rid.clone();
+    let output = gate::qtl2()
+        .run(__gn4_claim, async move {
+            qtl2::compute(
+                &script,
+                &cache_dir,
+                &cross,
+                &trait_label_for_job,
+                &samples,
+                &covariate_list,
+                &kinship,
+                &model,
+                cores,
+            )
+            .await
+            .map_err(|e| {
+                ApiError::new(
+                    StatusCode::BAD_GATEWAY,
+                    "qtl2_failed",
+                    "R/qtl2 failed",
+                    e.to_string(),
+                    "compute_qtl2",
+                )
+                .with_request_id(rid_for_job)
+            })
+        })
+        .await?;
+
+    let num_rows = output.markers;
+    let mut envelope = ctx
+        .envelope(output.rows)
+        .with_columns(
+            qtl2::COLUMNS.iter().map(|name| name.to_string()).collect(),
+            num_rows,
+        )
+        .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."
+        ))
+        .with_note(&output.command)
+        .with_note(&format!("qtl2: {}", output.summary));
+    for note in &notes {
+        envelope = envelope.with_note(note);
+    }
+    if let Some(group) = request_group {
+        envelope = envelope.with_action(crate::response::SuggestedCall {
+            method: "POST".to_string(),
+            href: "/plot/rqtl".to_string(),
+            description: "Draw this scan: the rows are the same shape /plot/rqtl takes (marker, \
+                          chr, pos, lod), so posting this response back gives a Manhattan plot \
+                          with no reshaping."
+                .to_string(),
+            body: None,
+        });
+        envelope = envelope.with_next(
+            &format!("/groups/{}/phewas", path_segment(&group)),
+            "PheWAS: every published trait peaking near a locus (add ?locus=)",
+        );
+    }
+    Ok(Json(envelope))
+}
+
+fn genotypes_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiError {
+    let (status, code, title) = match error {
+        genotypes::GenotypeError::NotFound(_) => (
+            StatusCode::NOT_FOUND,
+            "genotypes_not_found",
+            "Genotype file not found",
+        ),
+        genotypes::GenotypeError::Io(_) => (
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "genotypes_unreadable",
+            "Genotype files could not be read",
+        ),
+    };
+    ApiError::new(status, code, title, error.to_string(), "compute_qtl2").with_request_id(rid)
+}