diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 11:25:49 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 11:25:49 +0000 |
| commit | 8f4a9512d7fb4ac518341f23a4b062ccf80e2a7d (patch) | |
| tree | 698de016efbd16f2a659eac3f57c8df40babdf2f | |
| parent | 7646276e63fb7c4a7433530cfc3314ace3d362d8 (diff) | |
| download | genenetwork4-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(...) :".
| -rw-r--r-- | README.md | 30 | ||||
| -rw-r--r-- | docs/www/SKILL.md | 6 | ||||
| -rwxr-xr-x | scripts/qtl2_scan.R | 57 | ||||
| -rw-r--r-- | src/qtl2.rs | 326 | ||||
| -rw-r--r-- | src/routes/qtl2.rs | 169 | ||||
| -rw-r--r-- | tests/qtl2.rs | 94 |
6 files changed, 643 insertions, 39 deletions
diff --git a/README.md b/README.md index 31ac1fd..c8ae156 100644 --- a/README.md +++ b/README.md @@ -1450,6 +1450,36 @@ the Y and mitochondrion degenerate the per-chromosome kinship — GEMMA's LOCO run is given the same restriction, for the same reason. The `notes` say how many markers were left out. +**Multiparent crosses.** A multiparent population cannot come from a +`.geno`: that file carries two codes per marker (`B`/`D`, `A`/`H`/`B`), which +is a collapse, not a founder allele. It has to ship its own qtl2 control file +with founder genotypes, so the endpoint also takes a cross by name: + +```json +{"rqtl2_cross": "do", "trait_name": "DO::WBC", + "samples": [{"name": "JAXW202.2129", "value": 4.34}, …]} +``` + +The name is looked up as `genotype/rqtl2/{name}.json`, then +`{name}/{name}.json`, then `{name}.json` under `GENOTYPE_FILES`; `do/` is the +one such cross this deployment has (742 individuals, 8 founders A–H, 6 413 +markers, WBC and NEUT). The samples are matched to the cross by name and +anything outside its population is left out (and counted in `notes`). + +A multiparent scan is a **different claim** from a biallelic one: every marker +is fitted with one coefficient per founder, so the LOD asks whether *any* +founder differs, not which. Reading a multiparent LOD as a strain effect is the +usual mistake; per-founder effect sizes need `scan1coef`, which this endpoint +does not return yet. + +Measured on the DO (`WBC`, 8 cores): genotype probabilities 174 s and 1.39 GB, +cached per cross and keyed by the control file *and its directory*; LOCO +kinship 15 s, cached; the scan itself 21 s. `scan1` is run on one core for a +multiparent cross deliberately — its forked path stalls here on allele +probabilities (25+ minutes with 8 cores and no CPU consumed, against 21 s +serial). The autosomes-only rule applies here too: the DO's X is left out (369 +markers) rather than fitted without a sex covariate. + **Panel conversion.** The cross is generated from this deployment's own `.geno` file and cached (`QTL2_CACHE_DIR`), because the shipped `genotype/rqtl2/` control files are not usable: they name paths relative to a diff --git a/docs/www/SKILL.md b/docs/www/SKILL.md index 67ce622..2e63419 100644 --- a/docs/www/SKILL.md +++ b/docs/www/SKILL.md @@ -158,6 +158,12 @@ header (peak and, for GEMMA, the Bonferroni line). marker equals `/compute/rqtl`'s LOD at that marker; with one fitted it is a different model, so the two no longer match — quote the scan for "where", this for "how much". +* `/compute/qtl2` with `"rqtl2_cross": "do"`: a **multiparent** scan — 8 + founder alleles, an LMM with LOCO kinship. Only a cross that ships founder + genotypes can do this (a `.geno` is a biallelic collapse); `do` is the one + this deployment has. Pass `samples` by name; the LOD means "some founder + differs", not "this strain differs" — per-founder effects are not returned + yet. Minutes of genotype probabilities the first time, cached per cross. * `/compute/qtl2`: the same panel through **R/qtl2** — genotype probabilities and an LMM with `loco` kinship (`"kinship": "none"` turns it into a Haley-Knott scan on probabilities). Rows are `marker, chr, pos, lod`, diff --git a/scripts/qtl2_scan.R b/scripts/qtl2_scan.R index 6c0d355..6044db3 100755 --- a/scripts/qtl2_scan.R +++ b/scripts/qtl2_scan.R @@ -65,7 +65,10 @@ if (!is.null(opt[["cache-dir"]])) { # the same panel (an older one in another cache directory, say) can have # identical control files and identical file sizes, and reusing the first # one's probabilities silently scans the wrong cross. - parts <- list(dirname(normalizePath(opt$control, mustWork = FALSE)), control) + # The rules this script applies to the cross (the autosome subset) are + # part of the key too: caching probabilities that were computed under a + # different rule would silently change what a scan means. + parts <- list("scan-rules-v1", dirname(normalizePath(opt$control, mustWork = FALSE)), control) for (key in c("geno", "founder_geno", "gmap", "pmap", "pheno", "covar")) { path <- control[[key]] if (!is.null(path)) { @@ -84,6 +87,25 @@ cross <- read_cross2(opt$control, quiet = opt$quiet) say("cross:", cross$crosstype, "| individuals:", n_ind(cross), "| markers:", sum(n_mar(cross)), "| chromosomes:", n_chr(cross)) +# ---- autosomes only --------------------------------------------------- +# A cross this API converted has its non-autosomal markers removed already; +# one read from a control file (the DO, say) carries X, Y and MT as the panel +# does. X needs a sex covariate to be fitted properly and Y/MT degenerate the +# per-chromosome kinship, so both sources get the same treatment here and the +# number left out is printed rather than silently changing the scan. +chromosomes <- names(cross$gmap) +if (is.null(chromosomes)) chromosomes <- names(cross$pmap) +if (!is.null(chromosomes)) { + autosomal <- chromosomes[grepl("^[0-9]+$", chromosomes)] + left_out <- setdiff(chromosomes, autosomal) + if (length(left_out) > 0 && length(autosomal) > 0) { + before <- sum(n_mar(cross)) + cross <- cross[, chr = autosomal] + say("autosomes only: left out", paste(left_out, collapse = ","), "|", + before - sum(n_mar(cross)), "markers") + } +} + # ---- genotype probabilities, cached per chromosome -------------------- # Multiparent means more than two founder alleles -- eight for the DO. The # founder genotypes are the honest test; a biallelic cross has none. @@ -129,7 +151,11 @@ if (opt$kinship != "none") { } # ---- phenotype and covariates, aligned by name ------------------------ -df <- read.table(opt$pheno, na.strings = "x", header = TRUE, check.names = FALSE) +# sep = "\t" because a trait label may contain a space: with the default +# whitespace separator, "DO::10001 (WBC)" splits into three fields and +# read.table stops with "line 1 did not have 3 elements", which reads like a +# malformed file rather than a label with a space in it. +df <- read.table(opt$pheno, sep = "\t", na.strings = "x", header = TRUE, check.names = FALSE) trait_name <- colnames(df)[2] # The cross's individuals, whatever shape its pheno slot takes: a matrix # with rownames when the cross file carries several phenotypes, a named @@ -149,7 +175,7 @@ pheno <- matrix(values, ncol = 1, dimnames = list(ind, trait_name)) addcovar <- NULL if (!is.null(opt$covariates)) { - covar_df <- read.table(opt$covariates, header = TRUE, check.names = FALSE, na.strings = "x") + covar_df <- read.table(sep = "\t", opt$covariates, header = TRUE, check.names = FALSE, na.strings = "x") struct <- read.table(opt$covarstruct, header = FALSE, sep = "\t", stringsAsFactors = FALSE, col.names = c("name", "kind"), quote = "") addcovar <- data.frame(row.names = ind) @@ -181,13 +207,36 @@ if (!is.null(opt$covariates)) { # ---- the scan --------------------------------------------------------- started <- Sys.time() +# Multiparent crosses are scanned on one core, deliberately. scan1's forked +# path stalls here on allele probabilities -- the parent sits in waitpid with +# the children idle (measured: 25+ minutes with cores=8, no CPU consumed), +# while cores=1 scans the whole DO genome in 21 s. The expensive step, the +# genotype probabilities, is still parallel; only the scan is serial, and it +# is the cheap one. +scan_cores <- if (multiparent) 1L else opt$cores +if (multiparent && opt$cores > 1) { + say("scan1 on 1 core: the forked path stalls on allele probabilities") +} scan <- scan1(scan_probs, pheno, kinship = kinship, addcovar = addcovar, - model = opt$model, cores = opt$cores) + model = opt$model, cores = scan_cores) say("scan1:", round(as.numeric(difftime(Sys.time(), started, units="secs")), 1), "s") # ---- rows: marker, chr, pos(Mb), lod ---------------------------------- map <- if (!is.null(cross$pmap)) cross$pmap else cross$gmap in_mb <- !is.null(cross$pmap) +# qtl2 documents a physical map in base pairs, and the control files this API +# writes do hold bp -- but a map that ships with a panel may be in Mb (the +# DO's is: 74.22 for a chr6 marker, not 74223530). Dividing by 1e6 twice put +# every DO peak at 0.0 Mb, which plots as a peak at the telomere of nothing. +# A whole mouse chromosome is ~2e8 bp and ~200 Mb, so the largest position +# says which unit the map is in. +if (in_mb) { + largest <- suppressWarnings(max(unlist(cross$pmap), na.rm = TRUE)) + if (is.finite(largest) && largest < 1e6) { + say("physical map: already in Mb (largest position", round(largest, 1), ")") + in_mb <- FALSE + } +} rows <- list() for (chr_name in names(map)) { positions <- map[[chr_name]] 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 ¬es { envelope = envelope.with_note(note); } diff --git a/tests/qtl2.rs b/tests/qtl2.rs index 5b3f5fe..eb77e67 100644 --- a/tests/qtl2.rs +++ b/tests/qtl2.rs @@ -180,3 +180,97 @@ async fn qtl2_refuses_inputs_it_cannot_scan() { assert_eq!(error["code"], code, "{error}"); } } + +/// A cross that ships its own control file is the only route to a +/// multiparent scan, so its refusals matter: the name must exist, the +/// samples must belong to the cross, and the two genotype sources cannot +/// both be named. +#[tokio::test] +async fn a_shipped_multiparent_cross_is_named_not_guessed() { + let Some(token) = ready().await else { return }; + for (body, code) in [ + ( + serde_json::json!({"rqtl2_cross": "nonesuch", + "samples": [{"name": "S1", "value": 1.0}]}), + "unsupported_cross", + ), + (serde_json::json!({"rqtl2_cross": "do"}), "missing_samples"), + ( + serde_json::json!({"rqtl2_cross": "do", + "samples": [{"name": "not-an-individual", "value": 1.0}]}), + "no_samples_in_cross", + ), + ( + serde_json::json!({"rqtl2_cross": "do", "group": "BXD", + "samples": [{"name": "BXD1", "value": 1.0}]}), + "ambiguous_genotype", + ), + ] { + let response = + common::post_json_with_token("POST /compute/qtl2 (cross)", "/compute/qtl2", &token, &body) + .await; + let status = response.status(); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{error}"); + assert_eq!(error["code"], code, "{error}"); + } +} + +/// The real thing: the DO, 8 founder alleles, an LMM with LOCO kinship. +/// Ignored because the genotype probabilities for 742 individuals over 6 413 +/// markers take minutes the first time (then they are cached); run it with +/// `cargo test --test qtl2 -- --ignored`. +#[tokio::test] +#[ignore] +async fn a_do_scan_fits_eight_founder_alleles() { + let Some(token) = ready().await else { return }; + let pheno_path = std::path::Path::new( + "/home/wrk/tmp/ai-root/factory/gn4-data/genotype-files/do/do_pheno.csv", + ); + let Ok(text) = std::fs::read_to_string(pheno_path) else { + eprintln!("skipping: {} is not readable", pheno_path.display()); + return; + }; + let mut samples = Vec::new(); + for line in text.lines().filter(|line| !line.starts_with('#')) { + let fields: Vec<&str> = line.split(',').collect(); + if fields.len() < 2 || fields[0] == "id" { + continue; + } + samples.push(serde_json::json!({ + "name": fields[0], + "value": fields[1].parse::<f64>().ok(), + })); + } + assert!(samples.len() > 700, "the DO's 742 individuals: {}", samples.len()); + let body = serde_json::json!({ + "rqtl2_cross": "do", + "trait_name": "DO::WBC", + "samples": samples, + "cores": 8, + }); + let response = + common::post_json_with_token("POST /compute/qtl2 (DO)", "/compute/qtl2", &token, &body).await; + let status = response.status(); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); + let envelope: Value = serde_json::from_slice(&bytes).unwrap(); + let rows = envelope["data"].as_array().unwrap(); + assert!(rows.len() > 5000, "the DO's autosomes: {}", rows.len()); + let notes: Vec<&str> = envelope["notes"] + .as_array() + .unwrap() + .iter() + .map(|note| note.as_str().unwrap()) + .collect(); + let cross_note = notes.iter().find(|note| note.starts_with("Cross: ")).unwrap(); + assert!(cross_note.contains("do"), "{cross_note}"); + assert!(cross_note.contains("8 founder alleles"), "{cross_note}"); + // WBC's known peak region: the scan says something, not a flat line. + let best = rows + .iter() + .map(|row| row[3].as_f64().unwrap()) + .fold(0.0_f64, f64::max); + assert!(best > 3.0, "a real peak, not noise: {best}"); +} |
