From 061b76a5d963b7d5e2ce9d858094b305929766f2 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 18:11:38 +0000 Subject: scripts/make-mdb.sh: build pangemma's genotype store, lock-free and frozen pangemma picks an LMDB genotype store by looking for ".mdb" in the -g path (src/param.cpp:943), so the store's name is part of the interface. Two of gemma-wrapper's helpers make it -- anno2mdb.rb then geno2mdb.rb -- and this script does the three things they leave to the caller: * the lock file. Measured on a real store: these environments are single files (MDB_NOSUBDIR), and the lock is a *sibling*, .mdb-lock, which every open recreates with different bytes (8d3d268b after writing, another sha1 after one read-only open, another after a read-write open) while the .mdb itself never changes. Since the .mdb is what gets hashed and interned, the lock is deleted after writing and the .mdb is made read-only. * the name: .geno.mdb, so `-g' recognises it and the outer name says which translation it holds (Gf, Gb, G0_1, G0_2). * atomicity: the makers write beside their input, so they are given links in a temporary directory and the finished store is renamed into place; nothing is written next to the caller's files (an earlier hand run of anno2mdb.rb put a 2 MB .mdb into gn4-data, which is exactly the mistake this prevents). Measured on BXD.8 (21 056 markers, 235 individuals): 0.17 s for the annotation half, 4.7 s for the genotypes, 29 MB as Gf. Two things found while testing it, both for the plan rather than this script: the anno mdb is an intermediate that pangemma does not need (it takes the snps file with -a), so it is not kept; and a store built from a BIMBAM whose chr/pos columns are the "X"/"Y" placeholders makes pangemma produce an all-NaN K silently -- 235 individuals read, no error, a 235x235 matrix of -nan -- because geno2mdb keys genotypes by (chr,pos) and nothing matches the annotation. --- scripts/make-mdb.sh | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100755 scripts/make-mdb.sh (limited to 'scripts') diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh new file mode 100755 index 0000000..ea58fc6 --- /dev/null +++ b/scripts/make-mdb.sh @@ -0,0 +1,93 @@ +#!/bin/sh +# make-mdb.sh -- build pangemma's genotype store (an LMDB environment) from a +# BIMBAM genotype file and its marker annotation. +# +# Two of gemma-wrapper's helpers do the work: +# +# anno2mdb.rb snps.txt -> .snps.mdb (chr/pos -> marker name) +# geno2mdb.rb geno.txt --anno .snps.mdb -> .geno.mdb +# +# and this script exists for the three things they leave to the caller: +# +# 1. the lock file. An LMDB environment is data.mdb *plus* lock.mdb, and +# lock.mdb's bytes change on every open -- measured: 8d3d268b after writing, +# a different sha1 after one read-only open, different again after a +# read-write open, while data.mdb never changed. A directory whose hash is +# its identity (ravanan interns inputs by content) must therefore not +# contain one, so it is removed last and the tree is made read-only to stop +# anything recreating it. +# 2. the name. pangemma decides "this is an mdb" by looking for ".mdb" in the +# -g path (src/param.cpp:943), so the directory must end in .mdb and the +# outer name should say which translation it holds. +# 3. atomicity. A half-written environment must never be visible under the +# final name: build under a temporary name in the destination directory and +# rename when whole. +# +# scripts/make-mdb.sh --geno --snps \ +# [--eval Gf|Gb|G0_1|G0_2] [--name NAME] [--out DIR] +# +# Prints the directory it built. Exit 2 on bad arguments, 1 on a maker failure. +set -eu + +geno= snps= eval_=Gf name= out=. +while [ $# -gt 0 ]; do + case $1 in + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --eval) eval_=$2; shift 2 ;; + --name) name=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "make-mdb.sh: unknown argument $1" >&2; exit 2 ;; + esac +done +[ -n "$geno" ] && [ -n "$snps" ] || { echo "make-mdb.sh: --geno and --snps are required" >&2; exit 2; } +for f in "$geno" "$snps"; do + [ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; } +done +case $eval_ in Gf|Gb|G0_1|G0_2) ;; *) echo "make-mdb.sh: unknown --eval $eval_" >&2; exit 2 ;; esac + +# The makers, and something to run them with. MAKE_MDB_ANNO / MAKE_MDB_GENO +# let a caller point at a different checkout; ANNO2MDB_OK is set by the caller +# when it has checked they exist. +ANNO=${ANNO2MDB:-anno2mdb.rb} +GENO=${GENO2MDB:-geno2mdb.rb} +for tool in "$ANNO" "$GENO"; do + command -v "$tool" >/dev/null 2>&1 || { echo "make-mdb.sh: $tool is not on PATH" >&2; exit 1; } +done + +mkdir -p "$out" +[ -n "$name" ] || name=$(basename "$geno" | sed 's/\.\(txt\|gz\|bimbam\)$//') +work=$(mktemp -d "$out/.$name.XXXXXX") +trap 'rm -rf "$work"' EXIT + +# The makers write .mdb *beside their input* and take it as a +# positional argument, so they get links to work on: nothing is written next to +# the caller's files. +ln -s "$(cd "$(dirname "$geno")" && pwd)/$(basename "$geno")" "$work/geno.txt" +ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" + +# 1. the annotation half. It is an intermediate: pangemma is given the snps +# file itself (-a) and only geno2mdb needs this database, so it is not kept. +"$ANNO" "$work/snps.txt" >/dev/null 2>&1 || + { echo "make-mdb.sh: anno2mdb.rb failed" >&2; exit 1; } + +# 2. the genotypes, translated the way pangemma expects +"$GENO" --eval "$eval_" --anno "$work/snps.txt.mdb" "$work/geno.txt" >/dev/null 2>&1 || + { echo "make-mdb.sh: geno2mdb.rb failed" >&2; exit 1; } + +# 3. the lock file. These environments are single files (MDB_NOSUBDIR), so the +# lock is a *sibling*, .mdb-lock -- measured on a real store: every +# open recreates it with different bytes while the .mdb itself never changes. +# The .mdb is what gets interned and hashed (a File input hashes its +# content), so the lock only needs to go so the directory we hand out +# contains nothing but the store itself. +rm -f "$work/geno.txt.mdb-lock" "$work/snps.txt.mdb-lock" +chmod a-w "$work/geno.txt.mdb" + +rm -f "$out/$name.geno.mdb" "$out/$name.geno.mdb-lock" +mv "$work/geno.txt.mdb" "$out/$name.geno.mdb" +trap 'rm -rf "$work"' EXIT +rm -rf "$work" +trap - EXIT +printf '%s\n' "$out/$name.geno.mdb" -- cgit 1.4.1 From 304b92e310df9570a67ef3cdd3bbcc714569bc83 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:14:29 +0000 Subject: correlation: PC traits as basket columns, and compare-two-traits **PC traits.** `pca.traits` carries each component *as a trait*: PC1, PC2, ... with a score per individual, so a component can be used the way GN2's "PCA traits" are -- correlated, mapped, plotted, saved. Scores are the standardised values projected onto the loadings, standardised with the sample standard deviation because that is what the correlation matrix was built from; a constant trait has no z-score and refuses rather than filling a zero. They live on the complete cases of the kept traits (31 of 34 in the fixture), which is the honest reading of "a PCA is defined on a rectangle". The module story is a basket: POST /baskets with a PC's values gives a per-user, versioned, digest-recorded column (verified: 201, revision 1, values read back), which the mapping and plotting endpoints already accept. No new store, no new dataset concept. **Compare traits.** POST /compute/compare takes two trait references, keeps the individuals with a value for both, and returns r, p, n *and* the pairs -- the statistic and the data behind it. It agrees with the matrix: the same pair is r = 0.6756270426459695 in both. POST /plot/compare draws the scatter (6 303 bytes) with the individual's name in each tooltip and the OLS line implied by r and the two means; nothing is refitted. Monitor gained compute-compare and plot-compare; full run 49 ok, 0 failed, 1 skipped. Not done, deliberately: limit_to/ids_only/names_only. The listing handlers return typed rows (Envelope>), so "names only" is a shape change in every one of them -- a pass of its own rather than a query parameter. --- bin/monitor-gn4 | 35 +++++ scripts/plot-compare.py | 124 +++++++++++++++++ src/config.rs | 8 ++ src/lib.rs | 2 + src/pca.rs | 90 ++++++++++++ src/routes/compare.rs | 290 +++++++++++++++++++++++++++++++++++++++ src/routes/correlation.rs | 2 +- src/routes/correlation_matrix.rs | 80 ++++++++++- src/routes/mod.rs | 1 + src/routes/plot.rs | 2 +- 10 files changed, 627 insertions(+), 7 deletions(-) create mode 100755 scripts/plot-compare.py create mode 100644 src/routes/compare.rs (limited to 'scripts') diff --git a/bin/monitor-gn4 b/bin/monitor-gn4 index 609fdb8..f7f0365 100755 --- a/bin/monitor-gn4 +++ b/bin/monitor-gn4 @@ -685,6 +685,14 @@ def build_checks(found, tiers): "top_n": 5}, judge=has_rows, hint="no external tool: pure Rust + MariaDB")) + # Two traits, their shared individuals, and the scatter data. + add(Check("compute-compare", "compute", "POST", "/compute/compare", + "two traits, shared individuals and r (pure Rust)", + body={"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, + judge=has_comparison, + hint="no external tool: pure Rust + MariaDB")) add(Check("compute-rqtl", "compute", "POST", "/compute/rqtl", "R + r-qtl", body={"group": g, "method": "hk", "trait_name": found.trait, @@ -741,6 +749,11 @@ def build_checks(found, tiers): "clustered matrix -> heatmap svg (HEATMAP_PLOTTER)", body=heatmap_plot_body(found), expect=200, hint="HEATMAP_PLOTTER and python3", judge=has_svg)) + if found.control_trait: + add(Check("plot-compare", "plots", "POST", "/plot/compare", + "comparison -> scatter svg (COMPARE_PLOTTER)", + body=compare_plot_body(found), expect=200, + hint="COMPARE_PLOTTER and python3", judge=has_svg)) if found.samples: # The Manhattan plot: a GEMMA run's reply, posted back as-is. add(Check("plot-gemma", "plots", "POST", "/plot/gemma", @@ -785,6 +798,19 @@ def perturbed(body): return None +def has_comparison(reply): + """r, n and the pairs behind them.""" + data = (reply.json or {}).get("data") or {} + pairs = data.get("pairs") + if not isinstance(pairs, list) or len(pairs) < 2: + return FAIL, "no pairs in the answer" + if data.get("n") != len(pairs): + return FAIL, "n=%s but %d pairs" % (data.get("n"), len(pairs)) + if not isinstance(data.get("r"), (int, float)): + return FAIL, "r is %r" % (data.get("r"),) + return OK, "r %.4f over %d individual(s)" % (data["r"], len(pairs)) + + def has_clustering(reply): """A clustered order that is a permutation, with n-1 merges.""" data = (reply.json or {}).get("data") or {} @@ -868,6 +894,15 @@ def _post_result(client, path, body, what): return reply.json or {} +def compare_plot_body(found): + def build(client): + return _post_result(client, "/compute/compare", + {"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, "comparison") + return build + + def heatmap_plot_body(found): def build(client): return _post_result(client, "/compute/correlation/matrix", diff --git a/scripts/plot-compare.py b/scripts/plot-compare.py new file mode 100755 index 0000000..77aeae2 --- /dev/null +++ b/scripts/plot-compare.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Scatter plot of two compared traits, as one SVG panel. + +Input is the JSON response of POST /compute/compare (saved as-is): the paired +values, the individual names, and the r/p/n they came with. The line is the +ordinary least-squares line implied by r and the two means -- nothing is +refitted here, and nothing is invented beyond what the reply carries. + + python3 plot-compare.py compare.json -o compare.svg --trait "1427571_at vs 1427641_at" + +Standard library only; writes plain SVG (light/dark aware). +""" +import argparse +import json +import sys + +W, H = 760, 520 +L, R, T, B = 64, 150, 78, 64 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("result", help="saved /compute/compare response (JSON)") + ap.add_argument("-o", "--out", default="compare.svg") + ap.add_argument("--trait", default="", help="label for the title") + ap.add_argument("--title", default=None) + a = ap.parse_args() + + doc = json.load(open(a.result)) + data = doc.get("data") if isinstance(doc.get("data"), dict) else doc + pairs = data.get("pairs") or [] + if len(pairs) < 2: + sys.exit(f"{a.result}: no `pairs` -- post a /compute/compare reply") + r_value = data.get("r") + p_value = data.get("p") + n = data.get("n") or len(pairs) + first = (data.get("a") or {}) + second = (data.get("b") or {}) + + xs = [float(row[1]) for row in pairs] + ys = [float(row[2]) for row in pairs] + xmin, xmax = min(xs), max(xs) + ymin, ymax = min(ys), max(ys) + pad_x = (xmax - xmin) * 0.06 or 0.5 + pad_y = (ymax - ymin) * 0.06 or 0.5 + xmin, xmax = xmin - pad_x, xmax + pad_x + ymin, ymax = ymin - pad_y, ymax + pad_y + + pw, ph = W - L - R, H - T - B + + def X(v): + return L + (v - xmin) / (xmax - xmin) * pw + + def Y(v): + return T + ph - (v - ymin) / (ymax - ymin) * ph + + label = a.trait or (f"{first.get('trait_name', 'a')} vs {second.get('trait_name', 'b')}") + title = a.title or f"{label}: scatter" + method = data.get("method") or "pearson" + sub = (f"{method} r = {r_value:+.4f}" if isinstance(r_value, (int, float)) else f"{method} r = ?") + if isinstance(p_value, (int, float)): + sub += f", p = {p_value:.3g}" + sub += f", n = {n}" + if data.get("only_one_side"): + sub += f" · {data['only_one_side']} individual(s) had a value for only one trait" + desc = (f"Scatter of {first.get('trait_name', 'a')} ({first.get('dataset', '')}) against " + f"{second.get('trait_name', 'b')} ({second.get('dataset', '')}) over {n} individuals, " + f"{method} r {r_value}.") + + s = [f''' +{title} +{desc} + + +{title} +{sub}'''] + + for step in range(5): + value = ymin + (ymax - ymin) * step / 4 + y = Y(value) + s.append(f'') + s.append(f'{value:.3g}') + for step in range(5): + value = xmin + (xmax - xmin) * step / 4 + x = X(value) + s.append(f'{value:.3g}') + + # Least-squares line implied by r and the two standard deviations. + if isinstance(r_value, (int, float)) and n > 2: + mean_x = sum(xs) / n + mean_y = sum(ys) / n + var_x = sum((v - mean_x) ** 2 for v in xs) / (n - 1) + var_y = sum((v - mean_y) ** 2 for v in ys) / (n - 1) + if var_x > 0 and var_y > 0: + slope = r_value * (var_y / var_x) ** 0.5 + y_at = lambda v: mean_y + slope * (v - mean_x) + s.append(f'') + + for row in pairs: + name, xv, yv = row[0], float(row[1]), float(row[2]) + s.append(f'{name}: {xv:.4g} vs {yv:.4g}') + + s.append(f'' + f'{second.get("trait_name", "b")}') + s.append(f'' + f'{first.get("trait_name", "a")}') + s.append(f'r = {r_value:+.4f}' if isinstance(r_value, (int, float)) else "") + s.append(f'n = {n}') + s.append(f'dashed: OLS') + s.append(f'from r and the means') + s.append("") + open(a.out, "w").write("\n".join(s) + "\n") + print(f"{a.out}: {n} points, r {r_value}") + + +if __name__ == "__main__": + main() diff --git a/src/config.rs b/src/config.rs index c6a1553..0061070 100644 --- a/src/config.rs +++ b/src/config.rs @@ -175,6 +175,8 @@ pub struct Config { pub pca_plotter: String, /// Script that draws the clustered heatmap of a correlation matrix (HEATMAP_PLOTTER). pub heatmap_plotter: String, + /// Script that draws the scatter plot of a two-trait comparison (COMPARE_PLOTTER). + pub compare_plotter: String, /// Directory holding BNW's worked example datasets (`BNW_EXAMPLES_DIR`), /// served by `/compute/bnw/examples`. Empty means the endpoint reports /// that no examples are configured. @@ -419,6 +421,10 @@ impl Config { "HEATMAP_PLOTTER".to_string(), "scripts/plot-heatmap.py".to_string(), ); + values.insert( + "COMPARE_PLOTTER".to_string(), + "scripts/plot-compare.py".to_string(), + ); // Per-user baskets: one SQLite file each (src/baskets.rs). Never // MariaDB -- a user's edited column is theirs. values.insert( @@ -487,6 +493,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -554,6 +561,7 @@ impl Config { bnw_plotter: values["BNW_PLOTTER"].clone(), pca_plotter: values["PCA_PLOTTER"].clone(), heatmap_plotter: values["HEATMAP_PLOTTER"].clone(), + compare_plotter: values["COMPARE_PLOTTER"].clone(), bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(), bulklmm_cmd: values["BULKLMM_CMD"].clone(), bulklmm_env: values["BULKLMM_ENV"].clone(), diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..c025c46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -231,6 +231,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) diff --git a/src/pca.rs b/src/pca.rs index 23e3105..e924882 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -55,6 +55,29 @@ pub struct Pca { /// Eigenvalues should sum to the number of traits; reported so a caller can /// check that the decomposition is sane rather than trust it. pub trace: f64, + /// The components *as traits*: one value per individual per component, so + /// they can be used the way GN2's "PCA traits" are -- correlated, mapped, + /// plotted, saved in a basket. Empty when the caller did not ask, or when + /// the values were not available to project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub traits: Vec, +} + +/// One principal component as a trait: a value per individual. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcTrait { + /// `PC1`, `PC2`, ... in eigenvalue order. + pub name: String, + /// Score per individual, in the same order as `individuals`. + pub values: Vec, + /// Share of total variance this component explains. + pub explained_variance_ratio: f64, +} + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcValue { + pub name: String, + pub value: f64, } #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] @@ -189,6 +212,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; } let small: Vec> = kept @@ -201,6 +225,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; }; let trace: f64 = eigenvalues.iter().sum(); @@ -221,7 +246,72 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: eigenvalues, dropped, trace, + traits: Vec::new(), + } +} + +/// Project standardised trait values onto the components, giving PC scores. +/// +/// `values` is traits x individuals for the traits the PCA kept, in the kept +/// order and already aligned to `individuals`; a trait is standardised with the +/// **sample** standard deviation (n-1), because that is what the correlation +/// matrix was built from -- using the population one would rescale every score +/// by a constant and quietly disagree with `r`. +/// +/// Returns one [`PcTrait`] per component. `None` when the shapes disagree or a +/// value is missing, rather than filling a zero into a score. +pub fn scores( + pca: &Pca, + values: &[Vec], + individuals: &[String], +) -> Option> { + let n_traits = values.len(); + if n_traits == 0 || individuals.len() != values[0].len() || values.iter().any(|v| v.len() != individuals.len()) { + return None; + } + if pca.components.len() < n_traits || pca.components[0].loadings.len() != n_traits { + return None; + } + let n = individuals.len(); + if n < 2 { + return None; + } + // z-scores per trait + let mut standardised: Vec> = Vec::with_capacity(n_traits); + for trait_values in values { + if trait_values.iter().any(|v| !v.is_finite()) { + return None; + } + let mean = trait_values.iter().sum::() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::() / (n - 1) as f64; + let sd = variance.sqrt(); + // A constant trait has no z-score; it also has no correlation with + // anything, so it should have been dropped before we get here. + if !(sd > 0.0) { + return None; + } + standardised.push(trait_values.iter().map(|v| (v - mean) / sd).collect()); + } + let mut out = Vec::with_capacity(pca.components.len()); + for (index, component) in pca.components.iter().enumerate() { + let mut scores = vec![0.0; n]; + for (trait_index, loading) in component.loadings.iter().enumerate() { + for (individual, z) in standardised[trait_index].iter().enumerate() { + scores[individual] += loading * z; + } + } + out.push(PcTrait { + name: format!("PC{}", index + 1), + values: individuals + .iter() + .cloned() + .zip(scores) + .map(|(name, value)| PcValue { name, value }) + .collect(), + explained_variance_ratio: component.explained_variance_ratio, + }); } + Some(out) } #[cfg(test)] diff --git a/src/routes/compare.rs b/src/routes/compare.rs new file mode 100644 index 0000000..9879b8a --- /dev/null +++ b/src/routes/compare.rs @@ -0,0 +1,290 @@ +//! Compare two traits: their shared individuals, the correlation, and a +//! scatter plot of one against the other. +//! +//! GN1's "compare traits" and GN2's trait page both show this, and every piece +//! of it already existed here -- `values_of` for the values, the engine for r +//! and p, the plot family for the figure. What was missing was one endpoint +//! that says "these two, over the individuals they share", with the individual +//! names in the reply so a reader can see which points they are looking at. +//! +//! Deliberate choices: +//! +//! * **The minimum overlap is the correlation floor** (6), not 2: two points +//! always fit a line, and a scatter of two points would look like a result. +//! * **The individuals travel with the numbers**, because a scatter plot is +//! read by looking at outliers, and "which animal is that" is the first +//! question. GN2's page answers it with a hover label; here it is in the +//! reply and in the plot's tooltips. +//! * **Nothing is regressed.** The line in the plot is drawn from r and the two +//! means (an ordinary least-squares line through standardised values), which +//! is the only slope implied by the numbers; no fitted model is invented. + +use axum::Json; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::correlation::{self, Method, Reference}; +use crate::error::ApiError; +use crate::error::Unauthorized; +use crate::response::{Ctx, Envelope}; + +use super::correlation::{db_failure, values_of, TraitRef}; +use crate::plot; +use gnauth_macros::gnauth; + +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct CompareRequest { + /// The first trait. + pub a: TraitRef, + /// The second trait. + pub b: TraitRef, + /// "pearson" (default) or "spearman". + #[serde(default)] + pub method: Option, +} + +#[utoipa::path(post, path = "/compute/compare", + summary = "Compare two traits: their shared individuals, r, p and n", + description = "Fetches both traits, keeps the individuals that have a value for both, and \ +returns the correlation over them together with the paired values -- so the reply is both the \ +statistic and the data a scatter plot is drawn from. Needs the same six paired observations the \ +rest of the correlation surface needs: two points always fit a line. `spearman` ranks the pairs \ +first, as everywhere else.", + request_body = CompareRequest, + responses( + (status = 200, description = "The comparison", body = Envelope), + Unauthorized, + (status = 422, description = "Unknown method, a trait with no values, or fewer than six shared individuals", body = ApiError), + (status = 500, description = "Internal error", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn compare( + ctx: Ctx, + _token: AuthToken, + Json(request): Json, +) -> Result>, ApiError> { + let rid = ctx.request_info(); + let fail = |code: &str, title: &str, detail: String| { + ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + code, + title, + detail, + "compare_traits", + ) + .with_request_id(rid.clone()) + }; + let method = Method::parse(request.method.as_deref().unwrap_or("pearson")) + .map_err(|detail| fail("invalid_method", "Invalid correlation method", detail))?; + + let wanted = request.clone(); + let computed = tokio::task::spawn_blocking(move || align(&request)) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compare_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|failure| failure.into_api(rid.clone()))?; + + let aligned = computed; + let n = aligned.pairs.len(); + if n < correlation::MIN_OVERLAP { + return Err(fail( + "too_few_shared", + "Too few shared individuals", + format!( + "these two traits share {n} individual(s) with values; a comparison needs at \ + least {}", + correlation::MIN_OVERLAP + ), + )); + } + let x: Vec = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec = aligned.pairs.iter().map(|(_, _, b)| *b).collect(); + let (r, p) = correlation::correlate_named_value(&x, &y, n, method).ok_or_else(|| { + fail( + "no_correlation", + "No correlation", + "the coefficient is not a number over these individuals \ + (a constant trait has no correlation with anything)" + .to_string(), + ) + })?; + + let rows = serde_json::Value::Array( + aligned + .pairs + .iter() + .map(|(individual, a, b)| serde_json::json!([individual, a, b])) + .collect(), + ); + let mut body = serde_json::json!({ + "a": {"dataset": wanted.a.dataset, "trait_name": wanted.a.trait_name}, + "b": {"dataset": wanted.b.dataset, "trait_name": wanted.b.trait_name}, + "method": method.as_str(), + "r": r, + "p": if p.is_finite() { serde_json::Value::from(p) } else { serde_json::Value::Null }, + "n": n, + "pairs": rows, + }); + if let Some(extra) = aligned.only_one_side { + body["only_one_side"] = serde_json::Value::from(extra); + } + Ok(Json( + ctx.envelope(body) + .with_columns( + vec!["individual".to_string(), "a".to_string(), "b".to_string()], + n, + ) + .with_note(&format!( + "{} ({}) against {} ({}), {} over the {n} individual(s) with a value for both.", + wanted.a.trait_name, wanted.a.dataset, wanted.b.trait_name, wanted.b.dataset, + method.as_str() + )) + .with_note( + "`pairs` is positional: individual, first trait's value, second trait's value. \ + The individuals that had a value for only one side are counted in \ + `only_one_side`.", + ) + .with_next("/plot/compare", "The same numbers as a scatter plot"), + )) +} + +#[utoipa::path(post, path = "/plot/compare", + summary = "Draw the scatter plot of two compared traits, as an SVG", + description = "Post the response of POST /compute/compare back (as-is) and get the figure \ +scripts/plot-compare.py draws from it: one point per individual that has both values, the \ +individual's name in each point's tooltip, and the least-squares line implied by r and the two \ +means. Nothing is refitted and nothing is recomputed. image/svg+xml, not the JSON envelope; \ +`x-plot-summary` carries the plotter's one-line summary.", + params(super::plot::PlotParams), + request_body = serde_json::Value, + responses( + (status = 200, description = "The SVG", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The posted body is not a comparison", body = ApiError), + (status = 502, description = "The plotter failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_compare( + ctx: Ctx, + _token: AuthToken, + axum::extract::Query(plot_params): axum::extract::Query, + Json(posted): Json, +) -> Result { + let rid = ctx.request_info(); + let data = posted.get("data").unwrap_or(&posted); + let pairs = data.get("pairs").and_then(|pairs| pairs.as_array()); + if pairs.map(|rows| rows.len()).unwrap_or(0) < 2 { + return Err(ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "not_a_comparison", + "Not a comparison", + "the posted body has fewer than two `pairs`: post a /compute/compare reply".to_string(), + "plot_compare", + ) + .with_request_id(rid)); + } + let config = crate::config::Config::load(); + let mut extra: Vec = Vec::new(); + if let Some(title) = plot_params.title.as_deref() { + extra.push("--title".to_string()); + extra.push(title.to_string()); + } + let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect(); + let rendered = plot::render( + &config.plot_python, + &config.compare_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &posted, + plot_params.trait_label.as_deref().unwrap_or(""), + &borrowed, + ) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::BAD_GATEWAY, + "plot_failed", + "The plotter failed", + error.to_string(), + "plot_compare", + ) + .with_request_id(rid) + })?; + Ok(super::plot::svg_response(rendered)) +} + +/// The aligned pairs, plus a count of individuals only one side had. +struct Aligned { + pairs: Vec<(String, f64, f64)>, + only_one_side: Option, +} + +fn align(request: &CompareRequest) -> Result { + let a = values_of(&request.a.dataset, &request.a.trait_name)?; + let b = values_of(&request.b.dataset, &request.b.trait_name)?; + let mut pairs = Vec::new(); + let mut only_one_side = 0usize; + for (index, name) in a.names.iter().enumerate() { + match b.names.iter().position(|candidate| candidate == name) { + Some(position) => pairs.push((name.clone(), a.values[index], b.values[position])), + None => only_one_side += 1, + } + } + // Individuals only in B are not visited by the loop above. + for name in &b.names { + if !a.names.contains(name) { + only_one_side += 1; + } + } + Ok(Aligned { + pairs, + only_one_side: if only_one_side > 0 { + Some(only_one_side) + } else { + None + }, + }) +} + +/// Keep `Reference` in scope for readers of `align`. +#[allow(dead_code)] +fn _reference_is_used(_: &Reference) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pairs_are_the_shared_individuals() { + let a = Reference::from_pairs(vec![ + ("s1".to_string(), Some(1.0)), + ("s2".to_string(), Some(2.0)), + ("s3".to_string(), Some(3.0)), + ]); + let b = Reference::from_pairs(vec![ + ("s2".to_string(), Some(20.0)), + ("s3".to_string(), Some(30.0)), + ("s4".to_string(), Some(40.0)), + ]); + let mut pairs = Vec::new(); + for (index, name) in a.names.iter().enumerate() { + if let Some(position) = b.names.iter().position(|candidate| candidate == name) { + pairs.push((name.clone(), a.values[index], b.values[position])); + } + } + assert_eq!(pairs, vec![ + ("s2".to_string(), 2.0, 20.0), + ("s3".to_string(), 3.0, 30.0), + ]); + } +} diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index 2a7f8a2..a3620f6 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -702,7 +702,7 @@ fn resolve_reference(request: &CorrelationRequest) -> Result Result { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result { let request = CorrelationRequest { dataset: dataset.to_string(), trait_name: trait_name.to_string(), diff --git a/src/routes/correlation_matrix.rs b/src/routes/correlation_matrix.rs index 9a433b6..9676cd4 100644 --- a/src/routes/correlation_matrix.rs +++ b/src/routes/correlation_matrix.rs @@ -167,7 +167,7 @@ pub async fn correlation_matrix( } let wanted = request.clone(); - let matrix = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) + let (matrix, references) = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) .await .map_err(|error| { ApiError::new( @@ -192,11 +192,22 @@ pub async fn correlation_matrix( } } let measured = measured / 2; - let pca = if wanted.pca.unwrap_or(false) { + let mut pca = if wanted.pca.unwrap_or(false) { Some(crate::pca::analyse(&matrix)) } else { None }; + // The components as *traits*: a PC is only usable (correlated, mapped, + // plotted, saved in a basket) if it has a value per individual, and that + // needs the values the matrix was built from -- which is why it happens + // here and not in pca::analyse. + if let Some(pca) = pca.as_mut() { + if let Some((values, individuals)) = kept_values_in_order(&references, pca) { + if let Some(traits) = crate::pca::scores(pca, &values, &individuals) { + pca.traits = traits; + } + } + } let mut body = serde_json::json!({ "traits": matrix.traits, "r": matrix.r, @@ -278,6 +289,64 @@ pub async fn correlation_matrix( )) } +/// The aligned values of the traits the PCA kept, over the individuals that +/// have a value for **every** kept trait. +/// +/// PCA of standardised traits is only defined on a complete rectangle, which is +/// the same rule that already dropped traits with a gap: a different individual +/// set per trait would make the scores incomparable across individuals. +fn kept_values_in_order( + references: &[Reference], + pca: &crate::pca::Pca, +) -> Option<(Vec>, Vec)> { + let components = pca.components.first()?; + let n_kept = components.loadings.len(); + if n_kept == 0 || n_kept > references.len() { + return None; + } + // The kept traits are the first n_kept that have values; the PCA was built + // from the matrix's own kept order, so take that same order. + let kept: Vec<&Reference> = references + .iter() + .filter(|reference| !reference.is_empty()) + .take(n_kept) + .collect(); + if kept.len() != n_kept { + return None; + } + let individuals: Vec = kept[0] + .names + .iter() + .filter(|name| { + kept.iter().all(|reference| { + reference + .names + .iter() + .position(|candidate| candidate == *name) + .map(|position| true) + .unwrap_or(false) + }) + }) + .cloned() + .collect(); + if individuals.len() < 3 { + return None; + } + let mut values: Vec> = Vec::with_capacity(n_kept); + for reference in &kept { + let mut row = Vec::with_capacity(individuals.len()); + for name in &individuals { + let position = reference + .names + .iter() + .position(|candidate| candidate == name)?; + row.push(reference.values[position]); + } + values.push(row); + } + Some((values, individuals)) +} + /// How many traits the request asked for. fn matrix_trait_count(matrix: &Matrix) -> usize { matrix.traits.len() @@ -299,9 +368,10 @@ fn build( request: &MatrixRequest, method: Method, min_overlap: usize, -) -> Result { +) -> Result<(Matrix, Vec), Failure> { let axis = matrix_axis(request)?; let references = resolve_traits(request, axis.as_deref())?; + let references_out = references.clone(); let count = references.len(); let mut r = vec![vec![None; count]; count]; @@ -343,7 +413,7 @@ fn build( } } - Ok(Matrix { + Ok((Matrix { traits: request .traits .iter() @@ -355,7 +425,7 @@ fn build( r, p, n, - }) + }, references_out)) } /// The individuals every trait is measured over: the first trait's group. diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0461165..0da2eaa 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod baskets; pub mod bnw; pub mod bulklmm; +pub mod compare; pub mod correlation; pub mod correlation_matrix; pub mod datasets; diff --git a/src/routes/plot.rs b/src/routes/plot.rs index 2b4c043..d33f5d7 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -346,7 +346,7 @@ pub async fn plot_gemma( } /// The SVG, with the plotter's summary alongside it. -fn svg_response(rendered: plot::Plot) -> Response { +pub(crate) fn svg_response(rendered: plot::Plot) -> Response { let mut response = rendered.svg.into_response(); let headers = response.headers_mut(); headers.insert( -- cgit 1.4.1 From 74a5c318163ab4c286e8b8e43bd645c1c4840605 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 18:44:13 +0000 Subject: make-mdb.sh: impute missing genotypes, because pangemma cannot represent them pangemma's mdb path has no missing-data handling -- mdb_calc_kin in src/gemma_io.cpp still carries the comment "[ ] handle missing data" -- and one NA poisons the whole matrix. Measured on BXD.8 (235 individuals, 21 056 markers, 0.1% missing): a store built straight from the BIMBAM gave a 235x235 matrix of -nan in 0.1 s with "**** INFO: Done." and exit 0; the same data with NAs replaced by each marker's mean gave a clean 235x235 matrix, and -lmm 9 on one chromosome then produced 1 452 markers matching GEMMA's on 1 171 of them. So the script imputes per marker (awk, one streaming pass, no Python needed) by default and --keep-missing turns that off for anyone who wants the raw store. NOT what GEMMA does, measured afterwards: GEMMA keeps the missing genotype and reports it (n_miss=1 in its .assoc.txt) while analysing one individual fewer for that marker -- 286 of 1452 markers on chromosome 1 carry a missing value, and their p-values differ from the imputed run (0.732 against 0.698 for rsm10000000731) because n goes 235 -> 234. So imputation is a deliberate deviation the mdb path forces, not a reproduction of the direct path: on the 286 markers with a missing genotype, pangemma+mdb and gemma+BIMBAM are answering slightly different questions, and the endpoint has to say so. Also measured while checking: a File input is what ravanan hashes, and the store's LMDB lock is a sibling (.mdb-lock), not a file inside it -- the .mdb's sha1 is identical before and after a read while the lock's bytes change on every open. So deleting the lock after writing gives a stable identity and the lock that comes back when a reader opens the store costs nothing. --- scripts/make-mdb.sh | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh index ea58fc6..b5fd3df 100755 --- a/scripts/make-mdb.sh +++ b/scripts/make-mdb.sh @@ -24,17 +24,22 @@ # rename when whole. # # scripts/make-mdb.sh --geno --snps \ -# [--eval Gf|Gb|G0_1|G0_2] [--name NAME] [--out DIR] +# [--eval Gf|Gb|G0_1|G0_2] [--name NAME] [--out DIR] \ +# [--keep-missing] +# +# Missing genotypes are imputed to the marker's mean by default, because +# pangemma's mdb path cannot represent them: see the note further down. # # Prints the directory it built. Exit 2 on bad arguments, 1 on a maker failure. set -eu -geno= snps= eval_=Gf name= out=. +geno= snps= eval_=Gf name= out=. keep_missing=no while [ $# -gt 0 ]; do case $1 in --geno) geno=$2; shift 2 ;; --snps) snps=$2; shift 2 ;; --eval) eval_=$2; shift 2 ;; + --keep-missing) keep_missing=yes; shift ;; --name) name=$2; shift 2 ;; --out) out=$2; shift 2 ;; -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; @@ -72,11 +77,30 @@ ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" "$ANNO" "$work/snps.txt" >/dev/null 2>&1 || { echo "make-mdb.sh: anno2mdb.rb failed" >&2; exit 1; } -# 2. the genotypes, translated the way pangemma expects +# 2. missing genotypes. pangemma's mdb path has NO missing-data handling +# (src/gemma_io.cpp's mdb_calc_kin still carries the "[ ] handle missing +# data" TODO), and one NA poisons every cell: measured, a BIMBAM with 0.1% +# NAs gave a 235x235 matrix of -nan while the same data imputed gave a clean +# one, with "**** INFO: Done." and exit 0 either way. So NAs are replaced +# per marker by that marker's mean -- which is what GEMMA does to a BIMBAM +# before it looks at it -- unless --keep-missing asks otherwise. +if [ "$keep_missing" = no ]; then + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$work/geno.txt" > "$work/geno-imputed.txt" + mv "$work/geno-imputed.txt" "$work/geno.txt" +fi + +# 3. the genotypes, translated the way pangemma expects "$GENO" --eval "$eval_" --anno "$work/snps.txt.mdb" "$work/geno.txt" >/dev/null 2>&1 || { echo "make-mdb.sh: geno2mdb.rb failed" >&2; exit 1; } -# 3. the lock file. These environments are single files (MDB_NOSUBDIR), so the +# 4. the lock file. These environments are single files (MDB_NOSUBDIR), so the # lock is a *sibling*, .mdb-lock -- measured on a real store: every # open recreates it with different bytes while the .mdb itself never changes. # The .mdb is what gets interned and hashed (a File input hashes its -- cgit 1.4.1 From c9777828482d03affc912688bed316f1a16c5640 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 20:00:23 +0000 Subject: listing: keep the mechanical first pass alongside the model scripts/wire-listing.py is the first, mechanical pass at the listing change: it rewrites the handlers by hand so the shape of the work is visible before the model in src/listing.rs takes over. Kept rather than deleted, because the two are meant to be read together. (This commit was originally part of a larger one; splitting it so the message matches what it contains.) --- scripts/wire-listing.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100755 scripts/wire-listing.py (limited to 'scripts') diff --git a/scripts/wire-listing.py b/scripts/wire-listing.py new file mode 100755 index 0000000..3170106 --- /dev/null +++ b/scripts/wire-listing.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# Mechanical first pass at wiring src/listing.rs into the six listing handlers. +# It changed 3 of 6 (groups, group_strains, group_traits) before the return-type +# rewrite needed hand care; see the module docs in src/listing.rs for the plan. +"""Wire the listing shape into the six listing handlers, mechanically. + +Per handler: add the three query fields, change the utoipa `body =` type and +the return type to Envelope, and shape the rows where the +envelope is built. +""" +import re, sys + +def field_block(indent): + i = ' ' * indent + return (f"\n{i}/// Keep only these ids or names, comma-separated.\n{i}#[serde(default)]\n{i}pub limit_to: Option,\n" + f"{i}/// Answer with one id per row instead of objects.\n{i}#[serde(default)]\n{i}pub ids_only: Option,\n" + f"{i}/// Answer with one name per row instead of objects.\n{i}#[serde(default)]\n{i}pub names_only: Option,\n") + +def shape(rows_expr, ind, params_name='params'): + i = ' ' * ind + return (f"let listing = crate::listing::Listing::parse(&crate::listing::ListingParams {{\n" + f"{i} limit_to: {params_name}.limit_to.clone(),\n" + f"{i} ids_only: {params_name}.ids_only,\n" + f"{i} names_only: {params_name}.names_only,\n" + f"{i}}})\n" + f"{i}.map_err(|detail| crate::listing::refuse(detail, &listing_rid, \"{op}\"))?;\n" + f"{i}let rows = serde_json::to_value({rows_expr}).unwrap_or(serde_json::Value::Null);\n" + f"{i}let (shaped, missing) = listing.apply(&rows, {params_name}.limit_to.as_deref());\n") + +handlers = [ + # file, handler fn, struct to extend, params type name, rows variable, operation id + ('src/routes/groups.rs', 'groups', 'GroupsParams', 'groups', 'groups'), + ('src/routes/groups.rs', 'group_strains', 'GroupStrainsParams', 'strains', 'group_strains'), + ('src/routes/groups.rs', 'group_datasets', 'GroupDatasetsParams', 'datasets', 'group_datasets'), + ('src/routes/groups.rs', 'group_traits', 'GroupTraitsParams', 'traits', 'group_traits'), + ('src/routes/datasets.rs', 'dataset_probesets', 'DatasetProbesetsParams', 'probesets', 'dataset_probesets'), + ('src/routes/traits.rs', 'traits', 'TraitsParams', 'traits', 'dataset_traits'), +] +status = [] +for path, handler, params, rows_var, op in handlers: + s = open(path).read() + before = s + # 1. add the fields to the params struct + m = re.search(r'pub struct %s \{(.*?)\n\}' % params, s, re.S) + if not m: + status.append(f'{handler}: params struct {params} NOT FOUND') + continue + if 'pub limit_to' not in m.group(0): + s = s.replace(m.group(0), m.group(0)[:-2] + field_block(4) + '}', 1) + # 2. body= type in the handler's utoipa block (the one nearest above the fn) + idx = s.index('pub async fn %s(' % handler) + head = s[:idx] + cut = head.rfind('body = Envelope', cut) + 1 + s = head[:cut] + 'body = Envelope' + head[end:] + s[idx:] + # 3. return type + s = re.sub(r'(pub async fn %s\([^)]*?\) -> Result]*>>, ApiError>)' % handler, + lambda mm: mm.group(1).replace('Envelope[').split('Envelope[')[0] + + 'Envelope>, ApiError>', s, count=1, flags=re.S) + open(path, 'w').write(s) + status.append(f'{handler}: {"changed" if s != before else "UNCHANGED"}') +print('\n'.join(status)) -- cgit 1.4.1 From 94d08ecb58619ae60f048059f24536cac1f1e6e0 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 20:00:23 +0000 Subject: make-mdb.sh: HMM genotypes from qtl2, for the pangemma path The pangemma endpoint is to agree with R/qtl2, not with GEMMA, so the store's genotypes now come from qtl2's HMM rather than from a marker mean: maxmarg on the genotype probabilities /compute/qtl2 already computes and caches, at minprob 0 so every cell is called. GEMMA's own endpoints are untouched. scripts/make-mdb.sh --impute qtl2 --cross --probs writes a BIMBAM from the HMM's calls (marker, X, Y, genotypes -- the annotation mdb carries the positions, as the makers expect), the snps file from the cross's physical map, and then the store as before: lock file deleted, .mdb made read-only, renamed into place. Measured on BXD.8: 7 s for the HMM over 20 453 markers x 235 individuals, 4.7 s for geno2mdb, 28.9 MB as Gf, no gaps left. Three things found while wiring it, each now handled: * maxmarg returns individuals x markers -- the transpose of a BIMBAM -- and a first version wrote 4 465 lines with individuals where markers belong; * both makers name their output after their argument and write it in the current directory, so they now run inside the work directory with bare names. A hand run with absolute paths had put a 2 MB .mdb inside gn4-data; * pangemma's startup smoke test wants the working directory to be its own source root. Run from anywhere else it exits in 0.03 s having done nothing, which looks like a very fast scan rather than a failure. Comparison, three BXD traits, 20 451 markers, each engine with its own kinship matrix, positional phenotype in the cross's individual order: trait same top marker Spearman rho top-50 overlap median |d(-log10 p)| 10001 yes (rs27829136) 0.99732 48/50 0.008 16627 yes (rs29388476) 0.98415 43/50 0.029 16769 yes (rs29388476) 0.98339 32/50 0.029 K 0.13 s against gemma's 0.84 s; the LMM scan 2.5 s against 3.0 s. --- scripts/make-mdb.sh | 73 ++++++++++++++++++++++++++++++++------------ scripts/qtl2-impute-bimbam.R | 72 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 20 deletions(-) create mode 100755 scripts/qtl2-impute-bimbam.R (limited to 'scripts') diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh index b5fd3df..e5b753e 100755 --- a/scripts/make-mdb.sh +++ b/scripts/make-mdb.sh @@ -33,23 +33,29 @@ # Prints the directory it built. Exit 2 on bad arguments, 1 on a maker failure. set -eu -geno= snps= eval_=Gf name= out=. keep_missing=no +geno= snps= eval_=Gf name= out=. keep_missing=no impute= cross_dir= probs_rds= while [ $# -gt 0 ]; do case $1 in --geno) geno=$2; shift 2 ;; --snps) snps=$2; shift 2 ;; --eval) eval_=$2; shift 2 ;; --keep-missing) keep_missing=yes; shift ;; + --impute) impute=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs_rds=$2; shift 2 ;; --name) name=$2; shift 2 ;; --out) out=$2; shift 2 ;; -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "make-mdb.sh: unknown argument $1" >&2; exit 2 ;; esac done -[ -n "$geno" ] && [ -n "$snps" ] || { echo "make-mdb.sh: --geno and --snps are required" >&2; exit 2; } -for f in "$geno" "$snps"; do - [ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; } -done +if [ "$impute" != qtl2 ]; then + [ -n "$geno" ] && [ -n "$snps" ] || + { echo "make-mdb.sh: --geno and --snps are required (or --impute qtl2)" >&2; exit 2; } + for f in "$geno" "$snps"; do + [ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; } + done +fi case $eval_ in Gf|Gb|G0_1|G0_2) ;; *) echo "make-mdb.sh: unknown --eval $eval_" >&2; exit 2 ;; esac # The makers, and something to run them with. MAKE_MDB_ANNO / MAKE_MDB_GENO @@ -66,25 +72,51 @@ mkdir -p "$out" work=$(mktemp -d "$out/.$name.XXXXXX") trap 'rm -rf "$work"' EXIT -# The makers write .mdb *beside their input* and take it as a -# positional argument, so they get links to work on: nothing is written next to -# the caller's files. -ln -s "$(cd "$(dirname "$geno")" && pwd)/$(basename "$geno")" "$work/geno.txt" -ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" +# 1. Where do the genotypes come from? With --impute qtl2 they come from +# R/qtl2's HMM (maxmarg on the cached genotype probabilities), which is the +# genotype set /compute/qtl2 maps on -- complete by construction, and +# predicted from flanking markers rather than averaged. That replaces both +# the BIMBAM and the snps file, so --geno/--snps are then optional. +if [ "$impute" = qtl2 ]; then + [ -n "$cross_dir" ] && [ -n "$probs_rds" ] || + { echo "make-mdb.sh: --impute qtl2 needs --cross DIR and --probs FILE.rds" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "make-mdb.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + "$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + "$cross_dir" "$probs_rds" "$work/hmm" "${IMPUTE_MINPROB:-0}" >/dev/null 2>&1 || + { echo "make-mdb.sh: qtl2 HMM imputation failed" >&2; exit 1; } + geno=$work/hmm.bimbam.txt + snps=$work/hmm.snps.txt + [ -n "$name" ] || name=$(basename "$cross_dir") +else + # The makers write .mdb *beside their input* and take it as a + # positional argument, so they get links to work on: nothing is written + # next to the caller's files. + ln -s "$(cd "$(dirname "$geno")" && pwd)/$(basename "$geno")" "$work/geno.txt" + ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" + geno=$work/geno.txt + snps=$work/snps.txt +fi -# 1. the annotation half. It is an intermediate: pangemma is given the snps +# 2. the annotation half. It is an intermediate: pangemma is given the snps # file itself (-a) and only geno2mdb needs this database, so it is not kept. -"$ANNO" "$work/snps.txt" >/dev/null 2>&1 || +# Both makers name their output after the *argument they were given* and write +# it in the current directory, so they run inside the work directory with bare +# names: an absolute path would put the .mdb beside the caller's inputs (measured: +# a hand run left a 2 MB .mdb inside gn4-data). +( cd "$work" && "$ANNO" "$(basename "$snps")" ) >/dev/null 2>&1 || { echo "make-mdb.sh: anno2mdb.rb failed" >&2; exit 1; } +anno_db=$work/$(basename "$snps").mdb -# 2. missing genotypes. pangemma's mdb path has NO missing-data handling +# 2. missing genotypes (only for raw input: the HMM output has no gaps). pangemma's mdb path has NO missing-data handling # (src/gemma_io.cpp's mdb_calc_kin still carries the "[ ] handle missing # data" TODO), and one NA poisons every cell: measured, a BIMBAM with 0.1% # NAs gave a 235x235 matrix of -nan while the same data imputed gave a clean # one, with "**** INFO: Done." and exit 0 either way. So NAs are replaced # per marker by that marker's mean -- which is what GEMMA does to a BIMBAM # before it looks at it -- unless --keep-missing asks otherwise. -if [ "$keep_missing" = no ]; then +if [ "$keep_missing" = no ] && [ "$impute" != qtl2 ]; then awk -F, 'BEGIN { OFS = "," } { sum = 0; n = 0 @@ -92,13 +124,14 @@ if [ "$keep_missing" = no ]; then mean = (n ? sum / n : 0) for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) print - }' "$work/geno.txt" > "$work/geno-imputed.txt" - mv "$work/geno-imputed.txt" "$work/geno.txt" + }' "$geno" > "$work/geno-imputed.txt" + mv "$work/geno-imputed.txt" "$geno" fi # 3. the genotypes, translated the way pangemma expects -"$GENO" --eval "$eval_" --anno "$work/snps.txt.mdb" "$work/geno.txt" >/dev/null 2>&1 || +( cd "$work" && "$GENO" --eval "$eval_" --anno "$(basename "$snps").mdb" "$(basename "$geno")" ) >/dev/null 2>&1 || { echo "make-mdb.sh: geno2mdb.rb failed" >&2; exit 1; } +store=$work/$(basename "$geno").mdb # 4. the lock file. These environments are single files (MDB_NOSUBDIR), so the # lock is a *sibling*, .mdb-lock -- measured on a real store: every @@ -106,11 +139,11 @@ fi # The .mdb is what gets interned and hashed (a File input hashes its # content), so the lock only needs to go so the directory we hand out # contains nothing but the store itself. -rm -f "$work/geno.txt.mdb-lock" "$work/snps.txt.mdb-lock" -chmod a-w "$work/geno.txt.mdb" +rm -f "$store-lock" "$anno_db-lock" +chmod a-w "$store" rm -f "$out/$name.geno.mdb" "$out/$name.geno.mdb-lock" -mv "$work/geno.txt.mdb" "$out/$name.geno.mdb" +mv "$store" "$out/$name.geno.mdb" trap 'rm -rf "$work"' EXIT rm -rf "$work" trap - EXIT diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R new file mode 100755 index 0000000..1a9cd1b --- /dev/null +++ b/scripts/qtl2-impute-bimbam.R @@ -0,0 +1,72 @@ +#!/usr/bin/env Rscript +# qtl2-impute-bimbam.R -- write a BIMBAM genotype file from qtl2's HMM, so that +# pangemma's mdb can be built from the same genotype calls /compute/qtl2 uses. +# +# Why this exists: pangemma's LMDB path cannot represent a missing genotype +# (one NA makes the whole kinship matrix NaN, silently), while the BIMBAM the +# GEMMA path uses carries 0.1% unknown calls and the riself conversion used by +# R/qtl2 drops 12.7% (every heterozygous call). Filling those with a marker +# mean would be inventing data where there is a real prediction to be had, so +# the calls come from qtl2's HMM instead: `maxmarg` on the cached genotype +# probabilities, which predicts a missing call from its flanking markers. +# +# qtl2-impute-bimbam.R [minprob] +# +# writes .bimbam.txt (marker, X, Y, genotypes -- positions come from +# the annotation database, as the makers expect) and .snps.txt +# (marker, pos, chr, the order anno2mdb.rb parses). Autosomes only: the qtl2 +# cross this reads has no X, which is the same limit /compute/qtl2 has. + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +if (length(args) < 3) { + stop("usage: qtl2-impute-bimbam.R [minprob]", + call. = FALSE) +} +cross_dir <- args[1]; probs_path <- args[2]; out_prefix <- args[3] +minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 + +setwd(cross_dir) +cross <- read_cross2("control.json") +probs <- readRDS(probs_path) + +# maxmarg returns one call per marker and individual, at the highest +# probability above MINPROB -- or NA when the HMM is less sure than that. At +# minprob 0 every cell is filled, which is what the mdb needs. +imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1)) + +# How much work the HMM did: cells the cross itself had as missing (a 0 in an +# explicit genotype map, never NA -- see read_cross2's own convention). +missing <- sum(vapply(cross$geno, function(g) sum(g == 0 | is.na(g)), integer(1))) +filled <- sum(is.na(vapply(cross$geno, function(g) sum(is.na(g)), integer(1)))) +left <- sum(vapply(imputed, function(g) sum(is.na(g)), integer(1))) + +# The calls come back as genotype *codes* in qtl2's numeric convention for this +# cross (A = 1, B = 3, H = 2 per control.json); pangemma wants 0/1/2. +codes <- c(`1` = 0, `2` = 1, `3` = 2) +rows <- list(); snps <- list() +# maxmarg returns individuals x markers (rows are individuals, which is the +# opposite of the BIMBAM's marker-per-line shape, and the reason a first version +# of this wrote 4 465 lines naming individuals as markers). +for (chr_name in names(imputed)) { + calls <- imputed[[chr_name]] + markers <- colnames(calls) + # pmap (base pairs) when the cross has one: it is what the annotation lookup + # and the plot positions want, exactly as /compute/qtl2 reports them. + positions <- (if (!is.null(cross$pmap)) cross$pmap else cross$gmap)[[chr_name]][markers] + for (marker in markers) { + row <- codes[as.character(calls[, marker])] + if (any(is.na(row))) next # a cell the HMM could not call + rows[[length(rows) + 1]] <- c(marker, "X", "Y", as.character(row)) + snps[[length(snps) + 1]] <- c(marker, as.character(round(positions[[marker]])), chr_name) + } +} + +writeLines(vapply(rows, paste, character(1), collapse = ","), + paste0(out_prefix, ".bimbam.txt")) +writeLines(vapply(snps, paste, character(1), collapse = ","), + paste0(out_prefix, ".snps.txt")) + +cat(sprintf("hmm: %d markers, %d individuals, minprob %g, %d cells uncertain, %d written to %s.bimbam.txt\n", + length(rows), nrow(imputed[[1]]), minprob, left, length(rows), out_prefix)) -- cgit 1.4.1 From 7f6d92b546892ea5dba5a3f5df541c77c229f1e4 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 20:20:20 +0000 Subject: impute: one switch for how a missing genotype is treated, on the ravanan path "How do we treat a missing genotype?" now has one answer shared by every engine, so the same trait can be mapped both ways and the results compared: none the file as it stands -- GEMMA does complete-case per marker and reports n_miss (235 individuals for some markers, 234 for others) mean every gap takes that marker's mean (complete file, all individuals) hmm R/qtl2's HMM predicts the gap from flanking markers (maxmarg on the genotype probabilities, the calls /compute/qtl2 itself maps on) scripts/prepare-genotypes.sh is that one place. It writes .bimbam.txt and .snps.txt and nothing else, so the two engines consume the same files: /compute/gemma/ravanan takes `impute`, and the pangemma store builder (the next endpoint) takes the same script with --mode mean|hmm into the LMDB makers. On the ravanan path the files are cached under RAVANAN_CACHE_DIR/imputed/ -, so a second request for the same panel and treatment costs nothing: mean is a single pass (1.7 s for BXD.8), hmm is the qtl2 HMM (10 s including computing the probabilities the first time, then cached beside the cross). The reply says which treatment ran, and `hmm` refuses without a group (422 impute_needs_group) since the cross it predicts from is the group's. Measured, BXD.8 (20 453 markers, 235 individuals), missing calls in the prepared panel: 1 465 of 4.8M as NA. Both modes produce complete files of 9.2 and 10.0 MB, and a request with impute=mean or impute=hmm writes them and then proceeds to ravanan. What this box could not finish is the run itself: ravanan in the scratch instance failed on its own manifest cache ("manifest.scm newer than compiled ... warning") and, for hmm, answered "no association output files" -- environment, not the preparation, and the next thing to settle. Why not keep it in the workflow: the treatment has to be the same for both engines, and pangemma's store builder needs the file *before* the workflow exists (it builds an LMDB store from it). One script, two consumers. --- scripts/prepare-genotypes.sh | 77 +++++++++++++ scripts/qtl2-impute-bimbam.R | 19 +++- src/config.rs | 10 ++ src/routes/gemma.rs | 252 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 355 insertions(+), 3 deletions(-) create mode 100755 scripts/prepare-genotypes.sh (limited to 'scripts') diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh new file mode 100755 index 0000000..36a959b --- /dev/null +++ b/scripts/prepare-genotypes.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# prepare-genotypes.sh -- one place where "how do we treat a missing genotype?" +# is decided, so the same question can be asked of every engine and the answers +# compared. +# +# --mode none leave the file as it is (GEMMA then does complete-case per +# marker and reports n_miss; pangemma cannot represent a gap at +# all, so its store builder refuses this mode) +# --mode mean replace each missing call by that marker's mean over the +# individuals that have one (cheap, but it invents a datum and +# deflates the variance) +# --mode hmm predict the missing calls from flanking markers with R/qtl2's +# HMM (maxmarg on genotype probabilities) -- the genotype set +# /compute/qtl2 maps on, and the one that does not invent a value +# +# scripts/prepare-genotypes.sh --mode mean|hmm|none \ +# --geno --snps --out \ +# [--cross ] [--probs ] [--minprob N] +# +# Writes .bimbam.txt and .snps.txt and prints the prefix. +# Exits 2 on bad arguments, 1 when a step fails. +set -eu + +mode= geno= snps= out= cross_dir= probs= minprob=0 +while [ $# -gt 0 ]; do + case $1 in + --mode) mode=$2; shift 2 ;; + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs=$2; shift 2 ;; + --minprob) minprob=$2; shift 2 ;; + -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; + esac +done + +case $mode in none|mean|hmm) ;; *) echo "prepare-genotypes.sh: --mode must be none, mean or hmm" >&2; exit 2 ;; esac +[ -n "$out" ] || { echo "prepare-genotypes.sh: --out is required" >&2; exit 2; } +mkdir -p "$(dirname "$out")" + +case $mode in +none) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + cp "$geno" "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +mean) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +hmm) + [ -n "$cross_dir" ] || { echo "prepare-genotypes.sh: --mode hmm needs --cross DIR" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + # R's own complaint last, so a caller that reports the final stderr line + # reports the cause rather than our wrapper sentence. + if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + "$cross_dir" "${probs:--}" "$out" "$minprob" 2>&1); then + echo "prepare-genotypes.sh: HMM imputation failed:" >&2 + printf '%s\n' "$r_output" | tail -6 >&2 + exit 1 + fi + ;; +esac + +printf '%s\n' "$out" diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 1a9cd1b..4003f4e 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -29,7 +29,24 @@ minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 setwd(cross_dir) cross <- read_cross2("control.json") -probs <- readRDS(probs_path) + +# Passing "-" as the probabilities means "compute them": a caller that only has +# the converted cross (the GEMMA path has no qtl2 scan to borrow a cache entry +# from) should not have to run /compute/qtl2 first just to get genotypes. The +# result is cached in the cross directory, which is itself content-keyed, so a +# second call is free. +probs <- if (identical(probs_path, "-")) { + cached <- "probs-imputed.rds" + if (file.exists(cached)) { + readRDS(cached) + } else { + p <- calc_genoprob(cross, error_prob = 0.002, cores = 1, quiet = TRUE) + saveRDS(p, cached) + p + } +} else { + readRDS(probs_path) +} # maxmarg returns one call per marker and individual, at the highest # probability above MINPROB -- or NA when the HMM is less sure than that. At diff --git a/src/config.rs b/src/config.rs index 0061070..b937ce5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -126,6 +126,9 @@ pub struct Config { /// `ravanan_cache_dir` when the backend is slurm. Empty means "do /// not pass --scratch" (single-machine's own default). pub ravanan_scratch: String, + /// The script that materialises a genotype file for a given + /// missing-data treatment (`PREPARE_GENOTYPES`). + pub prepare_genotypes: String, /// Path to scripts/rqtl_wrapper.R (copied here from GeneNetwork3) /// for POST /compute/rqtl. Defaults to that path relative to the /// working directory the server is started from. @@ -315,6 +318,12 @@ impl Config { "RAVANAN_BATCH_SYSTEM".to_string(), "single-machine".to_string(), ); + // The one place where "how is a missing genotype treated?" is decided + // (`scripts/prepare-genotypes.sh`): mode none, mean or hmm. + values.insert( + "PREPARE_GENOTYPES".to_string(), + "scripts/prepare-genotypes.sh".to_string(), + ); // Only read when RAVANAN_BATCH_SYSTEM=slurm-api; left blank so // the single-machine default stays a zero-configuration path. values.insert("RAVANAN_SLURM_API_ENDPOINT".to_string(), String::new()); @@ -545,6 +554,7 @@ impl Config { ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), + prepare_genotypes: values["PREPARE_GENOTYPES"].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(), diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index a17010b..8c2c543 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -22,6 +22,7 @@ use crate::compute_gate; use crate::covariates; use crate::error::{ApiError, Unauthorized}; use crate::genotypes; +use crate::qtl2; use crate::gemma::{self, GemmaError}; use crate::response::{Ctx, Envelope, RequestInfo, path_segment}; use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; @@ -119,6 +120,16 @@ pub struct GemmaRequest { pub permutations: Option, /// Refused unless 0, as `nperm`. pub permutate: Option, + + /// How a missing genotype is treated, for the ravanan path: `none` + /// (default -- the file is used as it stands, so GEMMA does complete-case + /// per marker and reports `n_miss`), `mean` (each gap takes that marker's + /// mean) or `hmm` (R/qtl2's HMM predicts it from flanking markers). The + /// last two produce a complete genotype file, which is what a comparison + /// between engines needs: pangemma's LMDB store cannot hold a gap at all. + /// `hmm` needs a group-scoped request, since the cross it predicts from is + /// the group's. + pub impute: Option, } /// One trait value, by individual name. @@ -908,6 +919,200 @@ pub async fn compute_gemma( }) } + +/// A genotype file materialised for one missing-data treatment. +struct PreparedGenotypes { + genotype_file: String, + snps_file: String, + notes: Vec, +} + +/// Run `scripts/prepare-genotypes.sh` to turn the resolved genotype file into +/// the one the caller asked for (`mean` or `hmm`). +/// +/// Both modes write a *complete* file beside the ravanan cache, keyed by the +/// panel and the mode, so a second request for the same panel and treatment +/// reuses it: `mean` costs a pass over the file, `hmm` costs the qtl2 HMM +/// (about ten seconds for BXD.8 on one core, then cached). +async fn prepare_genotypes( + config: &Config, + mode: &str, + genotype_file: &str, + snps_file: &str, + group: &Option, + version: Option<&str>, + rid: RequestInfo, +) -> Result { + let stem = std::path::Path::new(genotype_file) + .file_stem() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "panel".to_string()); + let prefix = std::path::Path::new(&config.ravanan_cache_dir) + .join("imputed") + .join(format!("{stem}-{mode}")); + let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); + let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); + + let mut notes = Vec::new(); + if std::path::Path::new(&prepared_geno).is_file() + && std::path::Path::new(&prepared_snps).is_file() + { + notes.push(format!( + "genotypes: '{mode}' treatment reused from the cache ({})", + prepared_geno + )); + return Ok(PreparedGenotypes { + genotype_file: prepared_geno, + snps_file: prepared_snps, + notes, + }); + } + + // hmm predicts from the group's qtl2 cross: the same conversion and the + // same cache /compute/qtl2 uses, so the calls are the ones that endpoint + // maps on, and the probabilities are computed once and kept beside the + // cross. + let cross_dir = if mode == "hmm" { + let Some(group) = group.clone() else { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_group", + "hmm imputation needs a group", + "the HMM predicts a missing call from flanking markers in a converted \ + cross, and a cross is built from a group; send `group` (with \ + `genotype_version` if you want a particular version), or use \ + impute=mean." + .to_string(), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + }; + let directory = config.genotype_files_dir.clone(); + let cache = config.qtl2_cache_dir.clone(); + let version = version.map(|v| v.to_string()); + let prepared = tokio::task::spawn_blocking(move || { + let resolved = genotypes::resolve( + std::path::Path::new(&directory), + &group, + version.as_deref(), + ) + .map_err(|error| error.to_string())?; + // Drop is the default genotype model: the heterozygous calls a + // riset panel carries are exactly the ones the HMM is asked to + // re-predict, so predicting from the kept calls would be circular. + qtl2::prepare_cross(&resolved, std::path::Path::new(&cache), qtl2::Het::Drop) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cross", + format!("preparing the qtl2 cross failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "cross_preparation_failed", + "Could not prepare the cross", + format!("{error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })?; + prepared + .control + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)) + } else { + std::path::PathBuf::new() + }; + + let script = config.prepare_genotypes.clone(); + let script_for_job = script.clone(); + let geno = genotype_file.to_string(); + let snps = snps_file.to_string(); + let out = prefix.to_string_lossy().into_owned(); + let mode_owned = mode.to_string(); + let status = tokio::task::spawn_blocking(move || { + let mut args: Vec = vec![ + "--mode".to_string(), + mode_owned, + "--out".to_string(), + out, + ]; + if !geno.is_empty() { + args.push("--geno".to_string()); + args.push(geno); + args.push("--snps".to_string()); + args.push(snps); + } + if !cross_dir.as_os_str().is_empty() { + args.push("--cross".to_string()); + args.push(cross_dir.to_string_lossy().into_owned()); + args.push("--probs".to_string()); + args.push("-".to_string()); + } + std::process::Command::new(&script_for_job).args(&args).output() + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare genotypes", + format!("running {script} failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "prepare_genotypes_failed", + "Could not prepare genotypes", + format!("could not run {}: {error}", config.prepare_genotypes), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })?; + if !status.status.success() { + return Err(ApiError::new( + StatusCode::BAD_GATEWAY, + "prepare_genotypes_failed", + "Could not prepare genotypes", + format!( + "{} --mode {mode} failed: {}", + config.prepare_genotypes, + String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("no message") + ), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + + notes.push(match mode { + "mean" => "genotypes: missing calls replaced by each marker's mean (a complete \ + file, so every individual is analysed; GEMMA's own treatment is \ + complete-case per marker, which this replaces)" + .to_string(), + _ => "genotypes: missing calls predicted by R/qtl2's HMM (maxmarg on the \ + group's cached genotype probabilities, the same calls /compute/qtl2 \ + maps on)" + .to_string(), + }); + Ok(PreparedGenotypes { + genotype_file: prepared_geno, + snps_file: prepared_snps, + notes, + }) +} + #[utoipa::path(post, path = "/compute/gemma/ravanan", summary = "Map a QTL with GEMMA, run via ravanan instead of gemma-wrapper directly", description = "Same computation and request/response shape as POST \ @@ -982,7 +1187,7 @@ pub async fn compute_gemma_ravanan( trait_values, individuals: panel_individuals, names: _, - group: _, + group: resolved_group, notes: input_notes, } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() { @@ -1027,6 +1232,45 @@ pub async fn compute_gemma_ravanan( .with_request_id(rid)); } + // Genotypes as the caller asked for them: `impute` decides what happens to + // a missing call, and both non-default answers produce a complete file. + // Doing it here rather than inside the workflow keeps one implementation + // (`scripts/prepare-genotypes.sh`) for every engine, which is the point -- + // the same trait can then be mapped with `mean` and with `hmm` and the two + // answers compared. + let impute = request + .impute + .clone() + .unwrap_or_else(|| "none".to_string()) + .to_ascii_lowercase(); + if !matches!(impute.as_str(), "none" | "mean" | "hmm") { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_impute", + "Invalid impute mode", + format!("'{}' is not a mode; use none, mean or hmm.", impute), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + let mut impute_notes: Vec = Vec::new(); + let (genotype_file, snps_file) = if impute == "none" { + (genotype_file, snps_file) + } else { + let prepared = prepare_genotypes( + &config, + &impute, + &genotype_file, + &snps_file, + &Some(resolved_group.clone()), + request.genotype_version.as_deref(), + rid.clone(), + ) + .await?; + impute_notes = prepared.notes; + (prepared.genotype_file, prepared.snps_file) + }; + // Gated like the direct GEMMA run and by the same size rule, now with the // real panel size: a samples-only request used to be sized 0 and took no // slot at all. @@ -1075,10 +1319,14 @@ pub async fn compute_gemma_ravanan( "Rows come from GEMMA's own .assoc.txt output, positional (see meta.columns for names); column names depend on the lmm value used.", ); // What the request resolved to first (which genotype version, how many - // values aligned, what was dropped), then the run's own notes. + // values aligned, what was dropped), how the genotypes were treated if + // the caller asked for imputation, then the run's own notes. for note in &input_notes { envelope = envelope.with_note(note); } + for note in &impute_notes { + envelope = envelope.with_note(note); + } for note in &output.notes { envelope = envelope.with_note(note); } -- cgit 1.4.1 From bce93d3deedfc4f0a00a931b1b06ee1c9e8520d1 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 21:23:45 +0000 Subject: impute: make the hmm path able to run at all -- three bugs impute=none and impute=mean already worked; impute=hmm died every time with "gemma-wrapper's response listed no association output files", which named neither the cause nor the place. Three separate faults, each measured: 1. chromosomes_from split the SNP map on whitespace only. The panel's own file reads "marker, 3001490, 1" (spaces after the commas) and the HMM file scripts/qtl2-impute-bimbam.R writes reads "marker,3001490,1" -- one token -- so the chromosome list came back empty and ravanan was handed an empty scatter. It now splits on commas and whitespace both. 2. The HMM calls come from the qtl2 cross, whose individuals are the whole panel: 235 for BXD.8 against the 198 animals that carry trait values. Passing the panel's positional values against those columns makes every individual missing -- GEMMA says "no individuals in common", ravanan says "no association output files". The R script now also writes .individuals.txt and the ravanan path re-aligns the trait values to it by name; the reply says how many individuals the HMM calls carry. 3. A relative PREPARE_GENOTYPES ("scripts/prepare-genotypes.sh") is only found when the server runs from its checkout. An instance started elsewhere answered "could not run scripts/prepare-genotypes.sh: No such file or directory". A relative default is now resolved against the checkout that GEMMA_RAVANAN_WORKFLOW points into. State after these: none 200 (21 055 rows), mean 200 (21 056 rows, with its note), hmm now runs the whole workflow (the run took 32 minutes single-machine before failing) and stops on ravanan's own manifest cache -- "source file .../manifest.scm newer than compiled .../ccache" -- which is the next thing to fix and is not about genotypes. Same-genotype agreement, measured separately (gemma on the HMM BIMBAM versus pangemma on an LMDB store built from that same file): identical top marker (rsm10000010578, p 1.04e-05), Spearman rho 0.999971, top-50 overlap 50/50, median |difference in -log10 p| 0.00000. The engines agree; what was left was plumbing. --- scripts/qtl2-impute-bimbam.R | 6 +++++ src/config.rs | 20 +++++++++++++- src/gemma.rs | 12 ++++++++- src/routes/gemma.rs | 62 ++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 96 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 4003f4e..df5f6d6 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -82,6 +82,12 @@ for (chr_name in names(imputed)) { writeLines(vapply(rows, paste, character(1), collapse = ","), paste0(out_prefix, ".bimbam.txt")) +# The individual order of the calls, because it is the *cross's* order and not +# necessarily the panel's: a caller that writes a phenotype file positionally +# has to align to this, or the two disagree by name and every individual is +# missing (measured: gemma answered "no individuals in common" and ravanan +# reported no association files at all). +writeLines(colnames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/config.rs b/src/config.rs index b937ce5..118b12b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -554,7 +554,25 @@ impl Config { ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), - prepare_genotypes: values["PREPARE_GENOTYPES"].clone(), + prepare_genotypes: { + // A relative default is fine when the server runs from its + // checkout, and silently fatal when it does not (measured: an + // instance started elsewhere answered "could not run + // scripts/prepare-genotypes.sh"). The workflow path already + // points into that checkout, so it is used to locate the + // scripts directory when the relative name does not resolve. + let configured = values["PREPARE_GENOTYPES"].clone(); + let path = std::path::Path::new(&configured); + if path.is_absolute() || path.exists() { + configured + } else { + let workflow = std::path::Path::new(&values["GEMMA_RAVANAN_WORKFLOW"]); + match workflow.parent().and_then(|cwl| cwl.parent()).and_then(|repo| repo.parent()) { + Some(repo) => repo.join(&configured).to_string_lossy().into_owned(), + None => configured, + } + } + }, rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(), diff --git a/src/gemma.rs b/src/gemma.rs index 02a2456..c502903 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -1255,8 +1255,18 @@ fn trait_input_key(kinship_key: &str, trait_values: &TraitValues) -> String { fn chromosomes_from(contents: &str) -> Vec { let mut seen = std::collections::HashSet::new(); let mut chromosomes = Vec::new(); + // The SNP map is `marker, pos, chr` in the panel's own files (spaces after + // the commas) and `marker,pos,chr` in the ones scripts/qtl2-impute-bimbam.R + // writes. Splitting on whitespace alone read the second form as one token + // and returned no chromosomes at all, which reaches ravanan as an empty + // scatter and comes back as "no association output files" -- a genotype + // problem that was really a delimiter problem. for line in contents.lines() { - if let Some(chr) = line.split_whitespace().nth(2) { + let fields: Vec<&str> = line + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|field| !field.is_empty()) + .collect(); + if let Some(chr) = fields.get(2) { if seen.insert(chr.to_string()) { chromosomes.push(chr.to_string()); } diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 8c2c543..329158a 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1113,6 +1113,33 @@ async fn prepare_genotypes( }) } +/// Re-order trait values to the individual order of a prepared genotype file. +/// +/// `hmm` genotypes come from the qtl2 cross, whose individuals are the whole +/// panel -- 235 for BXD.8 against the 198 that have trait values. Passing the +/// panel's positional values against those columns makes every individual +/// missing, which GEMMA reports as "no individuals in common" and ravanan as +/// "no association output files"; the fix is to write the phenotype by name in +/// the genotype file's order. +fn align_to_individuals( + individuals_path: &str, + names: &[String], + values: &[Option], +) -> Result>, std::io::Error> { + let by_name: std::collections::HashMap<&str, Option> = names + .iter() + .map(String::as_str) + .zip(values.iter().copied()) + .collect(); + let text = std::fs::read_to_string(individuals_path)?; + Ok(text + .lines() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(|name| by_name.get(name).copied().flatten()) + .collect()) +} + #[utoipa::path(post, path = "/compute/gemma/ravanan", summary = "Map a QTL with GEMMA, run via ravanan instead of gemma-wrapper directly", description = "Same computation and request/response shape as POST \ @@ -1184,9 +1211,9 @@ pub async fn compute_gemma_ravanan( let ResolvedInputs { genotype_file, snps_file, - trait_values, + mut trait_values, individuals: panel_individuals, - names: _, + names: resolved_names, group: resolved_group, notes: input_notes, } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; @@ -1268,6 +1295,37 @@ pub async fn compute_gemma_ravanan( ) .await?; impute_notes = prepared.notes; + if impute == "hmm" { + let individuals = format!( + "{}.individuals.txt", + prepared + .genotype_file + .trim_end_matches(".bimbam.txt") + ); + if let Some(names) = resolved_names.as_deref() { + match align_to_individuals(&individuals, names, &trait_values) { + Ok(aligned) => { + impute_notes.push(format!( + "genotypes: trait values aligned by name to the {} individuals of the \ + HMM calls ({} had a value in the panel)", + aligned.len(), + trait_values.iter().filter(|v| v.is_some()).count() + )); + trait_values = aligned; + } + Err(error) => { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not align individuals", + format!("reading {individuals} failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + } + } (prepared.genotype_file, prepared.snps_file) }; -- cgit 1.4.1 From 2df90559ca597c0d35daf68e8648f8a46c823787 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 10:25:14 +0000 Subject: impute=hmm runs now: individuals from rownames, and a versioned cache Two more faults, both measured, both in the plumbing rather than the statistics. maxmarg returns individuals x markers, so colnames are *markers*: the individuals file I added last commit listed 1 452 marker names, every trait value aligned to nothing, and the workflow answered "number of analyzed individuals equals 0". It writes rownames now -- 235 names for BXD.8 -- and impute=hmm completes: 200, 11 657 rows, 26 s, single machine, with both notes ("missing calls predicted by R/qtl2's HMM", "trait values aligned by name to the 235 individuals"). The second fault was the cache: the prepared files are keyed on (panel, mode) and not on the code that writes them, so the corrected individuals file was ignored and the run kept failing on the stale one. The key now carries IMPUTE_CACHE_VERSION, bumped when either script changes what it writes. Three modes through the workflow, same trait, same machine: none 200, 21 055 rows mean 200, 21 056 rows hmm 200, 11 657 rows none and mean agree as they should: identical top marker (rs32133186), Spearman rho 1.00000, top-50 50/50, median |d(-log10 p)| 0.00004. hmm disagrees, and that is a real finding rather than a rounding matter: rho -0.07 against both, different top marker, and only 11 657 of the 20 453 markers reported. A rank correlation near zero means the genotypes and the markers are not being paired the way the other two modes pair them, so the next thing to check is the annotation file this path feeds GEMMA (it comes from the cross's physical map, while the genotype rows come from the HMM's marker order) -- not the imputation itself, which the same-genotype comparison already showed to be sound (rho 0.999971 against pangemma on the identical calls). --- scripts/qtl2-impute-bimbam.R | 9 ++++++--- src/routes/gemma.rs | 8 +++++++- 2 files changed, 13 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index df5f6d6..2e11a40 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -82,12 +82,15 @@ for (chr_name in names(imputed)) { writeLines(vapply(rows, paste, character(1), collapse = ","), paste0(out_prefix, ".bimbam.txt")) -# The individual order of the calls, because it is the *cross's* order and not -# necessarily the panel's: a caller that writes a phenotype file positionally +# The individual order of the calls -- rownames, because maxmarg returns +# individuals x markers and colnames are therefore markers (measured: writing +# colnames put 1452 marker names in a file of individuals, every value aligned +# to nothing, and the run reported "number of analyzed individuals equals 0") -- +# because it is the *cross's* order and not necessarily the panel's: a caller that writes a phenotype file positionally # has to align to this, or the two disagree by name and every individual is # missing (measured: gemma answered "no individuals in common" and ravanan # reported no association files at all). -writeLines(colnames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) +writeLines(rownames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 329158a..e94ca72 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -947,9 +947,15 @@ async fn prepare_genotypes( .file_stem() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| "panel".to_string()); + // The cache key carries a version, because it is keyed on the panel and the + // mode and NOT on the code that produces them: a fixed bug in the imputation + // script would otherwise be masked by its own old output (measured: a + // corrected individuals file was ignored and the run kept failing on the + // stale one). Bump this when either script changes what it writes. + const IMPUTE_CACHE_VERSION: &str = "v2"; let prefix = std::path::Path::new(&config.ravanan_cache_dir) .join("imputed") - .join(format!("{stem}-{mode}")); + .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); -- cgit 1.4.1 From a3d67c72dfa78840eb846f5d93f6f6326ac32b32 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 11:31:10 +0000 Subject: impute: a monotone genetic map for the HMM, and say hmm is not yet sound The HMM smooths along a genetic map, and ours is degenerate: the .geno files carry no cM, so the converted cross has 19 markers "with missing genetic map position; using 0". With no distance between markers the HMM has nothing to smooth with, and the probabilities show it: P(BB) never rises above 0.5 and every individual is called AA. When the map has gaps it is now replaced by physical position at 1 cM per Mb -- crude, monotone, and better than zeros. That fixed part of it (the spread of calls at a marker went from sd 0.21 to 0.34 where the panel has 0.46) but not the collapse: at rsm10000005700, where the panel has 125 BB, 84 A and 26 missing, maxmarg still answers 228 AA and 7 BB. Two explanations have been eliminated by measurement -- the code mapping (maxmarg returns genotype *names*; that is now derived from the data, so AA/BB map correctly) and the missing-value encoding (0 is already qtl2's missing). What is left is the converted cross itself: both HMM states appear to correspond to the same physical allele at many markers, which is a question for src/qtl2.rs, not for the imputation. So the reply now says so out loud: "NOT YET VALIDATED on a riself panel ... treat the hmm scan as experimental and prefer none or mean". A mode that runs and answers the wrong question silently is worse than one that says it is not ready. --- scripts/prepare-genotypes.sh | 8 +++--- scripts/qtl2-impute-bimbam.R | 62 +++++++++++++++++++++++++++++++++++++++++--- src/routes/gemma.rs | 46 ++++++++++++++++++++++++++++++-- 3 files changed, 108 insertions(+), 8 deletions(-) (limited to 'scripts') diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index 36a959b..9624e0e 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -15,13 +15,14 @@ # # scripts/prepare-genotypes.sh --mode mean|hmm|none \ # --geno --snps --out \ -# [--cross ] [--probs ] [--minprob N] +# [--cross ] [--probs ] [--minprob N] \ +# [--individuals-file ] # # Writes .bimbam.txt and .snps.txt and prints the prefix. # Exits 2 on bad arguments, 1 when a step fails. set -eu -mode= geno= snps= out= cross_dir= probs= minprob=0 +mode= geno= snps= out= cross_dir= probs= minprob=0 individuals_file= while [ $# -gt 0 ]; do case $1 in --mode) mode=$2; shift 2 ;; @@ -31,6 +32,7 @@ while [ $# -gt 0 ]; do --cross) cross_dir=$2; shift 2 ;; --probs) probs=$2; shift 2 ;; --minprob) minprob=$2; shift 2 ;; + --individuals-file) individuals_file=$2; shift 2 ;; -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; esac @@ -66,7 +68,7 @@ hmm) # R's own complaint last, so a caller that reports the final stderr line # reports the cause rather than our wrapper sentence. if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ - "$cross_dir" "${probs:--}" "$out" "$minprob" 2>&1); then + "$cross_dir" "${probs:--}" "$out" "$minprob" "$individuals_file" 2>&1); then echo "prepare-genotypes.sh: HMM imputation failed:" >&2 printf '%s\n' "$r_output" | tail -6 >&2 exit 1 diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 2e11a40..ae95b48 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -26,6 +26,13 @@ if (length(args) < 3) { } cross_dir <- args[1]; probs_path <- args[2]; out_prefix <- args[3] minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 +# Optional: the individuals the caller is actually serving, one per line. The +# cross carries the whole panel; a request that drops parents and F1s serves a +# subset, and a genotype file with more columns than the phenotype covers makes +# every comparison between modes meaningless (measured: none/mean fitted 198 +# individuals, hmm 235, and the peaks landed on different chromosomes). +individuals_file <- if (length(args) >= 5 && nzchar(args[5])) args[5] else NULL +wanted <- if (!is.null(individuals_file)) trimws(readLines(individuals_file)) else NULL setwd(cross_dir) cross <- read_cross2("control.json") @@ -51,7 +58,45 @@ probs <- if (identical(probs_path, "-")) { # maxmarg returns one call per marker and individual, at the highest # probability above MINPROB -- or NA when the HMM is less sure than that. At # minprob 0 every cell is filled, which is what the mdb needs. -imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1)) +# The genetic map the HMM smooths along. Ours is often degenerate -- the .geno +# files carry no cM, so the converter writes 0 for many markers ("19 markers with +# missing genetic map position; using 0"), and with no distance between markers +# the HMM has nothing to smooth with: measured, P(BB) never exceeded 0.5 and +# every individual was called AA at a marker where 125 of 235 are BB. When the +# map has gaps, positions come from the physical map at 1 cM per Mb, which is +# crude but monotone and infinitely better than 0. +if (!is.null(cross$pmap)) { + for (chr_name in names(cross$gmap)) { + g <- cross$gmap[[chr_name]] + p_mb <- cross$pmap[[chr_name]][names(g)] / 1e6 + if (anyNA(g) || any(diff(g) <= 0) || any(g == 0)) { + if (!anyNA(p_mb)) cross$gmap[[chr_name]] <- unname(p_mb) + } + } +} + +# return_char: the genotype LETTERS (A/B, plus H if it were kept), not qtl2's +# internal genotype *indices*. Measured the hard way: maxmarg returns 1..n_gen +# -- 1 and 2 for a riself cross -- which are not the cross's numeric codes +# (A=1, B=3 per control.json). Mapping 2 to 1 read every BB animal as a +# heterozygote, which collapsed the genotypes (sd 0.21 where the panel has +# 0.46) and quietly killed the scan: the same marker that is p 5.9e-07 in the +# other modes came out at 2.0e-01. +imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1, + return_char = TRUE)) +if (!is.null(wanted)) { + present <- rownames(imputed[[1]]) + keep <- wanted[wanted %in% present] + if (length(keep) == 0) { + stop("none of the requested individuals appear in the cross", call. = FALSE) + } + for (chr_name in names(imputed)) { + imputed[[chr_name]] <- imputed[[chr_name]][keep, , drop = FALSE] + } + wanted_kept <- keep +} else { + wanted_kept <- rownames(imputed[[1]]) +} # How much work the HMM did: cells the cross itself had as missing (a 0 in an # explicit genotype map, never NA -- see read_cross2's own convention). @@ -61,7 +106,18 @@ left <- sum(vapply(imputed, function(g) sum(is.na(g)), integer(1))) # The calls come back as genotype *codes* in qtl2's numeric convention for this # cross (A = 1, B = 3, H = 2 per control.json); pangemma wants 0/1/2. -codes <- c(`1` = 0, `2` = 1, `3` = 2) +# The alphabet comes from the data: return_char gives the genotype *names* +# ("AA"/"BB" for a riself cross, "A"/"B" for a plain one, one name per founder +# for multiparent), so the first is homozygote 1 (0), the last homozygote 2 (2) +# and anything in between a heterozygote (1). Hard-coding A/H/B skipped every +# marker, because the values are "AA" and "BB" -- the run then had no +# chromosomes and no association files. +present <- sort(unique(as.vector(unlist(imputed)))) +present <- present[!is.na(present)] +if (length(present) < 2) { + stop("the HMM returned a single genotype state; nothing to map", call. = FALSE) +} +codes <- stats::setNames(c(0, rep(1, max(0, length(present) - 2)), 2), present) rows <- list(); snps <- list() # maxmarg returns individuals x markers (rows are individuals, which is the # opposite of the BIMBAM's marker-per-line shape, and the reason a first version @@ -90,7 +146,7 @@ writeLines(vapply(rows, paste, character(1), collapse = ","), # has to align to this, or the two disagree by name and every individual is # missing (measured: gemma answered "no individuals in common" and ravanan # reported no association files at all). -writeLines(rownames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) +writeLines(wanted_kept, paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index e94ca72..31d5538 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -941,6 +941,7 @@ async fn prepare_genotypes( snps_file: &str, group: &Option, version: Option<&str>, + names: Option<&Vec>, rid: RequestInfo, ) -> Result { let stem = std::path::Path::new(genotype_file) @@ -952,7 +953,7 @@ async fn prepare_genotypes( // script would otherwise be masked by its own old output (measured: a // corrected individuals file was ignored and the run kept failing on the // stale one). Bump this when either script changes what it writes. - const IMPUTE_CACHE_VERSION: &str = "v2"; + const IMPUTE_CACHE_VERSION: &str = "v6"; let prefix = std::path::Path::new(&config.ravanan_cache_dir) .join("imputed") .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); @@ -1039,6 +1040,39 @@ async fn prepare_genotypes( std::path::PathBuf::new() }; + if let Some(parent) = std::path::Path::new(&prepared_geno).parent() { + if let Err(error) = std::fs::create_dir_all(parent) { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not create the imputation cache directory", + format!("creating {} failed: {error}", parent.display()), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + // The individuals the request actually serves, so the HMM output has the + // same columns as the other modes and the phenotype lines up positionally. + let individuals_path = format!("{}.panel.txt", prefix.to_string_lossy()); + if let Some(names) = names { + if !names.is_empty() { + if let Err(error) = std::fs::write( + &individuals_path, + names.iter().map(|n| format!("{n}\n")).collect::(), + ) { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the individual list", + format!("writing {individuals_path} failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + } + let individuals_arg = individuals_path.clone(); let script = config.prepare_genotypes.clone(); let script_for_job = script.clone(); let geno = genotype_file.to_string(); @@ -1063,6 +1097,10 @@ async fn prepare_genotypes( args.push(cross_dir.to_string_lossy().into_owned()); args.push("--probs".to_string()); args.push("-".to_string()); + if std::path::Path::new(&individuals_arg).is_file() { + args.push("--individuals-file".to_string()); + args.push(individuals_arg.clone()); + } } std::process::Command::new(&script_for_job).args(&args).output() }) @@ -1109,7 +1147,10 @@ async fn prepare_genotypes( .to_string(), _ => "genotypes: missing calls predicted by R/qtl2's HMM (maxmarg on the \ group's cached genotype probabilities, the same calls /compute/qtl2 \ - maps on)" + maps on). NOT YET VALIDATED on a riself panel: measured on BXD.8 \ + the calls collapse towards one allele at markers that carry both \ + (228 AA against the panel's 125 BB at rsm10000005700), so treat the \ + hmm scan as experimental and prefer none or mean." .to_string(), }); Ok(PreparedGenotypes { @@ -1297,6 +1338,7 @@ pub async fn compute_gemma_ravanan( &snps_file, &Some(resolved_group.clone()), request.genotype_version.as_deref(), + resolved_names.as_ref(), rid.clone(), ) .await?; -- cgit 1.4.1 From df7fb3dd11be0a27de8904f7a4cb1309bdb64575 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 13:02:21 +0000 Subject: qtl2-convert-geno.R: convert a .geno file to a cross in R, where the format lives The conversion was Rust writing qtl2's files by hand, and one of qtl2's conventions was wrong in it: the genotype codes. This does the same conversion as an R script and lets qtl2 write its own JSON metadata with write_control_file, so the layout and the codes come from the format's definition rather than from a second implementation of it. qtl2-convert-geno.R --geno BXD.8.geno --out DIR [--het drop|keep] [--crosstype riself|f2] The allele letters are read from the file's @mat/@pat/@het header lines (B/D as often as A/B), autosomes only, the heterozygous class dropped for a riself cross as R/qtl's convert2riself does, and missing calls left missing because imputing them is the point of the cross. Measured on BXD.8.geno: 20453 autosomal markers, 235 individuals, 610684 heterozygous calls dropped and 1533 missing cells left to the HMM. read_cross2 -> calc_genoprob(error_prob 0.002) -> maxmarg(minprob 0.5) reproduces 4193962 of 4194238 kept calls (99.99%) and imputes the 612217 dropped ones almost evenly (A 306841, B 305376). At rsm10000005700, where the old codes produced 218 AA and 17 BB against a truth of 84 A and 125 B, all 209 kept calls are reproduced. The Rust converter still runs; handing /compute/qtl2 over to this script is the next commit. --- scripts/qtl2-convert-geno.R | 135 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100755 scripts/qtl2-convert-geno.R (limited to 'scripts') diff --git a/scripts/qtl2-convert-geno.R b/scripts/qtl2-convert-geno.R new file mode 100755 index 0000000..c688930 --- /dev/null +++ b/scripts/qtl2-convert-geno.R @@ -0,0 +1,135 @@ +#!/usr/bin/env Rscript +# qtl2-convert-geno.R -- convert a GeneNetwork `.geno` file into an R/qtl2 cross. +# +# This is the conversion that used to live in src/qtl2.rs, done where it belongs: +# the output *is* an R/qtl2 cross, the format is qtl2's own, and the JSON +# metadata that describes it is written by qtl2's `write_control_file` rather +# than by hand. Writing those files in Rust meant reimplementing qtl2's +# conventions in another language, and one of them was wrong: the genotype +# codes. With the heterozygous class dropped (the `riself` default) the cross +# carries two alleles, and they must be numbered 1 and 2. Numbering the second +# one 3 gave qtl2's two-state HMM an allele code it cannot use -- it read that +# allele as unusable, P(second allele) never rose above 0.5, every individual +# was called the first allele, and a scan on those calls lost the signal +# (2.0e-01 where the same marker is 5.9e-07 from the BIMBAM). +# +# qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2] +# +# writes DIR/{control.json,geno.csv,gmap.csv,pmap.csv,pheno.csv} -- the layout +# `read_cross2(DIR/control.json)` reads back -- and prints a one-line summary. +# Autosomes only: the X needs a sex covariate and the other chromosomes +# degenerate the per-chromosome kinship (the same limit /compute/qtl2 has). + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +get <- function(flag, default = NULL) { + i <- match(flag, args) + if (is.na(i)) return(default) + args[i + 1] +} +geno_path <- get("--geno") +out_dir <- get("--out") +het <- match.arg(get("--het", "drop"), c("drop", "keep")) +crosstype <- match.arg(get("--crosstype", "riself"), c("riself", "f2")) +if (is.null(geno_path) || is.null(out_dir)) { + stop("usage: qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2]", + call. = FALSE) +} + +lines <- readLines(geno_path, warn = FALSE) +meta <- function(key) { + hit <- grep(paste0("^@", key, ":"), lines, value = TRUE) + if (length(hit) == 0) NULL else trimws(sub(paste0("^@", key, ":"), "", hit[1])) +} +# The allele letters are declared by the file, not assumed: GeneNetwork panels +# use B/D as often as A/B. +mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het") +if (is.null(mat) || is.null(pat)) { + stop("the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded", + call. = FALSE) +} + +hdr <- lines[tolower(substr(lines, 1, 4)) == "chr\t"][1] +if (is.na(hdr)) stop("the .geno file has no 'Chr' header row", call. = FALSE) +cols <- strsplit(hdr, "\t")[[1]] +individuals <- cols[-(1:4)] + +body <- lines[!startsWith(lines, "#") & lines != hdr] +autosomes <- as.character(1:19) + +geno <- list(); gmap <- list(); pmap <- list() +dropped <- 0L +for (line in body) { + f <- strsplit(line, "\t")[[1]] + if (length(f) < 5) next + chr <- f[1] + if (!(chr %in% autosomes)) next + marker <- f[2] + calls <- f[-(1:4)] + # A call is A, B or (if the heterozygous class is kept) H; anything else -- + # U or blank -- is missing and stays missing, because that is what the HMM is + # for. + calls[calls == mat] <- "A" + calls[calls == pat] <- "B" + if (!is.null(het_code)) { + calls[calls == het_code] <- if (het == "keep") "H" else "" + dropped <- dropped + if (het == "drop") sum(f[-(1:4)] == het_code) else 0L + } + calls[!(calls %in% c("A", "B", "H"))] <- "" + geno[[marker]] <- calls + gmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[3]))) + pmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[4])) * 1e6) +} + +if (length(geno) == 0) stop("no autosomal markers in the .geno file", call. = FALSE) + +# A degenerate genetic map leaves the HMM nothing to smooth along (the .geno +# files carry no cM), so missing positions fall back to physical distance at +# 1 cM per Mb -- crude, monotone, and better than zeros. +for (marker in names(gmap)) { + g <- gmap[[marker]] + if (!is.finite(as.numeric(g["pos"]))) { + p <- pmap[[marker]] + gmap[[marker]]["pos"] <- if (is.finite(as.numeric(p["pos"]))) as.numeric(p["pos"]) / 1e6 else 0 + } +} + +dir.create(out_dir, recursive = TRUE, showWarnings = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(gmap, `[`, "", "chr"), + pos = as.numeric(vapply(gmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "gmap.csv"), row.names = FALSE, quote = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(pmap, `[`, "", "chr"), + pos = as.numeric(vapply(pmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "pmap.csv"), row.names = FALSE, quote = FALSE) +# qtl2's default genotype file has one row per individual and one column per +# marker, with the first column named `id` (see qtl2's own iron example). +geno_df <- data.frame(id = individuals, + do.call(cbind, lapply(geno, function(calls) calls)), + check.names = FALSE, stringsAsFactors = FALSE) +names(geno_df) <- c("id", names(geno)) +write.csv(geno_df, file.path(out_dir, "geno.csv"), row.names = FALSE, quote = FALSE) +# qtl2 wants a phenotype column to be able to read a cross; the trait comes from +# the request, through the scan script's --pheno. +write.csv(data.frame(id = individuals, trait = 1), + file.path(out_dir, "pheno.csv"), row.names = FALSE, quote = FALSE) + +# The JSON metadata is qtl2's own description of a cross: one call, no +# hand-rolled keys, and it stays right when qtl2 changes. +# 1..n over the genotypes the file carries: A/B for a riself cross with the +# heterozygous class dropped, A/H/B when it is kept. +codes <- if (crosstype == "riself" && het == "drop") c(A = 1L, B = 2L) else c(A = 1L, H = 2L, B = 3L) +write_control_file( + file.path(out_dir, "control.json"), + crosstype = crosstype, + geno_file = "geno.csv", gmap_file = "gmap.csv", pmap_file = "pmap.csv", + pheno_file = "pheno.csv", + geno_transposed = FALSE, sep = ",", + na.strings = "", + geno_codes = codes, overwrite = TRUE) + +cat(sprintf("geno2cross: %d markers, %d individuals, %d heterozygous calls %s, crosstype %s -> %s\n", + length(geno), length(individuals), dropped, + if (het == "drop") "dropped" else "kept", crosstype, out_dir)) -- cgit 1.4.1 From 14622e57629d19451cad03f4a69fdd89e81a433f Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 16:05:11 +0000 Subject: qtl2: the .geno conversion is an R script now, and the Rust writer is gone The conversion wrote qtl2's control file and CSVs by hand in Rust. Its output is an R/qtl2 cross, so the script does it and write_control_file describes it: one implementation of the format, qtl2's. What Rust keeps is the endpoint's own limit -- a .geno panel carries no founder genotypes, so a multiparent crosstype is a 422 with a reason, and the cross type follows @type and the heterozygous policy. prepare_cross now runs Rscript scripts/qtl2-convert-geno.R --geno GROUP.geno --out DIR --het drop|keep --crosstype riself|f2 writes the cross into the same versioned cache directory (now v6: the files it writes are qtl2's own layout), and reads back the report the script leaves beside it -- markers, non-autosomal, individuals, het_dropped, cells -- instead of counting them itself. A failed conversion reports R's own complaint. New configuration key QTL2_CONVERT_SCRIPT (default scripts/qtl2-convert-geno.R). The Rust writer's 250 lines are deleted, along with count_calls and metadata_het. Measured, BXD trait 10001 on the same request: before (Rust, alleles 1/3) top rsm10000005730 chr8 LOD 3.685 after (R/qtl2, alleles 1/2) top rs32579649 chr8 LOD 3.8917, rsm10000005700 3.8916 GEMMA LMM, same trait rsm10000005700 p 5.90e-07 so the wrong allele code was flattening this endpoint's own scan too: it still found chromosome 8, at a neighbouring marker and 0.21 LOD lower, with the marker GEMMA picks not in its top three. The two engines now agree on the locus. Cost: 38.3 s cold for 20453 autosomal markers (the R conversion is ~35 s of it), 3.5 s with the cross cached. --- README.md | 13 +- scripts/qtl2-convert-geno.R | 18 ++- src/config.rs | 9 ++ src/qtl2.rs | 350 +++++++++++++------------------------------- src/routes/gemma.rs | 10 +- src/routes/qtl2.rs | 10 +- 6 files changed, 153 insertions(+), 257 deletions(-) (limited to 'scripts') diff --git a/README.md b/README.md index fc9a5fc..0bbaba4 100644 --- a/README.md +++ b/README.md @@ -1967,8 +1967,17 @@ directory the data is not in, declare no genotype-code map (every genotype reads as missing) and no orientation (individuals read as markers) — four traps that each produce a plausible flat scan rather than an error. The conversion also drops heterozygous calls on a `riself` panel, as R/qtl's -`convert2riself` does. Configuration: `QTL2_SCRIPT_PATH`, -`QTL2_CACHE_DIR`. +`convert2riself` does, and recodes the surviving alleles to 1 and 2 — a second +allele numbered 3 is not an allele a two-state HMM can use, and the scan built +on it was flat (BXD 10001: LOD 3.685 at the wrong marker, against 3.892 at the +locus GEMMA reports, p 5.9e-07). + +The conversion is an R script, `scripts/qtl2-convert-geno.R`, not Rust: its +output is an R/qtl2 cross, and `write_control_file` describes it, so the layout +and the codes come from the format's definition rather than from a second +implementation of it. Cost: 38 s cold for BXD's 20 453 autosomal markers, 3.5 s +once the cross is cached. Configuration: `QTL2_SCRIPT_PATH`, +`QTL2_CONVERT_SCRIPT`, `QTL2_CACHE_DIR`. ### Gene link-outs diff --git a/scripts/qtl2-convert-geno.R b/scripts/qtl2-convert-geno.R index c688930..48b4779 100755 --- a/scripts/qtl2-convert-geno.R +++ b/scripts/qtl2-convert-geno.R @@ -31,7 +31,7 @@ get <- function(flag, default = NULL) { geno_path <- get("--geno") out_dir <- get("--out") het <- match.arg(get("--het", "drop"), c("drop", "keep")) -crosstype <- match.arg(get("--crosstype", "riself"), c("riself", "f2")) +crosstype <- get("--crosstype") if (is.null(geno_path) || is.null(out_dir)) { stop("usage: qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2]", call. = FALSE) @@ -44,7 +44,7 @@ meta <- function(key) { } # The allele letters are declared by the file, not assumed: GeneNetwork panels # use B/D as often as A/B. -mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het") +mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het"); type <- meta("type") if (is.null(mat) || is.null(pat)) { stop("the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded", call. = FALSE) @@ -59,12 +59,12 @@ body <- lines[!startsWith(lines, "#") & lines != hdr] autosomes <- as.character(1:19) geno <- list(); gmap <- list(); pmap <- list() -dropped <- 0L +dropped <- 0L; non_autosomal <- 0L; markers_seen <- 0L for (line in body) { f <- strsplit(line, "\t")[[1]] if (length(f) < 5) next chr <- f[1] - if (!(chr %in% autosomes)) next + if (!(chr %in% autosomes)) { non_autosomal <- non_autosomal + 1L; next } marker <- f[2] calls <- f[-(1:4)] # A call is A, B or (if the heterozygous class is kept) H; anything else -- @@ -78,6 +78,7 @@ for (line in body) { } calls[!(calls %in% c("A", "B", "H"))] <- "" geno[[marker]] <- calls + markers_seen <- markers_seen + 1L gmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[3]))) pmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[4])) * 1e6) } @@ -130,6 +131,15 @@ write_control_file( na.strings = "", geno_codes = codes, overwrite = TRUE) +# The report the caller reads back: what this cross holds, and what the +# conversion dropped. It is written beside the cross so a cached one costs +# nothing. +writeLines(jsonlite::toJSON(list( + crosstype = crosstype, markers = length(geno), non_autosomal = non_autosomal, + individuals = as.list(individuals), het_dropped = dropped, + cells = length(individuals) * length(geno)), auto_unbox = TRUE), + file.path(out_dir, "conversion.json")) + cat(sprintf("geno2cross: %d markers, %d individuals, %d heterozygous calls %s, crosstype %s -> %s\n", length(geno), length(individuals), dropped, if (het == "drop") "dropped" else "kept", crosstype, out_dir)) diff --git a/src/config.rs b/src/config.rs index 118b12b..ce2b038 100644 --- a/src/config.rs +++ b/src/config.rs @@ -139,6 +139,9 @@ pub struct Config { pub fitqtl_script_path: String, /// Path to scripts/qtl2_scan.R, which POST /compute/qtl2 runs. pub qtl2_script_path: String, + /// The `.geno` -> qtl2-cross conversion, an R script (`Qt l2` owns its + /// own file format; see `src/qtl2.rs`). + pub qtl2_convert_script: String, /// Directory POST /compute/qtl2 keeps converted crosses and scan /// output in. Defaults to a "gn4-qtl2" directory under the temp dir. pub qtl2_cache_dir: String, @@ -343,6 +346,10 @@ impl Config { "QTL2_SCRIPT_PATH".to_string(), "scripts/qtl2_scan.R".to_string(), ); + values.insert( + "QTL2_CONVERT_SCRIPT".to_string(), + "scripts/qtl2-convert-geno.R".to_string(), + ); values.insert( "QTL2_CACHE_DIR".to_string(), std::env::temp_dir() @@ -493,6 +500,7 @@ impl Config { "RQTL_WRAPPER_PATH", "FITQTL_SCRIPT_PATH", "QTL2_SCRIPT_PATH", + "QTL2_CONVERT_SCRIPT", "QTL2_CACHE_DIR", "RQTL_CACHE_DIR", "WIKIDATA_CACHE_DIR", @@ -576,6 +584,7 @@ impl Config { rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(), + qtl2_convert_script: values["QTL2_CONVERT_SCRIPT"].clone(), qtl2_cache_dir: values["QTL2_CACHE_DIR"].clone(), rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), wikidata_cache_dir: values["WIKIDATA_CACHE_DIR"].clone(), diff --git a/src/qtl2.rs b/src/qtl2.rs index 44011de..0c0622f 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -155,47 +155,22 @@ pub struct Qtl2Output { pub permutation_note: Option, } -/// How many genotype cells carry one code -- the count a cached conversion -/// needs to say what it dropped, without re-converting. -fn count_calls(text: &str, code: &str) -> usize { - let mut seen_header = false; - let mut start = 3usize; - let mut count = 0usize; - for line in text.lines() { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { - continue; - } - let columns: Vec<&str> = line.split('\t').collect(); - if !seen_header { - seen_header = true; - start = if columns.len() > 3 && columns[3] == "Mb" { 4 } else { 3 }; - continue; - } - count += columns.iter().skip(start).filter(|cell| cell.trim() == code).count(); - } - count -} - -/// The header's `@het` code, if it declares one. -fn metadata_het(text: &str) -> Option { - text.lines() - .find_map(|line| line.strip_prefix("@het:")) - .map(|value| value.trim().to_string()) -} - -fn io_error(path: &Path, error: io::Error) -> Qtl2Error { - Qtl2Error::Io(io::Error::new( - error.kind(), - format!("{}: {error}", path.display()), - )) -} +/// The conversion, as an R script. +pub const CONVERT_SCRIPT: &str = "scripts/qtl2-convert-geno.R"; /// Convert `resolved`'s `.geno` into a cached qtl2 cross. +/// +/// The conversion itself is [`CONVERT_SCRIPT`], an R script: the output is an +/// R/qtl2 cross, and qtl2's own `write_control_file` describes it. Doing that +/// here meant a second implementation of the format in Rust, and one of its +/// conventions -- the genotype codes -- was wrong in a way that silently +/// destroyed the scan (see the script's own comment). Reading the report the +/// script leaves beside the cross is all this side needs to do. pub fn prepare_cross( resolved: &Resolved, cache_dir: &Path, het: Het, + convert_script: &Path, ) -> Result { let geno = &resolved.geno; let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?; @@ -209,45 +184,20 @@ pub fn prepare_cross( .map(|since| since.as_secs()) .unwrap_or(0) ); - // The version tag is part of the key: a change to this conversion (the - // heterozygous calls dropped for a riself panel, say) must not silently - // reuse the previous cross's probabilities and kinship. - // v3 keyed the heterozygous policy in as well: a cross converted with the - // calls kept is a different cross from one with them dropped. - // v4: the allele *codes*. With H=2, B=3 in a cross where the - // heterozygous class is dropped, the surviving pair is 1/3 -- and qtl2's - // two-state riself HMM cannot use an allele code outside 1..2. It treats - // that allele as unusable: measured, P(BB) never rose above 0.5, every - // individual was called AA at a marker where 125 of 235 are BB, and a scan - // built on those calls had nothing left of the signal (p 2.0e-01 where the - // same marker is 5.9e-07 from the BIMBAM). Recoding to 1/2 fixed it - // completely: agreement with the calls 209 of 209. - const CONVERSION_VERSION: &str = "v5"; - let directory = cache_dir.join("crosses").join(format!( - "{CONVERSION_VERSION}-{}-{}-{stamp}", - het.as_str(), - resolved.version.replace(['/', '.'], "_") - )); - let control = directory.join("control.json"); let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?; - // Metadata: the genotype codes, and the cross type. - let mut codes: BTreeMap = BTreeMap::new(); - let mut cross_type = String::new(); + // The cross type is checked here rather than in R: this is the endpoint's + // own limit (a `.geno` panel carries no founder genotypes, so it cannot be + // a multiparent cross), and the answer is a 422 with a reason, not a + // script failure. + let mut declared = String::new(); for line in text.lines() { - if let Some(rest) = line.strip_prefix('@') { - let Some((key, value)) = rest.split_once(':') else { continue }; - let value = value.trim().to_string(); - match key.trim() { - "mat" => { codes.insert(value, "A".to_string()); } - "het" => { codes.insert(value, "H".to_string()); } - "pat" => { codes.insert(value, "B".to_string()); } - "type" => cross_type = value, - _ => {} - } + if let Some(rest) = line.strip_prefix("@type:") { + declared = rest.trim().to_string(); + break; } } - let crosstype = match cross_type.as_str() { + let crosstype = match declared.as_str() { // A riset panel read as `f2` is a riset panel whose H calls are kept: // qtl2 needs a cross type that has a heterozygous state for that. "riset" if het == Het::Keep => "f2", @@ -261,205 +211,106 @@ pub fn prepare_cross( ))) } }; - // A riself panel is inbred lines: a heterozygous call is an error in the - // genotyping, not a third allele. R/qtl's `convert2riself` omits those - // genotypes, and qtl2 needs the same treatment -- left in, it reads the - // cross as multiparent and its scan1 takes a path this panel cannot - // satisfy ("scan1_pg ..."). - let mut het_kept: Option = None; - if crosstype == "riself" { - let het_code = metadata_het(&text); - if let Some(het_code) = het_code { - codes.remove(&het_code); - het_kept = Some(het_code); - } - } - if codes.len() < 2 { - return Err(Qtl2Error::Unsupported( - "the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded" - .to_string(), - )); - } - // Header row: Chr, Locus, cM, Mb?, then the individuals. - let mut lines = text.lines(); - let Some(header) = lines.find(|line| line.to_lowercase().starts_with("chr\t")) else { - return Err(Qtl2Error::Unsupported( - "the .geno file has no 'Chr' header row".to_string(), - )); - }; - let fields: Vec<&str> = header.split('\t').collect(); - let first_individual = if fields.get(3).copied() == Some("Mb") { 4 } else { 3 }; - let individuals: Vec = fields[first_individual..] - .iter() - .map(|name| name.trim().to_string()) - .collect(); - if individuals.is_empty() { - return Err(Qtl2Error::Unsupported( - "the .geno header names no individuals".to_string(), - )); - } + // The version tag is part of the key: a change to the conversion must not + // silently reuse the previous cross's probabilities and kinship. v3 keyed + // the heterozygous policy in; v4/v5 were the allele codes; v6 is the + // conversion itself moving to R, which changes the files it writes (qtl2's + // own genotype layout, individuals in rows). + const CONVERSION_VERSION: &str = "v6"; + let directory = cache_dir.join("crosses").join(format!( + "{CONVERSION_VERSION}-{}-{}-{stamp}", + het.as_str(), + resolved.version.replace(['/', '.'], "_") + )); + let control = directory.join("control.json"); if !control.is_file() { std::fs::create_dir_all(&directory).map_err(|e| io_error(&directory, e))?; - let mut geno_csv = String::new(); - let mut gmap_csv = String::from("marker,chr,pos\n"); - let mut pmap_csv = String::from("marker,chr,pos\n"); - geno_csv.push_str("marker,"); - geno_csv.push_str(&individuals.join(",")); - geno_csv.push('\n'); - let mut markers = 0usize; - let mut non_autosomal = 0usize; - let mut het_dropped = 0usize; - for line in lines { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') { - continue; - } - let row: Vec<&str> = line.split('\t').collect(); - if row.len() < first_individual { - continue; - } - let (chromosome, marker, centimorgans, megabases) = - (row[0].trim(), row[1].trim(), row[2].trim(), row.get(3).copied().unwrap_or("")); - // Autosomes only: see the module comment. - if !chromosome.chars().all(|c| c.is_ascii_digit()) { - non_autosomal += 1; - continue; - } - markers += 1; - geno_csv.push_str(marker); - for value in &row[first_individual..] { - let call = codes.get(value.trim()).map(String::as_str).unwrap_or(""); - if call.is_empty() && het_kept.as_deref() == Some(value.trim()) { - het_dropped += 1; + let het_arg = het.as_str(); + let output = std::process::Command::new("Rscript") + .arg(convert_script) + .arg("--geno") + .arg(geno) + .arg("--out") + .arg(&directory) + .arg("--het") + .arg(het_arg) + .arg("--crosstype") + .arg(crosstype) + .output() + .map_err(Qtl2Error::Io)?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let interesting = |line: &&str| { + let line = line.trim(); + !line.is_empty() + && !line.starts_with("Warning") + && !line.starts_with("In ") + && line != "Execution halted" + }; + let complaint: Vec<&str> = stderr.lines().filter(interesting).collect(); + return Err(Qtl2Error::CommandFailed(format!( + "converting {} failed: {}", + geno.display(), + if complaint.is_empty() { + "R/qtl2 gave no reason".to_string() + } else { + complaint.join(" ") } - geno_csv.push(','); - geno_csv.push_str(call); - } - geno_csv.push('\n'); - gmap_csv.push_str(&format!("{marker},{chromosome},{centimorgans}\n")); - let base_pairs = megabases.parse::().map(|mb| (mb * 1e6).round() as i64).unwrap_or(0); - pmap_csv.push_str(&format!("{marker},{chromosome},{base_pairs}\n")); - } - if markers == 0 { - return Err(Qtl2Error::Unsupported( - "the panel has no autosomal markers to scan".to_string(), - )); - } - // The cross needs a phenotype file of its own to be readable; the - // trait comes from the request, through the script's --pheno. - let mut pheno_csv = String::from("id,trait\n"); - for name in &individuals { - pheno_csv.push_str(&format!("{name},1\n")); - } - for (path, contents) in [ - (directory.join("geno.csv"), &geno_csv), - (directory.join("gmap.csv"), &gmap_csv), - (directory.join("pmap.csv"), &pmap_csv), - (directory.join("pheno.csv"), &pheno_csv), - ] { - std::fs::write(&path, contents).map_err(|e| io_error(&path, e))?; + ))); } - let control_json = serde_json::json!({ - // Paths are relative to the control file: qtl2 joins its own - // directory onto whatever it finds here. - "crosstype": crosstype, - "geno": "geno.csv", - "gmap": "gmap.csv", - "pmap": "pmap.csv", - "pheno": "pheno.csv", - "sep": ",", - "na.strings": [""], - // The codes must be 1..n over the genotypes the CSV actually - // carries. A riself cross with the heterozygous class dropped - // (the default) carries only A and B, so they are 1 and 2: leaving - // B as 3 hands qtl2 an allele code outside 1..2, which its - // two-state HMM cannot use -- it then reads that allele as - // unusable, P(BB) never rises above 0.5, every individual is - // called AA, and a scan built on those calls loses the signal - // (measured: 2.0e-01 where the same marker is 5.9e-07 from the - // BIMBAM; recoded, agreement with the calls is 209 of 209). - "genotypes": if crosstype != "riself" || het == Het::Keep { - serde_json::json!({"A": 1, "H": 2, "B": 3}) - } else { - serde_json::json!({"A": 1, "B": 2}) - }, - // Our own CSVs are markers-in-rows, individuals-in-columns. - "geno_transposed": true, - }); - std::fs::write(&control, control_json.to_string()).map_err(|e| io_error(&control, e))?; - // What the conversion discarded, kept beside the cross: a cached cross - // must be able to say how many calls it dropped. - let report = serde_json::json!({ - "het_dropped": het_dropped, - "cells": individuals.len() * markers, - }); - let report_path = directory.join("conversion.json"); - let _ = std::fs::write(&report_path, report.to_string()); - return Ok(PreparedCross { - control, - individuals: individuals.clone(), - markers, - non_autosomal, - crosstype: crosstype.to_string(), - het_dropped, - cells: individuals.len() * markers, - founders: 0, - multiparent: false, - }); } - // Cached: count what the conversion produced, without re-reading the - // panel. The marker counts come from the maps it wrote. - let markers = std::fs::read_to_string(directory.join("pmap.csv")) - .map_err(|e| io_error(&directory.join("pmap.csv"), e))? - .lines() - .filter(|line| !line.trim().is_empty()) - .count() - .saturating_sub(1); + // The script's report is the cross's own account of itself: what it + // dropped, and which individuals it holds. A cross converted before the + // report existed is measured once from the panel. let report_path = directory.join("conversion.json"); - let mut report: Value = std::fs::read_to_string(&report_path) + let report: Value = std::fs::read_to_string(&report_path) .ok() .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_else(|| serde_json::json!({})); - if report.get("het_dropped").is_none() { - // A cross converted before the count was kept: measure it once from the - // panel and record it beside the cross, so later replies are free. - let het_code = if crosstype == "riself" { - metadata_het(&text) - } else { - None - }; - let dropped = het_code - .as_deref() - .map(|code| count_calls(&text, code)) - .unwrap_or(0); - report = serde_json::json!({ - "het_dropped": dropped, - "cells": individuals.len() * markers, - }); - let _ = std::fs::write(&report_path, report.to_string()); + .ok_or_else(|| { + Qtl2Error::CommandFailed(format!( + "{} wrote no conversion report; can this convert {}?", + convert_script.display(), + geno.display() + )) + })?; + let want = |key: &str| report.get(key).and_then(Value::as_u64).unwrap_or(0) as usize; + let individuals: Vec = report + .get("individuals") + .and_then(Value::as_array) + .map(|names| { + names + .iter() + .filter_map(|name| name.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + if individuals.is_empty() { + return Err(Qtl2Error::Unsupported( + "the .geno header names no individuals".to_string(), + )); + } + let markers = want("markers"); + if markers == 0 { + return Err(Qtl2Error::Unsupported( + "the panel has no autosomal markers to scan".to_string(), + )); } - let het_dropped = report - .get("het_dropped") - .and_then(Value::as_u64) - .unwrap_or(0) as usize; - let cells = report.get("cells").and_then(Value::as_u64).unwrap_or(0) as usize; Ok(PreparedCross { control, individuals, markers, - non_autosomal: 0, + non_autosomal: want("non_autosomal"), crosstype: crosstype.to_string(), - het_dropped, - cells, + het_dropped: want("het_dropped"), + cells: want("cells"), founders: 0, multiparent: false, }) } -/// Find the control file of a cross named in a request. pub fn resolve_control_file(root: &Path, requested: &str) -> Result { let name = requested.trim(); if name.is_empty() { @@ -509,6 +360,13 @@ fn control_path(control: &Path, json: &Value, key: &str) -> Option { .map(|name| directory.join(name)) } +fn io_error(path: &Path, error: io::Error) -> Qtl2Error { + Qtl2Error::Io(io::Error::new( + error.kind(), + format!("{}: {error}", path.display()), + )) +} + /// The data lines of a CSV: comments and blank lines skipped, header dropped. fn data_lines(path: &Path, comment: &str) -> Result, Qtl2Error> { let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?; diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 31d5538..baf4d6d 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -997,6 +997,7 @@ async fn prepare_genotypes( let directory = config.genotype_files_dir.clone(); let cache = config.qtl2_cache_dir.clone(); let version = version.map(|v| v.to_string()); + let convert = config.qtl2_convert_script.clone(); let prepared = tokio::task::spawn_blocking(move || { let resolved = genotypes::resolve( std::path::Path::new(&directory), @@ -1007,8 +1008,13 @@ async fn prepare_genotypes( // Drop is the default genotype model: the heterozygous calls a // riset panel carries are exactly the ones the HMM is asked to // re-predict, so predicting from the kept calls would be circular. - qtl2::prepare_cross(&resolved, std::path::Path::new(&cache), qtl2::Het::Drop) - .map_err(|error| error.to_string()) + qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache), + qtl2::Het::Drop, + std::path::Path::new(&convert), + ) + .map_err(|error| error.to_string()) }) .await .map_err(|error| { diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index 896c0e9..bf2ba06 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -675,10 +675,14 @@ pub async fn compute_qtl2( let genotype_root = config.genotype_files_dir.clone(); let cache_dir_for_cross = cache_dir.clone(); let het_for_cross = het; + let convert_for_cross = config.qtl2_convert_script.clone(); let cross = tokio::task::spawn_blocking(move || match source_for_cross { - Source::Convert(resolved) => { - qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir_for_cross), het_for_cross) - } + Source::Convert(resolved) => qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache_dir_for_cross), + het_for_cross, + std::path::Path::new(&convert_for_cross), + ), Source::Control(name) => { qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name) } -- cgit 1.4.1 From f681a06b58879968e7b385e22d6c0560fa0588ba Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 14:53:57 +0000 Subject: docs: pangemma's store does hold gaps, so `impute` is optional for both engines Two places still said pangemma "cannot represent a gap at all" and that its store builder refuses impute=none -- written against an older pangemma. The store keeps them (NaN for Gf, 255 for Gb) and pangemma mean-substitutes per marker as GEMMA does: measured, impute=none through the pangemma engine answers 21,055 rows with `af` identical to GEMMA's on the same panel. What `impute` does change is which markers and individuals map, and it does so before the store is built, so each mode has its own store (they are different genotype files). Measured warm on BXD.8 trait 10001: none 21,055 rows, 20 chromosomes gemma 4.0 s pangemma 3.9 s hmm 20,453 rows, 19 chromosomes gemma 26.8 s pangemma 15.8 s mean 21,056 rows, 20 chromosomes gemma 16.3 s pangemma 16.0 s The hmm figures include the R/qtl2 imputation the first time and reuse it from RAVANAN_CACHE_DIR/imputed/ afterwards; mean maps one marker that complete-case treatment drops, which is why the three are not interchangeable answers. --- README.md | 11 +++++++++++ scripts/prepare-genotypes.sh | 7 ++++--- src/routes/gemma.rs | 15 ++++++++++++--- 3 files changed, 27 insertions(+), 6 deletions(-) (limited to 'scripts') diff --git a/README.md b/README.md index 6f80fc6..7ad2841 100644 --- a/README.md +++ b/README.md @@ -1837,6 +1837,17 @@ What changes underneath, all of it pinned by the deployment: sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller and exact only for integer calls. +`impute` is applied *before* the store is built, so every mode works with +either engine -- and each one gets its own store, since they are different +genotype files: on BXD.8, `none` 21,055 rows (the store keeps the gaps as +NaN and pangemma mean-substitutes them per marker as GEMMA does), `hmm` +20,453 rows over 19 chromosomes (autosomal markers only, and the R/qtl2 +imputation itself costs ~11 s the first time), `mean` 21,056 rows (a complete +file maps one marker that complete-case treatment drops). Measured warm: +`none` gemma 4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` +16.3 s / 16.0 s -- the first figure includes the imputation, the second +reuses it from the cache under `RAVANAN_CACHE_DIR/imputed/`. + **There is no fallback for this engine.** The in-process runner is gemma-wrapper on BIMBAM, so falling back would answer a different question under the requested engine's name: a pangemma request forces diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index 9624e0e..f26e8c7 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -3,9 +3,10 @@ # is decided, so the same question can be asked of every engine and the answers # compared. # -# --mode none leave the file as it is (GEMMA then does complete-case per -# marker and reports n_miss; pangemma cannot represent a gap at -# all, so its store builder refuses this mode) +# --mode none leave the file as it is: GEMMA then does complete-case per +# marker and reports n_miss, and pangemma's lmdb store keeps +# the gaps (NaN for Gf, 255 for Gb) and mean-substitutes them +# per marker exactly as GEMMA does # --mode mean replace each missing call by that marker's mean over the # individuals that have one (cheap, but it invents a datum and # deflates the variance) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index c36c1c2..5beb4db 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -129,9 +129,18 @@ pub struct GemmaRequest { /// per marker and reports `n_miss`), `mean` (each gap takes that marker's /// mean) or `hmm` (R/qtl2's HMM predicts it from flanking markers). The /// last two produce a complete genotype file, which is what a comparison - /// between engines needs: pangemma's LMDB store cannot hold a gap at all. - /// `hmm` needs a group-scoped request, since the cross it predicts from is - /// the group's. + /// between engines needs: a complete file maps one marker more than + /// complete-case treatment does (21,056 against 21,055 on BXD.8), so the + /// two modes are not interchangeable. `hmm` needs a group-scoped request, + /// since the cross it predicts from is the group's. + /// + /// Neither engine needs it: GEMMA does complete-case per marker, and + /// pangemma's store keeps the gaps (NaN for Gf, 255 for Gb) and + /// mean-substitutes them per marker as GEMMA does -- measured: `none` + /// answers 21,055 rows through pangemma with `af` identical to GEMMA's. + /// The mode is applied before the store is built, so each one gets its own + /// store (they are different genotype files) and an already-imputed panel + /// pays the store build once per mode. pub impute: Option, /// Which engine the per-chromosome workflow runs: `gemma` (default, /// gemma-gn2 on BIMBAM) or `pangemma` (the GeneNetwork fork reading an -- cgit 1.4.1 From 87314c6dbde26343d577423942d967b5acc37db5 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 15:49:41 +0000 Subject: docs: the HMM imputation is a modelling choice now, not a pangemma workaround The script's rationale still said pangemma "cannot represent a missing genotype (one NA makes the whole kinship matrix NaN, silently)" -- the third copy of a claim that stopped being true when pangemma learned to keep gaps in its GRM. It is worth keeping the history straight, because it is the reason the step exists at all: measure it, and `impute: none` through the pangemma engine answers the same rows and the same allele frequencies as GEMMA. What the script is for, then: the BIMBAM carries 0.1% unknown calls and the riself conversion R/qtl2 uses drops 12.7% (every heterozygous call), and a marker mean invents data where the HMM has a real prediction -- one that /compute/qtl2 maps on as well, so a GEMMA scan and a qtl2 scan over this file describe the same data. --- scripts/qtl2-impute-bimbam.R | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'scripts') diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index ae95b48..4d33d51 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -2,13 +2,21 @@ # qtl2-impute-bimbam.R -- write a BIMBAM genotype file from qtl2's HMM, so that # pangemma's mdb can be built from the same genotype calls /compute/qtl2 uses. # -# Why this exists: pangemma's LMDB path cannot represent a missing genotype -# (one NA makes the whole kinship matrix NaN, silently), while the BIMBAM the -# GEMMA path uses carries 0.1% unknown calls and the riself conversion used by -# R/qtl2 drops 12.7% (every heterozygous call). Filling those with a marker -# mean would be inventing data where there is a real prediction to be had, so -# the calls come from qtl2's HMM instead: `maxmarg` on the cached genotype -# probabilities, which predicts a missing call from its flanking markers. +# Why this exists: the BIMBAM the GEMMA path uses carries 0.1% unknown calls +# and the riself conversion used by R/qtl2 drops 12.7% (every heterozygous +# call). Filling those with a marker mean would be inventing data where there +# is a real prediction to be had, so the calls come from qtl2's HMM instead: +# `maxmarg` on the cached genotype probabilities, which predicts a missing call +# from its flanking markers -- and that is the call set /compute/qtl2 maps on, +# so a GEMMA scan and a qtl2 scan over this file describe the same data. +# +# It is not here because an engine cannot cope: an older pangemma could not +# hold a gap in its GRM (one NA made the whole kinship matrix NaN, silently), +# which is what introduced this step, but the current build keeps the gaps +# (NaN in a Gf store, 255 in a Gb one) and mean-substitutes them per marker as +# GEMMA does -- measured: `impute: none` through pangemma answers the same +# rows and the same allele frequencies as GEMMA. So this is a modelling +# choice, not a workaround. # # qtl2-impute-bimbam.R [minprob] # -- cgit 1.4.1 From 64f1268be9a06462fe9685107c949dbbad84212d Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 17:08:54 +0000 Subject: gemma: the genotype treatment and the lmdb store become workflow jobs Both used to run on the API host before ravanan was invoked, cached by two hand-rolled file keys -- one of which (the treatment) carried a version constant that had to be bumped whenever the script changed what it wrote, and the other (the store) keyed on a genotype file's path, size and mtime. As workflow jobs they are scheduled on the cluster and cached by ravanan on (script, inputs) like every other step, and both caches go away. They are *separate* workflows, not steps inside the mapping one, because ccwl's `pipe` is strictly linear: a step sees only the immediately preceding step's unconsumed outputs, and GWA needs the prepared genotypes *and* the kinship matrix -- a diamond ccwl cannot express (verified with a three-step probe; ravanan implements no CWL `when` either, so an optional step is not an option). So: cwl/gemma/prepare.scm mode + BIMBAM pair (+ cross, individuals) -> pair cwl/gemma/store.scm BIMBAM pair -> pangemma's lmdb store cwl/gemma/manifest-artifacts.scm bash, coreutils, gawk, r-minimal, r-qtl2, python, python-numpy, python-lmdb and the server chains them: prepare when `impute` is not `none`, store when the engine is pangemma, then the mapping workflow with the resulting paths. Ravanan sets the manifest profile's search paths inside the job, so python3 there finds numpy and lmdb without the PYTHONPATH the API host needs. Measured warm on BXD.8 trait 10001 (gemma / pangemma, rows): none 21055 3.9 s / 10.3 s mean 21056 10.5 s / 16.5 s hmm 20453 10.2 s / 16.5 s Against 26.8 s for hmm through the host-side path before this. Three things had to be right that were not: - A step input cannot be optional here, so `cross` and `individuals_file` are always passed -- an empty directory and an empty file for the modes that ignore them. - `cross` is a *path*, not a CWL Directory: ravanan's slurm-api backend does not stage a Directory input (the staged path reached the job and R's setwd failed; the same workflow under single-machine succeeded), so the server copies the cross under its cache directory, which the nodes can see. - `scripts/prepare-genotypes.sh --out` is now absolutized before use, because qtl2-impute-bimbam.R does setwd(cross_dir) and writes .* from there: a relative prefix put the outputs inside the cross directory and the job's output globs matched nothing. It also grew --impute-script (a staged script is not beside its companion) and always writes .individuals.txt, since the caller needs the HMM's individual order to align trait values. Also: a request that asked for a treatment no longer falls back to the in-process wrapper when the Slurm route fails. The wrapper reads genotypes as they stand, so falling back on `impute: hmm` answered 21,055 rows where the request meant 20,453 -- a wrong answer under a "degraded" note. Treated requests (and pangemma ones) now fail instead. And ravanan's output may be one File or an array of them: a scattered step reports an array, a single-step workflow one File, which is what "no store array in ravanan's output" was. Deployed and verified on the production instance: all six engine x mode combinations answer 200 with the expected row counts, and bin/monitor-gn4 --tier all is 50 ok / 0 failed. --- README.md | 25 +- cwl/gemma/manifest-artifacts.scm | 25 ++ cwl/gemma/prepare.scm | 77 +++++ cwl/gemma/store.scm | 35 ++ docs/ravanan-slurm.md | 7 +- scripts/prepare-genotypes.sh | 38 ++- src/config.rs | 66 +++- src/gemma.rs | 303 +++++++++-------- src/routes/gemma.rs | 711 +++++++++++++++++++++++---------------- 9 files changed, 816 insertions(+), 471 deletions(-) create mode 100644 cwl/gemma/manifest-artifacts.scm create mode 100644 cwl/gemma/prepare.scm create mode 100644 cwl/gemma/store.scm (limited to 'scripts') diff --git a/README.md b/README.md index 7ad2841..5c2cda6 100644 --- a/README.md +++ b/README.md @@ -1837,16 +1837,21 @@ What changes underneath, all of it pinned by the deployment: sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller and exact only for integer calls. -`impute` is applied *before* the store is built, so every mode works with -either engine -- and each one gets its own store, since they are different -genotype files: on BXD.8, `none` 21,055 rows (the store keeps the gaps as -NaN and pangemma mean-substitutes them per marker as GEMMA does), `hmm` -20,453 rows over 19 chromosomes (autosomal markers only, and the R/qtl2 -imputation itself costs ~11 s the first time), `mean` 21,056 rows (a complete -file maps one marker that complete-case treatment drops). Measured warm: -`none` gemma 4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` -16.3 s / 16.0 s -- the first figure includes the imputation, the second -reuses it from the cache under `RAVANAN_CACHE_DIR/imputed/`. +`impute` is a *workflow of its own* on this path (`cwl/gemma/prepare.scm`), +one job that writes the prepared BIMBAM pair, cached by ravanan on +(script, inputs) so the treatment runs once per (panel, mode) however many +traits follow; `none` is the same step with nothing to do (a copy). It is a +separate workflow rather than a step inside this one because ccwl's `pipe` is +linear: the GWA step needs the prepared genotypes *and* the kinship matrix, +and a step sees only the immediately preceding step's outputs. pangemma's +lmdb store is a second such workflow (`cwl/gemma/store.scm`). + +Each mode is its own genotype file and therefore its own store: on BXD.8, +`none` 21,055 rows (the store keeps the gaps as NaN and pangemma +mean-substitutes them per marker as GEMMA does), `hmm` 20,453 rows over 19 +chromosomes (autosomal markers only), `mean` 21,056 rows (a complete file maps +one marker that complete-case treatment drops). Measured warm: `none` gemma +4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` 16.3 s / 16.0 s. **There is no fallback for this engine.** The in-process runner is gemma-wrapper on BIMBAM, so falling back would answer a different diff --git a/cwl/gemma/manifest-artifacts.scm b/cwl/gemma/manifest-artifacts.scm new file mode 100644 index 0000000..8a8eb07 --- /dev/null +++ b/cwl/gemma/manifest-artifacts.scm @@ -0,0 +1,25 @@ +;; Guix manifest for the artifact workflows -- prepare.scm (the +;; missing-genotype treatment) and store.scm (BIMBAM to pangemma's lmdb) -- as +;; resolved by ravanan's --guix-manifest. They are separate from manifest.scm / +;; manifest-mdb.scm because their jobs need a different toolchain than the +;; mapping steps do, and because ravanan builds one profile per workflow: a +;; mapping job has no business carrying R and numpy. +;; +;; bash + gawk + coreutils: prepare-genotypes.sh is `sh' with an awk one-liner +;; for `mean' and a cp for `none'. +;; r-minimal + r-qtl2: `hmm' runs qtl2-impute-bimbam.R (maxmarg on the cross's +;; genotype probabilities). r-qtl2 propagates r-qtl, r-rcpp, r-jsonlite and +;; r-data-table, so nothing else is listed. +;; python + python-numpy + python-lmdb: geno2mdb.py, which writes the store. +;; +;; ravanan sets these packages' search paths (PYTHONPATH among them) inside the +;; job, so `python3' here finds numpy and lmdb without any wrapper script -- +;; measured, after the API host needed PYTHONPATH exported by hand for the same +;; script (see the deployment's env.sh). +;; +;; A manifest change must be followed by a cold run: ravanan keys a step on +;; (script, inputs), so an old job with an old profile would be reused +;; silently. +(specifications->manifest + (list "bash" "coreutils" "gawk" "r-minimal" "r-qtl2" + "python" "python-numpy" "python-lmdb")) diff --git a/cwl/gemma/prepare.scm b/cwl/gemma/prepare.scm new file mode 100644 index 0000000..1de4d68 --- /dev/null +++ b/cwl/gemma/prepare.scm @@ -0,0 +1,77 @@ +;; The missing-genotype treatment as a workflow of its own: one job that turns +;; the panel's BIMBAM pair into the pair the mapping steps read, by mode -- +;; `none' copies, `mean' substitutes each marker's mean, `hmm' predicts from +;; flanking markers with R/qtl2 (scripts/prepare-genotypes.sh dispatches on +;; --mode, so one step serves all three and no CWL conditional is needed; +;; ravanan implements no `when' and ccwl cannot emit one). +;; +;; WHY A SEPARATE WORKFLOW and not a step inside gemma-loco.scm: the GWA step +;; needs both the prepared genotypes AND the kinship matrix, and ccwl's `pipe' +;; is strictly linear -- each step sees only the immediately preceding step's +;; unconsumed outputs, so a diamond cannot be written in it. Chaining two +;; workflows is what a diamond becomes, and ravanan caches each of them on +;; (script, inputs), so the treatment runs once per (panel, mode) however many +;; traits are mapped afterwards. Cost of the split: one more ravanan invocation +;; per cold request, and interned copies of the pair in the store. +;; +;; Before this, the same script ran on the API host before ravanan was invoked, +;; and its output was cached by a hand-rolled file key whose version constant +;; had to be bumped whenever the script changed what it wrote. +;; +;; `cross' and `individuals_file' are read only for `hmm'; the caller sends an +;; empty directory and an empty file otherwise, since a step input cannot be +;; optional here and a qtl2 cross per request would be work nobody asked for. +;; +;; Written in ccwl; see gemma-loco.scm's header for how it is compiled. +(define prepare + (command + #:inputs (mode #:type string) + (prepare_script #:type File) + (impute_script #:type File) + (raw_genotype_file #:type File) + (raw_snps_file #:type File) + ;; A path, not a Directory: ravanan's slurm-api backend does not stage a + ;; Directory input onto the node (measured: the job ran with the staged path + ;; in its argv and R's setwd failed, while the same workflow under + ;; single-machine succeeded). The caller copies the cross under its own + ;; cache directory, which is on the share the nodes see, and passes that path. + (cross #:type string) + (individuals_file #:type File) + ;; Commands come from the manifest (manifest-artifacts.scm): bash, awk and + ;; R/qtl2 live there, while the two scripts are staged inputs -- so a compute + ;; node needs nothing from the checkout. + #:run "bash" prepare_script + ("--mode" mode) + ("--geno" raw_genotype_file) + ("--snps" raw_snps_file) + ("--out" "prepared") + ("--impute-script" impute_script) + ("--cross" cross) + ("--probs" "-") + ("--individuals-file" individuals_file) + #:outputs (genotype_file #:type File + #:binding ((glob . "prepared.bimbam.txt"))) + (snps_file #:type File + #:binding ((glob . "prepared.snps.txt"))) + ;; The individual order of the file it wrote. BIMBAM carries none, and the + ;; `hmm' calls come from the cross, whose order is its own -- so the caller + ;; needs this to line the trait values up with the genotypes. + (individuals_file #:type File + #:binding ((glob . "prepared.individuals.txt"))))) + +(workflow ((mode #:type string) + (prepare_script #:type File) + (impute_script #:type File) + (genotype_file #:type File) + (snps_file #:type File) + ;; A path under the caller's cache directory (on the share): see the + ;; step's note on why this is not a Directory input. + (cross #:type string) + (individuals_file #:type File)) + (prepare #:mode mode + #:prepare_script prepare_script + #:impute_script impute_script + #:raw_genotype_file genotype_file + #:raw_snps_file snps_file + #:cross cross + #:individuals_file individuals_file)) diff --git a/cwl/gemma/store.scm b/cwl/gemma/store.scm new file mode 100644 index 0000000..6a60628 --- /dev/null +++ b/cwl/gemma/store.scm @@ -0,0 +1,35 @@ +;; The lmdb genotype store pangemma reads with `-g', built from a BIMBAM pair by +;; gemma-wrapper's bin/geno2mdb.py. A workflow of its own for the same reason +;; gemma-loco-mdb.scm's steps are separate (see prepare.scm): the mapping +;; workflow takes the store as an input, and ravanan caches this build on +;; (script, inputs), so a panel's store is built once however many traits are +;; mapped over it. +;; +;; The store is what makes pangemma cheap at scale -- its keys carry the +;; chromosome, so a scan neither parses BIMBAM again per job nor needs the `-a' +;; annotation -- and it is also the expensive artifact: 22 MB for BXD.8, minutes +;; for HLC. Before this it was built on the API host into a +;; GEMMA_LMDB_CACHE_DIR keyed by the genotype file's path, size and mtime; as a +;; workflow it is keyed the way every other step is. +;; +;; Gf always: one little-endian float32 per sample, missing as NaN. Exact for a +;; mean-genotype panel (0, 0.5, 1 all fit in a float32), where Gb is 4x smaller +;; but exact only for integer calls (0/1/2 -> 0/127/254). +(define store + (command + #:inputs (store_script #:type File) + (genotype_file #:type File) + (snps_file #:type File) + #:run "python3" store_script genotype_file + ("--snps" snps_file) + ("--format" "Gf") + ("--out" "genotypes.mdb") + #:outputs (store #:type File + #:binding ((glob . "genotypes.mdb"))))) + +(workflow ((store_script #:type File) + (genotype_file #:type File) + (snps_file #:type File)) + (store #:store_script store_script + #:genotype_file genotype_file + #:snps_file snps_file)) diff --git a/docs/ravanan-slurm.md b/docs/ravanan-slurm.md index 616e924..ba715f3 100644 --- a/docs/ravanan-slurm.md +++ b/docs/ravanan-slurm.md @@ -30,8 +30,11 @@ backend): …`). | `RAVANAN_CACHE_DIR` | where pheno files, logs, the compiled CWL and ravanan's `--store` live | | `GEMMA_RAVANAN_WORKFLOW_MDB` | ccwl source for `"engine": "pangemma"` (default `cwl/gemma/gemma-loco-mdb.scm`) | | `GEMMA_RAVANAN_MANIFEST_MDB` | manifest naming `pangemma-git` for that workflow (default `cwl/gemma/manifest-mdb.scm`); a manifest change needs a cold run, since ravanan keys a step on (script, inputs) | -| `GENO2MDB_CMD` | the lmdb store builder (`geno2mdb.py` from gemma-wrapper's `bin/` -- it is not on `PATH` in every deployment) | -| `GEMMA_LMDB_CACHE_DIR` | where built lmdb stores live, one per genotype file; **must be durable**, since rebuilding one is the expensive part of a pangemma run | +| `GENO2MDB_CMD` | the lmdb store builder (`geno2mdb.py` from gemma-wrapper's `bin/`), staged into the store workflow as a `File` input | +| `GEMMA_PREPARE_WORKFLOW` | ccwl source of the missing-genotype treatment (default `cwl/gemma/prepare.scm`), run as its own job before the mapping workflow | +| `GEMMA_STORE_WORKFLOW` | ccwl source that builds pangemma's lmdb store (default `cwl/gemma/store.scm`) | +| `GEMMA_ARTIFACTS_MANIFEST` | manifest for both of those jobs (default `cwl/gemma/manifest-artifacts.scm`: bash, gawk, R/qtl2, python, numpy, lmdb) -- a different toolchain from the mapping steps, and ravanan builds one profile per workflow | +| `IMPUTE_SCRIPT` | `scripts/qtl2-impute-bimbam.R`, staged into the prepare job | Selecting slurm without an endpoint or a JWT file is a startup error (fail closed, like `GN4_DB_MODE`): ravanan would fail every step, and a diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index f26e8c7..e6042a5 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -17,13 +17,22 @@ # scripts/prepare-genotypes.sh --mode mean|hmm|none \ # --geno --snps --out \ # [--cross ] [--probs ] [--minprob N] \ -# [--individuals-file ] +# [--individuals-file ] \ +# [--impute-script ] +# +# A workflow job stages this script and the R one as separate inputs, so +# --impute-script is how it says where the R script landed; by hand it +# defaults to the file beside this one. # # Writes .bimbam.txt and .snps.txt and prints the prefix. # Exits 2 on bad arguments, 1 when a step fails. set -eu mode= geno= snps= out= cross_dir= probs= minprob=0 individuals_file= +# The HMM script normally sits beside this one. A caller that stages this +# script somewhere else (a workflow job, where it is a copied input and the R +# script is a second one) names it explicitly. +impute_script= while [ $# -gt 0 ]; do case $1 in --mode) mode=$2; shift 2 ;; @@ -34,6 +43,7 @@ while [ $# -gt 0 ]; do --probs) probs=$2; shift 2 ;; --minprob) minprob=$2; shift 2 ;; --individuals-file) individuals_file=$2; shift 2 ;; + --impute-script) impute_script=$2; shift 2 ;; -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; esac @@ -41,6 +51,15 @@ done case $mode in none|mean|hmm) ;; *) echo "prepare-genotypes.sh: --mode must be none, mean or hmm" >&2; exit 2 ;; esac [ -n "$out" ] || { echo "prepare-genotypes.sh: --out is required" >&2; exit 2; } +# Absolute, before anything moves: the HMM script does setwd(cross_dir) and +# writes .* from there, so a relative prefix would put the outputs in +# the cross directory instead of the caller's -- which in a workflow job is the +# difference between the step's output globs matching and not (measured: the +# job answered "Type File mismatch for globbed paths"). +case $out in +/*) ;; +*) out=$(pwd)/$out ;; +esac mkdir -p "$(dirname "$out")" case $mode in @@ -68,7 +87,8 @@ hmm) { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } # R's own complaint last, so a caller that reports the final stderr line # reports the cause rather than our wrapper sentence. - if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + [ -n "$impute_script" ] || impute_script="$(dirname "$0")/qtl2-impute-bimbam.R" + if ! r_output=$("$RSCRIPT" "$impute_script" \ "$cross_dir" "${probs:--}" "$out" "$minprob" "$individuals_file" 2>&1); then echo "prepare-genotypes.sh: HMM imputation failed:" >&2 printf '%s\n' "$r_output" | tail -6 >&2 @@ -77,4 +97,18 @@ hmm) ;; esac +case $mode in +hmm) + # The R script writes .individuals.txt itself: the HMM calls come + # from the cross, whose individual order is its own, and the caller aligns + # the trait values to that order. + ;; +*) + # The other modes keep the panel's order, so the caller's list is the + # answer -- copied rather than re-derived, because a BIMBAM file does not + # carry individual names at all. + [ -n "$individuals_file" ] && cp "$individuals_file" "$out.individuals.txt" + ;; +esac + printf '%s\n' "$out" diff --git a/src/config.rs b/src/config.rs index 849b30a..e029969 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,16 +119,30 @@ pub struct Config { /// naming `pangemma-git` rather than `gemma-gn2` /// (GEMMA_RAVANAN_MANIFEST_MDB). pub gemma_ravanan_manifest_mdb: String, + /// The R script the `hmm` treatment runs (`IMPUTE_SCRIPT`, + /// scripts/qtl2-impute-bimbam.R), passed to the prepare workflow as a + /// staged input so a compute node needs nothing from the checkout. + pub impute_script: String, /// The lmdb store builder `geno2mdb.py` (in gemma-wrapper's bin/, /// which is not on PATH in every deployment): turns a BIMBAM /// genotype file plus its annotation into the store pangemma reads. /// Set via GENO2MDB_CMD. pub geno2mdb_cmd: String, - /// Where those stores are kept, one file per genotype file - /// (`GEMMA_LMDB_CACHE_DIR`). They are the expensive part of a - /// pangemma run -- built once, reused by every trait over the same - /// panel -- so a deployment must point this somewhere durable. - pub gemma_lmdb_cache_dir: String, + /// The workflow that applies the missing-genotype treatment + /// (`GEMMA_PREPARE_WORKFLOW`, cwl/gemma/prepare.scm): one cluster job + /// that writes the prepared BIMBAM pair, cached by ravanan on + /// (script, inputs) so the treatment runs once per (panel, mode). + pub gemma_prepare_workflow: String, + /// The workflow that builds pangemma's lmdb store + /// (`GEMMA_STORE_WORKFLOW`, cwl/gemma/store.scm), cached the same way + /// -- the store is the expensive artifact of a pangemma run (22 MB for + /// BXD.8, minutes for HLC), so it is built once per panel. + pub gemma_store_workflow: String, + /// The manifest those two workflows' jobs resolve their commands + /// against (`GEMMA_ARTIFACTS_MANIFEST`): bash, awk, R/qtl2, python, + /// numpy and lmdb -- a different toolchain from the mapping steps', + /// and ravanan builds one profile per workflow. + pub gemma_artifacts_manifest: String, /// Directory POST /compute/gemma/ravanan uses for phenotype files, /// run logs, and ravanan's own --store and --output-directory. /// Separate from `gemma_cache_dir` so the two runners don't share @@ -356,13 +370,22 @@ impl Config { "GEMMA_RAVANAN_MANIFEST_MDB".to_string(), "cwl/gemma/manifest-mdb.scm".to_string(), ); + values.insert( + "IMPUTE_SCRIPT".to_string(), + "scripts/qtl2-impute-bimbam.R".to_string(), + ); values.insert("GENO2MDB_CMD".to_string(), "geno2mdb.py".to_string()); values.insert( - "GEMMA_LMDB_CACHE_DIR".to_string(), - std::env::temp_dir() - .join("gn4-gemma-lmdb") - .to_string_lossy() - .into_owned(), + "GEMMA_PREPARE_WORKFLOW".to_string(), + "cwl/gemma/prepare.scm".to_string(), + ); + values.insert( + "GEMMA_STORE_WORKFLOW".to_string(), + "cwl/gemma/store.scm".to_string(), + ); + values.insert( + "GEMMA_ARTIFACTS_MANIFEST".to_string(), + "cwl/gemma/manifest-artifacts.scm".to_string(), ); values.insert( "RAVANAN_CACHE_DIR".to_string(), @@ -546,8 +569,11 @@ impl Config { "GEMMA_RAVANAN_WORKFLOW", "GEMMA_RAVANAN_WORKFLOW_MDB", "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", "GENO2MDB_CMD", - "GEMMA_LMDB_CACHE_DIR", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -620,8 +646,11 @@ impl Config { gemma_ravanan_manifest: values["GEMMA_RAVANAN_MANIFEST"].clone(), gemma_ravanan_workflow_mdb: values["GEMMA_RAVANAN_WORKFLOW_MDB"].clone(), gemma_ravanan_manifest_mdb: values["GEMMA_RAVANAN_MANIFEST_MDB"].clone(), + impute_script: values["IMPUTE_SCRIPT"].clone(), geno2mdb_cmd: values["GENO2MDB_CMD"].clone(), - gemma_lmdb_cache_dir: values["GEMMA_LMDB_CACHE_DIR"].clone(), + gemma_prepare_workflow: values["GEMMA_PREPARE_WORKFLOW"].clone(), + gemma_store_workflow: values["GEMMA_STORE_WORKFLOW"].clone(), + gemma_artifacts_manifest: values["GEMMA_ARTIFACTS_MANIFEST"].clone(), ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), gemma_engine: values["GEMMA_ENGINE"].clone(), @@ -910,8 +939,11 @@ mod tests { "GEMMA_RAVANAN_WORKFLOW", "GEMMA_RAVANAN_WORKFLOW_MDB", "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", "GENO2MDB_CMD", - "GEMMA_LMDB_CACHE_DIR", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -963,8 +995,14 @@ mod tests { config.gemma_ravanan_manifest_mdb, "cwl/gemma/manifest-mdb.scm" ); + assert_eq!(config.impute_script, "scripts/qtl2-impute-bimbam.R"); assert_eq!(config.geno2mdb_cmd, "geno2mdb.py"); - assert!(config.gemma_lmdb_cache_dir.ends_with("gn4-gemma-lmdb")); + assert_eq!(config.gemma_prepare_workflow, "cwl/gemma/prepare.scm"); + assert_eq!(config.gemma_store_workflow, "cwl/gemma/store.scm"); + assert_eq!( + config.gemma_artifacts_manifest, + "cwl/gemma/manifest-artifacts.scm" + ); assert!(config.ravanan_cache_dir.ends_with("gn4-gemma-ravanan")); assert_eq!(config.rqtl_wrapper_path, "scripts/rqtl_wrapper.R"); assert!(config.rqtl_cache_dir.ends_with("gn4-rqtl")); diff --git a/src/gemma.rs b/src/gemma.rs index e9f6a60..5d2d173 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -13,7 +13,7 @@ //! shared infrastructure; see `crate::streaming`. use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Output; use serde_json::Value; @@ -1037,10 +1037,23 @@ pub async fn compute( /// `{"": [{"class": "File", "path": ..., ...}, ...], ...}`, /// one entry per `cwl/gemma/gemma-loco.scm` chromosome). fn ravanan_output_paths<'a>(outputs: &'a Value, id: &str) -> Result, GemmaError> { - let files = outputs - .get(id) - .and_then(Value::as_array) - .ok_or_else(|| GemmaError::RavananOutput(format!("no \"{id}\" array in ravanan's output")))?; + let Some(value) = outputs.get(id) else { + return Err(GemmaError::RavananOutput(format!( + "no \"{id}\" in ravanan's output" + ))); + }; + // A scattered step's output is an array of Files; a single-step workflow's + // is one File object. Both are outputs here -- the mapping workflows + // scatter over chromosomes, the artifact ones (prepare, store) do not. + let files: Vec<&Value> = match value { + Value::Array(items) => items.iter().collect(), + Value::Object(_) => vec![value], + _ => { + return Err(GemmaError::RavananOutput(format!( + "\"{id}\" in ravanan's output is neither a File nor an array of them" + ))) + } + }; files .iter() .map(|file| { @@ -1185,7 +1198,7 @@ fn check_workflow_inputs(compiled_path: &Path, supplied: &[&str]) -> Result<(), /// file, interned verbatim into ravanan's store). The SNP file is hashed, /// because the chromosome list -- and therefore the whole scatter -- comes /// from it. -fn sha16(material: &[u8]) -> String { +pub fn sha16(material: &[u8]) -> String { crate::indexer::sha256::hex_digest(material)[..16].to_string() } @@ -1286,7 +1299,7 @@ fn chromosomes_from(contents: &str) -> Vec { /// genotypes: `gemma` parses BIMBAM text every invocation and needs the /// `-a` annotation to know which markers to leave out, while `pangemma` /// reads an lmdb store whose keys carry the chromosome, so it needs neither. -/// The store is built once per panel (see [`lmdb_store`]) and is what makes +/// The store is built once per panel (see cwl/gemma/store.scm) and is what makes /// pangemma cheaper at scale -- measured on HLC (358,454 markers): 141 s of /// cluster job time against 958 s for gemma on BIMBAM. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1347,125 +1360,131 @@ impl GemmaEngine { /// The per-chromosome workflow to run and the engine behind it: what a /// deployment pins in `GEMMA_RAVANAN_WORKFLOW`/`_MANIFEST` (gemma) and their -/// `_MDB` twins (pangemma), plus what pangemma needs to build its store. +/// `_MDB` twins (pangemma). pub struct RavananWorkflow<'a> { pub engine: GemmaEngine, /// The ccwl source compiled to CWL before every run. pub source: &'a str, /// The Guix manifest ravanan resolves the steps' commands against. pub manifest: &'a str, - /// `geno2mdb.py`, used only by the pangemma engine. - pub geno2mdb: &'a str, - /// Where built lmdb stores live, one per genotype file. - pub lmdb_cache_dir: &'a str, } -/// A key for one genotype file's lmdb store: path, size and mtime plus the -/// annotation's contents and the store format. +/// What running an artifact workflow needs: the ccwl source, the manifest its +/// jobs resolve against, ravanan's own switches, and the outputs wanted. /// -/// Not the genotype *contents*: a 200 MB BIMBAM file is not hashed on every -/// request (the same reason `kinship_input_key` uses path and size). The -/// mtime is what catches an in-place rewrite, which size alone would miss -/// when a prepared file is regenerated with the same byte count. -fn lmdb_store_key(genotype_file: &str, snps_file: &str) -> String { - let mut material = Vec::new(); - material.extend_from_slice(genotype_file.as_bytes()); - material.push(0); - if let Ok(metadata) = std::fs::metadata(genotype_file) { - material.extend_from_slice(&metadata.len().to_le_bytes()); - if let Ok(modified) = metadata.modified() { - if let Ok(since) = modified.duration_since(std::time::UNIX_EPOCH) { - material.extend_from_slice(&since.as_nanos().to_le_bytes()); - } - } - } - material.push(0); - if let Ok(snps) = std::fs::read(snps_file) { - material.extend_from_slice(&snps); - } - material.push(0); - // Gf: one float32 per sample, exact for a mean-genotype panel (0, 0.5, 1 - // all fit). Gb is 4x smaller but exact only for integer calls, where it - // would move p-values in the third decimal. - material.extend_from_slice(b"Gf"); - sha16(&material) +/// The two artifacts -- the missing-genotype treatment (`prepare.scm`) and +/// pangemma's lmdb store (`store.scm`) -- are workflows of their own rather +/// than steps inside the mapping workflows, because ccwl's `pipe` is linear: +/// the GWA step needs the prepared genotypes *and* the kinship matrix, and a +/// step sees only the immediately preceding step's outputs. Chaining +/// workflows is what that diamond becomes; ravanan caches each of them on +/// (script, inputs), so each artifact is still built once. +pub struct ArtifactWorkflow<'a> { + /// "prepare" or "store", for the compiled artifact's name and for errors. + pub label: &'a str, + pub ccwl_cmd: &'a str, + pub ravanan_cmd: &'a str, + pub batch: &'a crate::config::RavananBatch, + pub source: &'a str, + pub manifest: &'a str, + pub cache_dir: &'a str, + pub scratch_dir: &'a str, } -/// Build (or reuse) the lmdb genotype store pangemma reads with `-g`. +/// Run one artifact workflow and return its outputs by id. /// -/// One store per genotype file, not per trait: the store holds the panel's -/// markers and samples, and pangemma does GEMMA's own per-marker -/// mean-substitution at run time, so every trait over the panel shares it and -/// a repeat request costs one `stat`. -/// -/// Written aside and renamed, so a concurrent identical request sees either no -/// store or a complete one; two simultaneous first-runs both build it, which -/// the rename makes harmless rather than wrong. -async fn lmdb_store( - cmd: &str, - cache_dir: &str, - genotype_file: &str, - snps_file: &str, -) -> Result<(PathBuf, String), GemmaError> { - std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; - let key = lmdb_store_key(genotype_file, snps_file); - let stem = Path::new(genotype_file) - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| "genotypes".to_string()); - let store_path = Path::new(cache_dir).join(format!("{stem}-{key}.mdb")); - if store_path.is_file() { - return Ok(( - store_path.clone(), - format!( - "pangemma's lmdb genotype store was already built ({})", - store_path.display() - ), +/// The inputs YAML's own hash names the staged file, so two concurrent +/// identical requests share one and different ones cannot collide -- the same +/// convention the mapping workflow uses for its phenotype files. +pub async fn run_artifact( + run: &ArtifactWorkflow<'_>, + supplied: &[&str], + inputs_yaml: &str, + output_ids: &[&str], +) -> Result)>, GemmaError> { + std::fs::create_dir_all(run.cache_dir).map_err(GemmaError::Io)?; + let workflow = workflow_key(run.source); + let compiled_path = Path::new(run.cache_dir).join(format!("{workflow}-{}.cwl", run.label)); + let compiled_tmp = Path::new(run.cache_dir) + .join(format!("{workflow}-{}.tmp-{}.cwl", run.label, std::process::id())); + let ccwl_output_arg = format!("--output={}", compiled_tmp.display()); + let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), run.source]; + let ccwl_output = streaming::run_streaming(run.ccwl_cmd, &ccwl_args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ccwl_cmd.to_string(), + error, + })?; + if !ccwl_output.status.success() { + return Err(GemmaError::CommandFailed { + step: "ccwl compile", + stderr: String::from_utf8_lossy(&ccwl_output.stderr).into_owned(), + }); + } + std::fs::rename(&compiled_tmp, &compiled_path).map_err(GemmaError::Io)?; + check_workflow_inputs(&compiled_path, supplied)?; + + let key = sha16(inputs_yaml.as_bytes()); + let inputs_path = + Path::new(run.cache_dir).join(format!("{key}-{}-inputs.yaml", run.label)); + if !inputs_path.is_file() { + let inputs_tmp = Path::new(run.cache_dir).join(format!( + "{key}-{}-inputs.tmp-{}.yaml", + run.label, + std::process::id() )); + std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?; + std::fs::rename(&inputs_tmp, &inputs_path).map_err(GemmaError::Io)?; } - let tmp_path = Path::new(cache_dir).join(format!( - "{stem}-{key}.tmp-{}.mdb", - std::process::id() - )); - let _ = std::fs::remove_file(&tmp_path); - let tmp_arg = tmp_path.to_string_lossy().into_owned(); - let args = [ - genotype_file, - "--snps", - snps_file, - "--format", - "Gf", - "--out", - tmp_arg.as_str(), + let store_dir = Path::new(run.cache_dir).join("ravanan-store"); + for subdir in ["files", "logs", "data"] { + std::fs::create_dir_all(store_dir.join(subdir)).map_err(GemmaError::Io)?; + } + let scratch = if run.scratch_dir.is_empty() { + run.cache_dir + } else { + run.scratch_dir + }; + let store_arg = format!("--store={}", store_dir.display()); + let manifest_arg = format!("--guix-manifest={}", run.manifest); + let compiled_arg = compiled_path.to_string_lossy().into_owned(); + let inputs_arg = inputs_path.to_string_lossy().into_owned(); + let mut args = vec![ + store_arg.as_str(), + manifest_arg.as_str(), + compiled_arg.as_str(), + inputs_arg.as_str(), ]; - let output = streaming::run_streaming(cmd, &args, None) + let batch_args = run.batch.ravanan_args(scratch); + args.extend(batch_args.iter().map(String::as_str)); + let output = streaming::run_streaming(run.ravanan_cmd, &args, None) .await .map_err(|error| GemmaError::Spawn { - command: cmd.to_string(), + command: run.ravanan_cmd.to_string(), error, })?; if !output.status.success() { - let _ = std::fs::remove_file(&tmp_path); - return Err(GemmaError::CommandFailed { - step: "geno2mdb", - stderr: format!( - "{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ), - }); + return Err(GemmaError::RavananFailed(format!( + "{} ({})", + run.label, + String::from_utf8_lossy(&output.stderr) + ))); } - std::fs::rename(&tmp_path, &store_path).map_err(GemmaError::Io)?; - // lmdb leaves a `-lock` companion beside the temporary name. - let _ = std::fs::remove_file(tmp_path.with_extension("mdb-lock")); - Ok(( - store_path.clone(), - format!( - "pangemma's lmdb genotype store was built from {genotype_file} ({})", - store_path.display() - ), - )) + let outputs: Value = serde_json::from_str(&String::from_utf8_lossy(&output.stdout)) + .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?; + let mut found = Vec::new(); + for id in output_ids { + let paths = ravanan_output_paths(&outputs, id)?; + if paths.is_empty() { + return Err(GemmaError::WrapperError { + step: "artifact workflow", + detail: format!("{} produced no '{id}'", run.label), + }); + } + found.push((id.to_string(), paths.into_iter().map(str::to_string).collect())); + } + Ok(found) } /// The ravanan inputs YAML for one engine: same fields the workflow declares, @@ -1525,6 +1544,8 @@ pub async fn compute_ravanan( batch: &crate::config::RavananBatch, ccwl_cmd: &str, workflow: &RavananWorkflow<'_>, + // pangemma only: the lmdb store built by the store workflow. + store: Option<&str>, cache_dir: &str, scratch_dir: &str, genotype_file: &str, @@ -1621,22 +1642,13 @@ pub async fn compute_ravanan( .collect::>() .join(", "); - // pangemma reads an lmdb store instead of BIMBAM plus its annotation, so - // that store has to exist before anything is staged -- and it is the one - // expensive input, built once per genotype file rather than per trait. - let (store_path, store_note) = match engine { - GemmaEngine::Gemma => (None, None), - GemmaEngine::Pangemma => { - let (path, note) = lmdb_store( - workflow.geno2mdb, - workflow.lmdb_cache_dir, - genotype_file, - snps_file, - ) - .await?; - (Some(path), Some(note)) - } - }; + // pangemma reads an lmdb store instead of BIMBAM plus its annotation; the + // caller has already had it built (cwl/gemma/store.scm), and ravanan's + // store holds it, so this is just the path. + let store_path = store.map(Path::new); + let store_note = store_path.map(|path| { + format!("pangemma's lmdb genotype store: {}", path.display()) + }); let inputs_yaml_path = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.yaml")); let inputs_tmp = @@ -1645,7 +1657,7 @@ pub async fn compute_ravanan( engine, genotype_file, snps_file, - store_path.as_deref(), + store_path, &pheno_path, &kinship_pheno_path, lmm, @@ -1699,13 +1711,11 @@ pub async fn compute_ravanan( // cannot say which cost its caller what. let engine_note = match (&store_note, engine) { (Some(note), _) => Some(format!( - "Engine: {} (lmdb genotypes rather than BIMBAM): {note}", + "Engine: {} reads its genotypes from an lmdb store rather than BIMBAM ({note})", engine.as_str() )), + (None, GemmaEngine::Pangemma) => None, (None, GemmaEngine::Gemma) => None, - (None, GemmaEngine::Pangemma) => { - Some(format!("Engine: {}", engine.as_str())) - } }; let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref()) @@ -2364,25 +2374,30 @@ mod engine_tests { assert!(!pangemma.contains("snps_file")); } - /// A store belongs to a genotype file, not to a trait: every trait over - /// the panel must reuse it, or the expensive half of a pangemma run is - /// paid again per request. The annotation is part of the key because it - /// decides which markers and chromosomes the store holds. + /// ravanan reports a scattered step's output as an array of Files and a + /// single-step workflow's as one File. Both arrive here: the mapping + /// workflows scatter, the artifact ones (prepare, store) do not, and a + /// single-output workflow answering "no store array" is how this was found. #[test] - fn the_store_key_follows_the_genotype_file_and_annotation_only() { - let dir = std::env::temp_dir().join(format!("gn4-lmdbkey-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let geno = dir.join("G.txt"); - let snps = dir.join("S.txt"); - std::fs::write(&geno, "s1\ts2\nm1\t1\t1\t0\t2\n").unwrap(); - std::fs::write(&snps, "m1 150 1\n").unwrap(); - let geno_s = geno.to_string_lossy().into_owned(); - let snps_s = snps.to_string_lossy().into_owned(); - - let first = lmdb_store_key(&geno_s, &snps_s); - assert_eq!(first, lmdb_store_key(&geno_s, &snps_s), "must be stable"); - std::fs::write(&snps, "m1 150 2\n").unwrap(); - assert_ne!(first, lmdb_store_key(&geno_s, &snps_s), "annotation counts"); - let _ = std::fs::remove_dir_all(&dir); + fn ravanan_outputs_may_be_one_file_or_an_array() { + let one: Value = serde_json::from_str( + r#"{"store":{"class":"File","path":"/s/genotypes.mdb"}}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&one, "store").unwrap(), + vec!["/s/genotypes.mdb"] + ); + + let many: Value = serde_json::from_str( + r#"{"assoc":[{"class":"File","path":"/s/1-gwa.assoc.txt"}, + {"class":"File","path":"/s/2-gwa.assoc.txt"}]}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&many, "assoc").unwrap(), + vec!["/s/1-gwa.assoc.txt", "/s/2-gwa.assoc.txt"] + ); + assert!(ravanan_output_paths(&many, "store").is_err()); } } diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 5beb4db..6cb8d0b 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -185,6 +185,360 @@ pub(crate) struct ResolvedInputs { pub notes: Vec, } +/// The two cluster-side artifacts a ravanan request needs before anything is +/// mapped: the missing-genotype treatment (`cwl/gemma/prepare.scm`) and, for +/// pangemma, its lmdb store (`cwl/gemma/store.scm`). +/// +/// Both are workflows rather than steps inside the mapping workflow because +/// ccwl's `pipe` is linear -- the GWA step needs the prepared genotypes *and* +/// the kinship matrix, which is a diamond. Ravanan caches each of them on +/// (script, inputs), so the treatment runs once per (panel, mode) and the store +/// once per panel, however many traits follow. +/// +/// Failure here is the caller's error only when it is the *request's* (an +/// unknown mode, `hmm` without a group); a cluster or script failure is a 502 +/// like any other engine failure. +#[allow(clippy::too_many_arguments)] +async fn ravanan_artifacts( + config: &Config, + engine: crate::gemma::GemmaEngine, + mode: &str, + genotype_file: &str, + snps_file: &str, + group: &Option, + version: Option<&str>, + names: Option<&Vec>, + endpoint: &'static str, + rid: RequestInfo, +) -> Result { + let cache_dir = &config.ravanan_cache_dir; + let mut notes = Vec::new(); + std::fs::create_dir_all(cache_dir).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cache directory", + format!("creating {cache_dir} failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + + // The cross `hmm' predicts from, and the individuals this request serves. + // Both are inputs of the prepare workflow even when it ignores them: a CWL + // step input cannot be optional here, and an empty directory and file are + // cheaper than building a cross nobody asked for. + let (cross_dir, cross_note) = if mode == "hmm" { + let Some(group_name) = group.clone() else { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_group", + "hmm imputation needs a group", + "the HMM predicts a missing call from flanking markers in a converted \ + cross, and a cross is built from a group; send `group` (with \ + `genotype_version` if you want a particular version), or use \ + impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + }; + let (directory, cache, convert) = ( + config.genotype_files_dir.clone(), + config.qtl2_cache_dir.clone(), + config.qtl2_convert_script.clone(), + ); + let version = version.map(|v| v.to_string()); + let prepared = tokio::task::spawn_blocking(move || { + let resolved = + genotypes::resolve(std::path::Path::new(&directory), &group_name, version.as_deref()) + .map_err(|error| error.to_string())?; + // Drop is the default genotype model: the heterozygous calls a + // riset panel carries are exactly the ones the HMM is asked to + // re-predict, so predicting from the kept calls would be circular. + qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache), + qtl2::Het::Drop, + std::path::Path::new(&convert), + ) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cross", + format!("preparing the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "cross_preparation_failed", + "Could not prepare the cross", + format!("{error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + let dir = prepared + .control + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)); + // Copy it under the cache directory, which is on the filesystem the + // compute nodes see: ravanan's slurm backend does not stage a Directory + // input (measured: the staged path reached the job and the HMM's setwd + // failed, while the same workflow ran under single-machine), so the job + // reads the cross where it lies instead. The cross's own name carries + // its version and a panel fingerprint, so copying once is enough. + let staged = std::path::Path::new(&config.ravanan_cache_dir) + .join("crosses") + .join(dir.file_name().unwrap_or_default()); + if !staged.is_dir() { + let (from, to) = (dir.clone(), staged.clone()); + tokio::task::spawn_blocking(move || { + std::fs::create_dir_all(to.parent().unwrap_or(&to))?; + let status = std::process::Command::new("cp") + .arg("-r") + .arg(&from) + .arg(&to) + .status()?; + if !status.success() { + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + "cp -r failed", + )); + } + Ok::<(), std::io::Error>(()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("staging the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("copying {} to {} failed: {error}", dir.display(), staged.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + } + ( + staged.to_string_lossy().into_owned(), + Some( + "genotypes: the group's R/qtl2 cross, so a missing call is predicted by the \ + HMM (maxmarg on the same genotype probabilities /compute/qtl2 maps on)" + .to_string(), + ), + ) + } else { + let empty = std::path::Path::new(cache_dir).join("no-cross"); + std::fs::create_dir_all(&empty).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not create the artifact staging directory", + format!("creating {} failed: {error}", empty.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + (empty.to_string_lossy().into_owned(), None) + }; + if let Some(note) = cross_note { + notes.push(note); + } + + // The served individuals, one per line: an input of the workflow, and for + // `hmm' also the list the R script restricts its calls to. + let served = match names { + Some(names) if !names.is_empty() => { + let path = std::path::Path::new(cache_dir).join(format!( + "served-individuals-{}.txt", + crate::gemma::sha16(names.join(",").as_bytes()) + )); + let body: String = names.iter().map(|n| format!("{n}\n")).collect(); + std::fs::write(&path, body).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + _ => { + if mode == "hmm" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_names", + "hmm imputation needs named individuals", + "the HMM is asked for a specific set of individuals, so the request has to \ + name them: send `samples` or a group-scoped request (not positional \ + `trait_values`), or use impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + } + let path = std::path::Path::new(cache_dir).join("no-individuals.txt"); + std::fs::write(&path, "").map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the empty individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + }; + + // Ravanan resolves an input path relative to the inputs YAML, which lives + // in the cache directory -- so a configured script path has to be absolute + // here, not merely valid from the server's working directory (measured: a + // relative prepare-genotypes.sh died inside ravanan as + // "canonicalize-path: No such file or directory"). + let absolute = |path: &str| -> String { + std::fs::canonicalize(path) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| path.to_string()) + }; + let prepare_script = absolute(&config.prepare_genotypes); + let impute_script = absolute(&config.impute_script); + + let (genotype_file, snps_file, individuals_file) = if mode == "none" { + (genotype_file.to_string(), snps_file.to_string(), None) + } else { + let inputs = format!( + "mode: \"{mode}\"\n\ + prepare_script: {{class: File, path: {}}}\n\ + impute_script: {{class: File, path: {}}}\n\ + genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n\ + cross: \"{cross_dir}\"\n\ + individuals_file: {{class: File, path: {served}}}\n", + prepare_script, impute_script, + ); + let run = gemma::ArtifactWorkflow { + label: "prepare", + ccwl_cmd: &config.ccwl_cmd, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_prepare_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &[ + "mode", + "prepare_script", + "impute_script", + "genotype_file", + "snps_file", + "cross", + "individuals_file", + ], + &inputs, + &["genotype_file", "snps_file", "individuals_file"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let pick = |id: &str| { + outputs + .iter() + .find(|(name, _)| name == id) + .and_then(|(_, paths)| paths.first().cloned()) + .unwrap_or_default() + }; + notes.push(format!( + "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \ + cluster), cached by ravanan on (script, inputs)" + )); + (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file"))) + }; + + let store = if engine == gemma::GemmaEngine::Pangemma { + let inputs = format!( + "store_script: {{class: File, path: {}}}\n\ + genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n", + absolute(&config.geno2mdb_cmd), + ); + let run = gemma::ArtifactWorkflow { + label: "store", + ccwl_cmd: &config.ccwl_cmd, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_store_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &["store_script", "genotype_file", "snps_file"], + &inputs, + &["store"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let path = outputs + .iter() + .find(|(name, _)| name == "store") + .and_then(|(_, paths)| paths.first().cloned()); + notes.push( + "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \ + cluster), cached by ravanan on (script, inputs)" + .to_string(), + ); + path + } else { + None + }; + + Ok(Artifacts { + genotype_file, + snps_file, + store, + individuals_file, + notes, + }) +} + +/// What [`ravanan_artifacts`] produced. +struct Artifacts { + genotype_file: String, + snps_file: String, + store: Option, + /// The individual order of the prepared genotypes, when the treatment + /// changed it (`hmm` takes its order from the cross). + individuals_file: Option, + notes: Vec, +} + /// Resolve a request's genotype input and trait values. /// /// `endpoint` names this endpoint in errors ("compute_gemma" or @@ -608,8 +962,19 @@ pub async fn compute_gemma( request.engine.as_deref(), Some(value) if crate::gemma::GemmaEngine::parse(value) == Some(crate::gemma::GemmaEngine::Pangemma) ); + // A treatment the request asked for and the wrapper cannot apply: the + // in-process run reads the panel's genotypes as they stand, so falling back + // to it on `impute: hmm` answered 21,055 rows where the request meant the + // HMM's 20,453 -- a wrong answer wearing a "degraded" note. Treated + // requests therefore fail rather than fall back. + let treated = pangemma + || !request + .impute + .as_deref() + .unwrap_or("none") + .eq_ignore_ascii_case("none"); let mut fallback_note: Option = None; - if pangemma || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { + if treated || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { match gemma_via_ravanan( ctx.clone(), token.clone(), @@ -621,7 +986,7 @@ pub async fn compute_gemma( .await { Ok(answer) => return Ok(answer), - Err(error) if error.status >= 500 && !pangemma => { + Err(error) if error.status >= 500 && !treated => { eprintln!( "compute_gemma: slurm route failed ({} {}); falling back to the local gemma-wrapper run", error.status, error.code @@ -1001,255 +1366,6 @@ pub async fn compute_gemma( } -/// A genotype file materialised for one missing-data treatment. -struct PreparedGenotypes { - genotype_file: String, - snps_file: String, - notes: Vec, -} - -/// Run `scripts/prepare-genotypes.sh` to turn the resolved genotype file into -/// the one the caller asked for (`mean` or `hmm`). -/// -/// Both modes write a *complete* file beside the ravanan cache, keyed by the -/// panel and the mode, so a second request for the same panel and treatment -/// reuses it: `mean` costs a pass over the file, `hmm` costs the qtl2 HMM -/// (about ten seconds for BXD.8 on one core, then cached). -async fn prepare_genotypes( - config: &Config, - mode: &str, - genotype_file: &str, - snps_file: &str, - group: &Option, - version: Option<&str>, - names: Option<&Vec>, - rid: RequestInfo, -) -> Result { - let stem = std::path::Path::new(genotype_file) - .file_stem() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| "panel".to_string()); - // The cache key carries a version, because it is keyed on the panel and the - // mode and NOT on the code that produces them: a fixed bug in the imputation - // script would otherwise be masked by its own old output (measured: a - // corrected individuals file was ignored and the run kept failing on the - // stale one). Bump this when either script changes what it writes. - const IMPUTE_CACHE_VERSION: &str = "v6"; - let prefix = std::path::Path::new(&config.ravanan_cache_dir) - .join("imputed") - .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); - let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); - let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); - - let mut notes = Vec::new(); - if std::path::Path::new(&prepared_geno).is_file() - && std::path::Path::new(&prepared_snps).is_file() - { - notes.push(format!( - "genotypes: '{mode}' treatment reused from the cache ({})", - prepared_geno - )); - return Ok(PreparedGenotypes { - genotype_file: prepared_geno, - snps_file: prepared_snps, - notes, - }); - } - - // hmm predicts from the group's qtl2 cross: the same conversion and the - // same cache /compute/qtl2 uses, so the calls are the ones that endpoint - // maps on, and the probabilities are computed once and kept beside the - // cross. - let cross_dir = if mode == "hmm" { - let Some(group) = group.clone() else { - return Err(ApiError::new( - StatusCode::UNPROCESSABLE_ENTITY, - "impute_needs_group", - "hmm imputation needs a group", - "the HMM predicts a missing call from flanking markers in a converted \ - cross, and a cross is built from a group; send `group` (with \ - `genotype_version` if you want a particular version), or use \ - impute=mean." - .to_string(), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - }; - let directory = config.genotype_files_dir.clone(); - let cache = config.qtl2_cache_dir.clone(); - let version = version.map(|v| v.to_string()); - let convert = config.qtl2_convert_script.clone(); - let prepared = tokio::task::spawn_blocking(move || { - let resolved = genotypes::resolve( - std::path::Path::new(&directory), - &group, - version.as_deref(), - ) - .map_err(|error| error.to_string())?; - // Drop is the default genotype model: the heterozygous calls a - // riset panel carries are exactly the ones the HMM is asked to - // re-predict, so predicting from the kept calls would be circular. - qtl2::prepare_cross( - &resolved, - std::path::Path::new(&cache), - qtl2::Het::Drop, - std::path::Path::new(&convert), - ) - .map_err(|error| error.to_string()) - }) - .await - .map_err(|error| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not prepare the cross", - format!("preparing the qtl2 cross failed: {error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })? - .map_err(|error| { - ApiError::new( - StatusCode::UNPROCESSABLE_ENTITY, - "cross_preparation_failed", - "Could not prepare the cross", - format!("{error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })?; - prepared - .control - .parent() - .map(|dir| dir.to_path_buf()) - .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)) - } else { - std::path::PathBuf::new() - }; - - if let Some(parent) = std::path::Path::new(&prepared_geno).parent() { - if let Err(error) = std::fs::create_dir_all(parent) { - return Err(ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not create the imputation cache directory", - format!("creating {} failed: {error}", parent.display()), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - } - // The individuals the request actually serves, so the HMM output has the - // same columns as the other modes and the phenotype lines up positionally. - let individuals_path = format!("{}.panel.txt", prefix.to_string_lossy()); - if let Some(names) = names { - if !names.is_empty() { - if let Err(error) = std::fs::write( - &individuals_path, - names.iter().map(|n| format!("{n}\n")).collect::(), - ) { - return Err(ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not write the individual list", - format!("writing {individuals_path} failed: {error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - } - } - let individuals_arg = individuals_path.clone(); - let script = config.prepare_genotypes.clone(); - let script_for_job = script.clone(); - let geno = genotype_file.to_string(); - let snps = snps_file.to_string(); - let out = prefix.to_string_lossy().into_owned(); - let mode_owned = mode.to_string(); - let status = tokio::task::spawn_blocking(move || { - let mut args: Vec = vec![ - "--mode".to_string(), - mode_owned, - "--out".to_string(), - out, - ]; - if !geno.is_empty() { - args.push("--geno".to_string()); - args.push(geno); - args.push("--snps".to_string()); - args.push(snps); - } - if !cross_dir.as_os_str().is_empty() { - args.push("--cross".to_string()); - args.push(cross_dir.to_string_lossy().into_owned()); - args.push("--probs".to_string()); - args.push("-".to_string()); - if std::path::Path::new(&individuals_arg).is_file() { - args.push("--individuals-file".to_string()); - args.push(individuals_arg.clone()); - } - } - std::process::Command::new(&script_for_job).args(&args).output() - }) - .await - .map_err(|error| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not prepare genotypes", - format!("running {script} failed: {error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })? - .map_err(|error| { - ApiError::new( - StatusCode::BAD_GATEWAY, - "prepare_genotypes_failed", - "Could not prepare genotypes", - format!("could not run {}: {error}", config.prepare_genotypes), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })?; - if !status.status.success() { - return Err(ApiError::new( - StatusCode::BAD_GATEWAY, - "prepare_genotypes_failed", - "Could not prepare genotypes", - format!( - "{} --mode {mode} failed: {}", - config.prepare_genotypes, - String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("no message") - ), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - - notes.push(match mode { - "mean" => "genotypes: missing calls replaced by each marker's mean (a complete \ - file, so every individual is analysed; GEMMA's own treatment is \ - complete-case per marker, which this replaces)" - .to_string(), - _ => "genotypes: the group's R/qtl2 cross, so a missing call is predicted by \ - the HMM (maxmarg on the same genotype probabilities /compute/qtl2 \ - maps on) rather than filled with a mean. The heterozygous calls a \ - riself panel carries are dropped first, as convert2riself does, and \ - the HMM re-predicts those too. Validated on BXD.8 after the allele \ - codes were fixed (alleles 1 and 2, not 1 and 3): all 20453 autosomal \ - markers stay polymorphic and the top is rsm10000005700, p 6.6e-07 -- \ - the locus the other two engines name. Before that fix it was 11912 \ - markers with the peak on chromosome 5, so a collapse this mode can \ - still produce silently is worth checking when a scan looks wrong." - .to_string(), - }); - Ok(PreparedGenotypes { - genotype_file: prepared_geno, - snps_file: prepared_snps, - notes, - }) -} /// Re-order trait values to the individual order of a prepared genotype file. /// @@ -1456,55 +1572,53 @@ pub(crate) async fn gemma_via_ravanan( ) .with_request_id(rid)); } - let mut impute_notes: Vec = Vec::new(); - let (genotype_file, snps_file) = if impute == "none" { - (genotype_file, snps_file) - } else { - let prepared = prepare_genotypes( - &config, - &impute, - &genotype_file, - &snps_file, - &Some(resolved_group.clone()), - request.genotype_version.as_deref(), - resolved_names.as_ref(), - rid.clone(), - ) - .await?; - impute_notes = prepared.notes; - if impute == "hmm" { - let individuals = format!( - "{}.individuals.txt", - prepared - .genotype_file - .trim_end_matches(".bimbam.txt") - ); - if let Some(names) = resolved_names.as_deref() { - match align_to_individuals(&individuals, names, &trait_values) { - Ok(aligned) => { - impute_notes.push(format!( - "genotypes: trait values aligned by name to the {} individuals of the \ - HMM calls ({} had a value in the panel)", - aligned.len(), - trait_values.iter().filter(|v| v.is_some()).count() - )); - trait_values = aligned; - } - Err(error) => { - return Err(ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not align individuals", - format!("reading {individuals} failed: {error}"), - endpoint, - ) - .with_request_id(rid)); - } + // The genotypes as the caller asked for them, built on the cluster: the + // `hmm`/`mean` treatment and pangemma's lmdb store are workflows of their + // own (see ravanan_artifacts), so what arrives here are paths in ravanan's + // store. + let artifacts = ravanan_artifacts( + &config, + engine, + &impute, + &genotype_file, + &snps_file, + &Some(resolved_group.clone()), + request.genotype_version.as_deref(), + resolved_names.as_ref(), + endpoint, + rid.clone(), + ) + .await?; + let mut impute_notes = artifacts.notes; + let (genotype_file, snps_file) = (artifacts.genotype_file, artifacts.snps_file); + if impute == "hmm" { + if let (Some(individuals), Some(names)) = + (artifacts.individuals_file.as_deref(), resolved_names.as_deref()) + { + match align_to_individuals(individuals, names, &trait_values) { + Ok(aligned) => { + impute_notes.push(format!( + "genotypes: trait values aligned by name to the {} individuals of the \ + HMM calls ({} had a value in the panel)", + aligned.len(), + trait_values.iter().filter(|v| v.is_some()).count() + )); + trait_values = aligned; + } + Err(error) => { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not align individuals", + format!("reading {individuals} failed: {error}"), + endpoint, + ) + .with_request_id(rid)); } } } - (prepared.genotype_file, prepared.snps_file) - }; + } + let store = artifacts.store; // Gated like the direct GEMMA run and by the same size rule, now with the // real panel size: a samples-only request used to be sized 0 and took no @@ -1535,14 +1649,13 @@ pub(crate) async fn gemma_via_ravanan( engine, source: workflow_source, manifest: manifest_source, - geno2mdb: &config.geno2mdb_cmd, - lmdb_cache_dir: &config.gemma_lmdb_cache_dir, }; gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, &ravanan_workflow, + store.as_deref(), &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, -- cgit 1.4.1 From fd5807024b0b5553cbe6e7d6d2bf717d50ef8b05 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sat, 21 Nov 2026 18:52:12 +0000 Subject: scripts: a .geno to BIMBAM projector that refuses to guess the projection HET3-ITP's `bimbam/HET3-ITP.*` pair is empty -- 5.76 M cells, all "NA" -- which is why every GEMMA route answers 422 no_samples_aligned on a panel that is 45.8% dense in the `.geno` R/qtl reads. The converter that made those files only understood the biallelic letter codes a `.geno` header declares, and a four-founder panel writes numeric ones. This adds the tool that can regenerate such a pair, and the experiment that says what a 4-way panel actually needs. Tried the only contrast the header supports -- parent-of-origin, maternal codes 1,2 -> 0, paternal 3,4 -> 1, mixed 5..8 -> 0.5 (order-insensitive, so it cannot transpose two founders): - the pair it produced is real: 2,639,235 of 5,757,171 calls, 893 markers; - pangemma ran on HET3-ITP trait 10000 for the first time: 1314 s (21.9 min, 893 markers x 6447 individuals, one LOCO eigen decomposition per chromosome on a 2-CPU node), HTTP 200; - and it found nothing: 881 of 893 markers came out with exactly zero variance, because an advanced 4-way intercross is ~99.4% heterozygous, so "maternal versus paternal dosage" is a constant. So the mechanism works and the contrast does not. What HET3 needs is a founder contrast (the dosage of one founder's allele), whose numeric-code -> founder-pair table is in neither the `.geno` header, this repository, nor the panel's `rdata/HET3-ITP.RData` (qtl2 allele-probability arrays, not calls). `--codes` is therefore required rather than defaulted: a guessed table produces a silently empty projection, which is exactly how the shipped pair came to be 23 MB of NA. The data is unchanged: the stubs were restored after the experiment. docs/genotypes.md now records this, since it previously described the pair as "a biallelic projection" when in this deployment it carries nothing. --- docs/genotypes.md | 17 +++++- scripts/geno-to-bimbam.py | 140 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 154 insertions(+), 3 deletions(-) create mode 100755 scripts/geno-to-bimbam.py (limited to 'scripts') diff --git a/docs/genotypes.md b/docs/genotypes.md index 55f7a6d..127ff68 100644 --- a/docs/genotypes.md +++ b/docs/genotypes.md @@ -85,9 +85,20 @@ QTLReaper and R/qtl; 2 → GEMMA; 3 → R/qtl; 4 → GEMMA and PLINK. On this database: `BXD` = 1, `HET3-ITP` = 3, `HSNIH-Palmer` = 2, `HS` = NULL. `HET3-ITP` is UM-HET3, a 4-way cross (`@type:4-way`, `@mat:AB`, -`@pat:CD` in its `.geno` header), so R/qtl is the right engine even -though `bimbam/HET3-ITP.*` files exist — those are a biallelic -projection of a four-founder panel. +`@pat:CD` in its `.geno` header), so R/qtl is the right engine. The +`bimbam/HET3-ITP.*` files are **empty stubs** — every genotype cell is +`NA` — so every GEMMA route refuses them with `422 no_samples_aligned` +(after `individuals_with_genotypes` finds nobody with a call), while the +same panel is 45.8% dense in the `.geno` R/qtl reads. A real projection +has to pick a *founder* contrast: tried parent-of-origin +(`scripts/geno-to-bimbam.py`, maternal 1,2 -> 0, paternal 3,4 -> 1, mixed +-> 0.5) and it produced a working pair -- pangemma then ran HET3-ITP +10000 for 21.9 min -- but with **no associations**, because an advanced +4-way intercross is ~99.4% heterozygous, so that dosage is constant (881 +of 893 markers had exactly zero variance). The numeric-code -> +founder-pair table is not in the header, this repository, or +`rdata/HET3-ITP.RData` (qtl2 allele-probability arrays, not calls), so a +founder projection is a decision for the panel's owner. ## Measured runs (2026-11-07, this deployment) diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py new file mode 100755 index 0000000..089da45 --- /dev/null +++ b/scripts/geno-to-bimbam.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Project a GeneNetwork `.geno` panel to the BIMBAM pair GEMMA reads. + +Why this exists: the deployment's `genotype/bimbam/_geno.txt` files +were generated by a converter that only understands the *biallelic* letter +codes a `.geno` header declares (`@mat:AB`, `@pat:CD` -> calls are "A"/"B"). +A four-founder panel declares the same two-letter header but writes its calls +as numeric codes, so every cell fell through to missing: HET3-ITP.12's BIMBAM +was 23 MB of "NA", which is why every GEMMA route refuses it (the panel has +45.8% data in the `.geno`) while R/qtl, which reads the `.geno`, runs fine. + +What the projection is. A 4-way panel (`@type:4-way`, `@mat:AB`, `@pat:CD`) +has eight genotype classes: the four founder homozygotes and the four +maternal-by-paternal combinations. Biallelic BIMBAM can carry one contrast, +and the one this tool takes is **maternal- versus paternal-derived**: a mouse +that inherited both alleles from the `@mat` founders scores 0, both from the +`@pat` founders scores 1, and a heterozygote (one from each) scores 0.5 -- +the mean-genotype scale BIMBAM and GEMMA already use. That projection needs +no knowledge of which numeric code is which heterozygous *pair*, only which +codes are the maternal homozygotes, the paternal homozygotes and everything +else, so it cannot silently transpose two founder alleles. + +Which codes are which is NOT assumed: `--codes` is required, because getting +it wrong is silent. Tried on HET3-ITP.12 with the only table its header +supports (1,2 -> 0; 3,4 -> 1; 5..8 -> 0.5): the projection produced a real +BIMBAM (2.6 M of 5.8 M calls) and pangemma ran on it for 21.9 min, but +answered no associations at all -- 881 of 893 markers came out with exactly +zero variance, because an advanced 4-way intercross is ~99.4% heterozygous, so +"maternal versus paternal dosage" is a constant. A parent-of-origin contrast +is therefore useless for that panel; what it needs is a *founder* contrast +(dosage of one founder's allele), and the numeric-code -> founder-pair table +is not in the `.geno` header, this repository, or the panel's `rdata/*.RData` +(which holds qtl2 allele-probability arrays, not calls). That is a modelling +decision for whoever owns the panel -- pick the founders, then pass the table +here. R/qtl remains the engine for 4-way panels (docs/genotypes.md). + + scripts/geno-to-bimbam.py --geno HET3-ITP.12.geno --out DIR +writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt. +""" + +import argparse +import sys + + +def read_geno(path): + """Yield (chr, locus, cM, Mb, calls) for every marker row.""" + header = None + with open(path) as handle: + for line in handle: + line = line.rstrip("\n") + if not line or line.startswith("#") or line.startswith("@"): + continue + fields = line.split("\t") + if header is None: + if fields[0].lower() != "chr": + continue + header = fields + continue + if len(fields) < 5: + continue + yield fields[0], fields[1], fields[2], fields[3], fields[4:] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--geno", required=True, help="the .geno panel to project") + parser.add_argument("--out", required=True, help="directory for the pair") + parser.add_argument( + "--name", + default=None, + help="basename for the outputs (default: the .geno's name)", + ) + parser.add_argument( + "--codes", + required=True, + help="projection table: '=' separated by ';', " + "e.g. '0=1,2;1=3,4;0.5=5,6,7,8' (required: a guessed table produces a " + "silently empty projection, see the docstring)", + ) + args = parser.parse_args() + + table = {} + for part in args.codes.split(";"): + dosage, codes = part.split("=") + for code in codes.split(","): + table[code.strip()] = dosage.strip() + + import os + + name = args.name or os.path.basename(args.geno).removesuffix(".geno") + geno_out = os.path.join(args.out, f"{name}_geno.txt") + snps_out = os.path.join(args.out, f"{name}_snps.txt") + + seen = {"markers": 0, "calls": 0, "missing": 0} + per_dosage = {} + with open(geno_out, "w") as geno, open(snps_out, "w") as snps: + for chrom, locus, _cm, mb, calls in read_geno(args.geno): + projected = [] + for call in calls: + call = call.strip() + dosage = table.get(call) + if dosage is None: + projected.append("NA") + seen["missing"] += 1 + else: + projected.append(dosage) + per_dosage[dosage] = per_dosage.get(dosage, 0) + 1 + seen["calls"] += 1 + # BIMBAM: marker, allele1, allele0, then one mean genotype per + # individual in column order (X/Y are the placeholders the + # deployment's other BIMBAM files use). + geno.write(f"{locus}, X, Y, " + ", ".join(projected) + "\n") + # The annotation file GEMMA takes as -a: marker, bp, chromosome. + # A `.geno` writes physical positions in Mb (`@scale:physic` and an + # "Mb" column); BIMBAM annotation wants bp, which is what the + # deployment's other `_snps.txt` files carry. + try: + position = str(int(round(float(mb) * 1e6))) + except (TypeError, ValueError): + position = "0" + snps.write(f"{locus}, {position}, {chrom}\n") + seen["markers"] += 1 + + if seen["markers"] == 0: + sys.exit("no marker rows: is this a .geno file?") + if seen["missing"] == seen["calls"]: + sys.exit( + "every call projected to missing -- the --codes table does not " + "match this panel's numeric codes" + ) + print( + f"{geno_out}: {seen['markers']} markers, {seen['calls'] - seen['missing']} " + f"calls projected ({100 * (1 - seen['missing'] / seen['calls']):.1f}% present), " + f"dosages {dict(sorted(per_dosage.items()))}" + ) + print(f"{snps_out}") + + +if __name__ == "__main__": + main() -- cgit 1.4.1 From 098bc6fcc8da84a3598e301c6527d2907df5252e Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sat, 21 Nov 2026 21:14:01 +0000 Subject: scripts: project a panel whose markers are each biallelic onto their own pair HET3-ITP.12's codes are not one alphabet: 486 markers carry exactly {5,6}, 395 carry {7,8}, one carries {2,3}. Each marker is biallelic with its own code pair, which is why a single global table is constant on that panel (measured: 881 of 893 markers with zero variance) and why `--pairwise` exists: per marker, its two present codes become 0 and 1, and a marker with one or more than two classes is left missing rather than folded. `--pairwise` produces a real pair -- 2,603,603 of 5,761,710 calls, dosages 0 and 1 at 50/50 -- and pangemma ran HET3-ITP trait 10000 on it: HTTP 200 in 2678 s (44.6 min; 6447 mice, so the LOCO eigen decomposition per chromosome dominates). The *result* is not usable yet, and the numbers say why: only 36 of 893 markers came back with association rows, and `af` reads 0.25, i.e. GEMMA divided a mean-of-0.5 by two -- the coding is on the wrong scale for its mean-genotype convention (0, 0.5, 1), and most markers then fall out. So: the panel's structure is now understood and the tool can express it; what remains is the dosage scale (0/0.5/1 rather than 0/1) and finding why 857 markers produce no rows. Data restored to the shipped stub meanwhile -- a 45-minute run that returns 36 markers should not be what the deployment serves. R/qtl stays the engine for this panel (it models the 4-way genotypes directly); the point of the exercise is that GEMMA's refusal was diagnosable, not mysterious. --- scripts/geno-to-bimbam.py | 49 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py index 089da45..b31829d 100755 --- a/scripts/geno-to-bimbam.py +++ b/scripts/geno-to-bimbam.py @@ -34,8 +34,16 @@ is not in the `.geno` header, this repository, or the panel's `rdata/*.RData` decision for whoever owns the panel -- pick the founders, then pass the table here. R/qtl remains the engine for 4-way panels (docs/genotypes.md). - scripts/geno-to-bimbam.py --geno HET3-ITP.12.geno --out DIR + scripts/geno-to-bimbam.py --geno HET3-ITP.12.geno --out DIR --pairwise writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt. + +NOT every panel needs a fixed table. A panel whose markers are each biallelic +but whose *code pair* varies from marker to marker (HET3-ITP.12: 486 markers +carry codes {5,6}, 395 carry {7,8}, a handful more) needs `--pairwise`: for +each marker its two present codes become 0 and 1 (lower code -> 0), anything +else missing. That is the biallelic projection the panel actually supports -- +a single global table cannot express it, and forcing one there was measured to +be constant (881 of 893 markers with zero variance). """ import argparse @@ -70,17 +78,28 @@ def main(): default=None, help="basename for the outputs (default: the .geno's name)", ) + parser.add_argument( + "--pairwise", + action="store_true", + help="per-marker biallelic coding: each marker's two present codes " + "become 0 and 1. Use this for a panel whose code pair varies by " + "marker (see the docstring); it conflicts with --codes.", + ) parser.add_argument( "--codes", - required=True, + required=False, help="projection table: '=' separated by ';', " "e.g. '0=1,2;1=3,4;0.5=5,6,7,8' (required: a guessed table produces a " "silently empty projection, see the docstring)", ) args = parser.parse_args() + if bool(args.pairwise) == bool(args.codes): + sys.exit("give exactly one of --pairwise or --codes") table = {} - for part in args.codes.split(";"): + for part in (args.codes or "").split(";"): + if not part: + continue dosage, codes = part.split("=") for code in codes.split(","): table[code.strip()] = dosage.strip() @@ -93,12 +112,27 @@ def main(): seen = {"markers": 0, "calls": 0, "missing": 0} per_dosage = {} + pairwise_seen = {} with open(geno_out, "w") as geno, open(snps_out, "w") as snps: for chrom, locus, _cm, mb, calls in read_geno(args.geno): + marker_table = table + if args.pairwise: + present = sorted({c.strip() for c in calls if c.strip() not in ("NA", "", ".")}) + # Exactly two classes is what a biallelic marker looks like. + # One class (monomorphic) or more than two (a genuinely + # multi-allelic marker, which BIMBAM cannot carry) is left + # missing rather than silently folded. + if len(present) == 2: + marker_table = {present[0]: "0", present[1]: "1"} + pairwise_seen[(present[0], present[1])] = ( + pairwise_seen.get((present[0], present[1]), 0) + 1 + ) + else: + marker_table = {} projected = [] for call in calls: call = call.strip() - dosage = table.get(call) + dosage = marker_table.get(call) if dosage is None: projected.append("NA") seen["missing"] += 1 @@ -133,6 +167,13 @@ def main(): f"calls projected ({100 * (1 - seen['missing'] / seen['calls']):.1f}% present), " f"dosages {dict(sorted(per_dosage.items()))}" ) + if args.pairwise: + print( + "per-marker code pairs: " + + ", ".join( + f"{a}/{b}: {n}" for (a, b), n in sorted(pairwise_seen.items(), key=lambda kv: -kv[1]) + ) + ) print(f"{snps_out}") -- cgit 1.4.1 From b223757bb5c04d03be5ccccf32488594134bb542 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 18:45:52 +0000 Subject: rqtl: the rows are `data`, and the permutation null is meta.permutation Every compute endpoint kept its rows in `data` except this one, which put them under `data.markers` beside `data.permutation`. A script written from SKILL.md ("rows are positional") broke on the first scan it read, and the same script had to special-case both shapes -- measured in Rob Williams's test drive of the release service. `data` is now the marker array (positional, `meta.columns` names the columns, as /compute/gemma and /compute/qtl2 already did), and the permutation null goes to `meta.permutation`, where Meta's own documentation says endpoint-specific qualifier information belongs. /plot/rqtl and scripts/plot-rqtl.py accept both shapes, so a saved reply from an older build still plots. --- scripts/plot-rqtl.py | 9 +++++-- src/response.rs | 9 +++++++ src/routes/plot.rs | 13 ++++++---- src/routes/rqtl.rs | 12 ++++++++-- src/rqtl.rs | 65 +++++++++++++++++++++++++++----------------------- tests/genoupload.rs | 5 ++-- tests/links.rs | 4 ++-- tests/peakgenotypes.rs | 4 ++-- tests/rqtl.rs | 13 ++++++---- 9 files changed, 84 insertions(+), 50 deletions(-) (limited to 'scripts') diff --git a/scripts/plot-rqtl.py b/scripts/plot-rqtl.py index 73d8c51..b24a14f 100644 --- a/scripts/plot-rqtl.py +++ b/scripts/plot-rqtl.py @@ -28,8 +28,13 @@ def main(): if "data" not in doc: sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}") res = doc["data"] - rows = res["markers"] # [name, chr, pos_mb, lod] - perm = res.get("permutation") + # `data` is the marker array itself (a reply from before that change kept + # it under `data.markers`), and the permutation null sits beside it in + # meta; older replies carried it inside data. + rows = res if isinstance(res, list) else res["markers"] + perm = (doc.get("meta") or {}).get("permutation") or ( + res.get("permutation") if isinstance(res, dict) else None + ) thr = [] # (value, label, dash) if perm: thr = [(perm["significant"], "significant (95%)", "7 4"), diff --git a/src/response.rs b/src/response.rs index c2a6cc9..974a585 100644 --- a/src/response.rs +++ b/src/response.rs @@ -279,6 +279,15 @@ impl Envelope { self } + /// Puts one endpoint-specific value into `meta.extra` (qualified data that + /// belongs beside the rows rather than around them -- the permutation null + /// of a scan, say). + pub fn with_extra(mut self, key: &str, value: serde_json::Value) -> Self { + let extra = self.meta.extra.get_or_insert_with(serde_json::Map::new); + extra.insert(key.to_string(), value); + self + } + /// Attaches [`Timing`] to `meta`. pub fn with_timing(mut self, timing: Timing) -> Self { self.meta.timing = Some(timing); diff --git a/src/routes/plot.rs b/src/routes/plot.rs index d33f5d7..0f698be 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -158,11 +158,16 @@ fn check_gemma_result(posted: &serde_json::Value) -> Result<(), String> { /// What `/plot/rqtl` validates in a posted R/qtl result: `data.markers`, /// each row `[name, chr, pos, lod, ...]`. fn check_rqtl_result(result: &serde_json::Value) -> Result<(), String> { - let rows = result["data"]["markers"] - .as_array() - .ok_or("`data.markers` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; + // `data` is the marker array; a reply from a build before that change kept + // it under `data.markers`, and a caller may still be holding one. + let rows = if result["data"].is_array() { + result["data"].as_array() + } else { + result["data"]["markers"].as_array() + } + .ok_or("`data` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; if rows.is_empty() { - return Err("`data.markers` is empty: nothing to plot".to_string()); + return Err("`data` is empty: nothing to plot".to_string()); } let first = rows[0] .as_array() diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 84c43e2..0fbfdf4 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -546,11 +546,16 @@ pub async fn compute_rqtl( // responses from the same panel apart, and `/plot/rqtl` reads it // for the title. let mut envelope = ctx - .envelope(rqtl::to_json(output)) + // `data` is the marker rows, like every other compute endpoint: + // the permutation null is qualifier information and goes to + // meta.extra, so a caller can write one script for all of them + // (measured: Rob Williams's test-drive read data.markers here and + // data itself on GEMMA, and had to special-case both). + .envelope(rqtl::marker_rows(&output)) .with_columns(rqtl::MARKER_COLUMNS.iter().map(|s| s.to_string()).collect(), num_rows) .with_note(&format!("Trait: {}", request.trait_name)) .with_note( - "markers come from R/qtl's scanone output, positional (see meta.columns for names); permutation is null unless nperm > 0 was requested.", + "markers come from R/qtl's scanone output, positional (see meta.columns for names); the permutation null, when nperm > 0 was requested, is meta.permutation.", ) // The conversion is not silent in the status log, but it was // silent here: every heterozygous call is dropped and X becomes an @@ -562,6 +567,9 @@ pub async fn compute_rqtl( panel with heterozygotes at 0.5, so the two are different models, not two \ implementations of one.", ); + if let Some(permutation) = rqtl::permutation_json(&output) { + envelope = envelope.with_extra("permutation", permutation); + } for note in ¬es { envelope = envelope.with_note(note); } diff --git a/src/rqtl.rs b/src/rqtl.rs index 2bf6de3..7dd608d 100644 --- a/src/rqtl.rs +++ b/src/rqtl.rs @@ -495,32 +495,39 @@ pub const MARKER_COLUMNS: [&str; 4] = ["name", "chr", "pos", "lod"]; /// is what utoipa needs here. `markers` rows are positional (see /// `MARKER_COLUMNS`), the same space-saving shape `crate::gemma::compute` /// uses for its own (much larger) marker rows. -pub fn to_json(output: RqtlOutput) -> Value { - let markers: Vec = output - .markers - .into_iter() - .map(|m| { - let mut row = vec![ - Value::String(m.name), - Value::String(m.chr), - serde_json::json!(m.pos), - serde_json::json!(m.lod), - ]; - row.extend(m.extra.into_iter().map(Value::String)); - Value::Array(row) - }) - .collect(); - serde_json::json!({ - "markers": markers, - "permutation": output.permutation, - }) +pub fn marker_rows(output: &RqtlOutput) -> Value { + Value::Array( + output + .markers + .iter() + .map(|m| { + let mut row = vec![ + Value::String(m.name.clone()), + Value::String(m.chr.clone()), + serde_json::json!(m.pos), + serde_json::json!(m.lod), + ]; + row.extend(m.extra.iter().cloned().map(Value::String)); + Value::Array(row) + }) + .collect(), + ) +} + +/// The permutation null, for `meta.extra` beside the rows -- it qualifies the +/// scan rather than being one of its rows, which is why it is not in `data` +/// (that is where every other compute endpoint keeps its rows). +pub fn permutation_json(output: &RqtlOutput) -> Option { + output + .permutation + .as_ref() + .and_then(|permutation| serde_json::to_value(permutation).ok()) } /// The marker with the strongest LOD in a `to_json` result, if there is /// one: the QTL's peak, which is what a PheWAS wants to be centred on. pub fn peak_marker(data: &Value) -> Option { - data.get("markers")? - .as_array()? + data.as_array()? .iter() .filter_map(|row| { let row = row.as_array()?; @@ -661,16 +668,14 @@ mod tests { #[test] fn the_peak_marker_is_the_strongest_lod() { - let data = serde_json::json!({ - "markers": [ - ["rs1", "1", 3.0, 0.5], - ["rs2", "3", 9.0, 4.2], - ["rs3", "5", 12.0, 1.1] - ], - "permutation": null - }); + // `data` is the rows themselves; the permutation null is in meta. + let data = serde_json::json!([ + ["rs1", "1", 3.0, 0.5], + ["rs2", "3", 9.0, 4.2], + ["rs3", "5", 12.0, 1.1] + ]); assert_eq!(peak_marker(&data).as_deref(), Some("rs2")); - assert_eq!(peak_marker(&serde_json::json!({"markers": []})), None); + assert_eq!(peak_marker(&serde_json::json!([])), None); assert_eq!(peak_marker(&serde_json::json!({})), None); } diff --git a/tests/genoupload.rs b/tests/genoupload.rs index 9f8a8a5..4797376 100644 --- a/tests/genoupload.rs +++ b/tests/genoupload.rs @@ -335,9 +335,8 @@ async fn every_engine_maps_an_uploaded_genotype() { let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{endpoint}: {}", String::from_utf8_lossy(&bytes)); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - // /compute/rqtl wraps its rows in data.markers; /compute/qtl2 returns - // them as the array itself. - let rows = envelope["data"]["markers"] + // Both /compute/rqtl and /compute/qtl2 return their rows as `data`. + let rows = envelope["data"] .as_array() .or_else(|| envelope["data"].as_array()) .unwrap_or_else(|| panic!("{endpoint}: no rows in {envelope}")); diff --git a/tests/links.rs b/tests/links.rs index 5291008..d36e5a7 100644 --- a/tests/links.rs +++ b/tests/links.rs @@ -221,8 +221,8 @@ async fn a_scan_points_at_the_class_counts_behind_its_peak() { "the trait id is the caller's to fill in: {hint}" ); // And the marker it names is the peak the reply reported. - // /compute/rqtl's rows live under data.markers. - let rows = envelope["data"]["markers"].as_array().unwrap(); + // /compute/rqtl's rows are `data` itself, like every compute endpoint's. + let rows = envelope["data"].as_array().unwrap(); let peak = rows .iter() .max_by(|left, right| { diff --git a/tests/peakgenotypes.rs b/tests/peakgenotypes.rs index 56461f8..132cfca 100644 --- a/tests/peakgenotypes.rs +++ b/tests/peakgenotypes.rs @@ -34,7 +34,7 @@ async fn scan_peak(token: &str, values: &Value) -> Value { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - envelope["data"]["markers"] + envelope["data"] .as_array() .unwrap() .iter() @@ -148,7 +148,7 @@ async fn a_marker_away_from_the_peak_is_refused() { .await; let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - let rows = envelope["data"]["markers"].as_array().unwrap(); + let rows = envelope["data"].as_array().unwrap(); let distant = rows .iter() .find(|row| row[1] != peak[1]) diff --git a/tests/rqtl.rs b/tests/rqtl.rs index ae0e280..5eeaef4 100644 --- a/tests/rqtl.rs +++ b/tests/rqtl.rs @@ -115,7 +115,7 @@ async fn compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture() { ); let data: Value = common::data(&bytes); - let markers = data["markers"].as_array().unwrap(); + let markers = data.as_array().unwrap(); // The fixture has 6 markers (3 per chromosome, 2 chromosomes). assert_eq!(markers.len(), 6); // Rows are positional (name, chr, pos, lod); see meta.columns. @@ -179,8 +179,11 @@ async fn compute_rqtl_with_permutations_returns_thresholds() { ); let data: Value = common::data(&bytes); - let perm = &data["permutation"]; - assert!(!perm.is_null(), "{data}"); + // The permutation null is qualifier information, so it lives in + // meta.permutation beside the rows rather than in data. + let envelope: Value = serde_json::from_slice(&bytes).unwrap(); + let perm = &envelope["meta"]["permutation"]; + assert!(!perm.is_null(), "{envelope}"); assert_eq!(perm["values"].as_array().unwrap().len(), 20); let suggestive = perm["suggestive"].as_f64().unwrap(); let significant = perm["significant"].as_f64().unwrap(); @@ -432,7 +435,7 @@ async fn compute_rqtl_fits_a_case_attribute_as_a_covariate() { String::from_utf8_lossy(&bytes) ); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - assert!(!envelope["data"]["markers"].as_array().unwrap().is_empty()); + assert!(!envelope["data"].as_array().unwrap().is_empty()); let notes: Vec<&str> = envelope["notes"] .as_array() @@ -514,7 +517,7 @@ async fn a_cm_only_genotype_file_maps() { 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 markers = envelope["data"]["markers"].as_array().unwrap(); + let markers = envelope["data"].as_array().unwrap(); assert_eq!( markers.len(), 6, -- cgit 1.4.1 From 465fcc0bd08495c0a702b94e002a425115a0bab3 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 27 Nov 2026 10:41:36 +0000 Subject: gn4-log: show the usage fields, and count datasets and queries The table grows a short suffix only when a line has them (dataset=... source=... engine=... run=..., or q="..." type=... hits=...), and --json already passed everything through. Two new views for the question the log could not answer before: --datasets counts requests and distinct callers per dataset and source (what is used, by how many separate people), and --queries counts search terms. Both verified against a synthetic file and a week of real lines. --- scripts/gn4-log.py | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) (limited to 'scripts') diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py index a14e653..c4cf3b0 100755 --- a/scripts/gn4-log.py +++ b/scripts/gn4-log.py @@ -25,6 +25,15 @@ Use it on a process log or a proxy log that carries `x-gn4-user`: scripts/gn4-log.py -f log.jsonl --json # enriched JSON, for jq scripts/gn4-log.py -f log.jsonl --summary # who ran what, counted +A compute request names its panel in its *body*, not its path, so the line +carries what the handler recorded about the work (`crate::usage`): `dataset`, +`group`, `source`, `trait`, `engine`, `cached`, `run`, and on `/search` the +query itself as `q` (the path has no query string on purpose). The table shows +them in a short suffix; `--datasets` and `--queries` count them: + + scripts/gn4-log.py -f log.jsonl --since 2026-11-20 --datasets + scripts/gn4-log.py -f log.jsonl --queries --limit 20 + Lines that are not JSON (a Ruby backtrace, a GEMMA progress bar) pass through unchanged unless --quiet; that is deliberate, because the process log interleaves them and dropping them would hide the interesting failures. @@ -150,6 +159,29 @@ def enrich(record: dict, registry: Registry, when: int | None) -> dict: return out +USAGE_FIELDS = ("dataset", "group", "source", "trait", "traits", "engine", "cached", "run") + + +def usage_suffix(record: dict) -> str: + """What the handler recorded about the work, short enough for a table. + + `q` is shown quoted (it is caller text and may contain spaces); the rest + as `key=value`. Nothing here is a secret: see `crate::usage`. + """ + parts = [] + if record.get("q") is not None: + parts.append(f'q="{record["q"]}"') + if record.get("type"): + parts.append(f"type={record['type']}") + if record.get("hits") is not None: + parts.append(f"hits={record['hits']}") + for field in USAGE_FIELDS: + value = record.get(field) + if value not in (None, ""): + parts.append(f"{field}={value}") + return " " + " ".join(parts) if parts else "" + + def format_line(record: dict, when: str) -> str: who = record.get("user") or "-" credential = record.get("scheme") or "-" @@ -165,6 +197,7 @@ def format_line(record: dict, when: str) -> str: f"{when or '-':<19} {who:<20} {credential:<34} " f"{record.get('method', '-'):<6} {record.get('status', '-'):>4} " f"{took:>6} ms {record.get('path', '')}" + f"{usage_suffix(record)}" ) @@ -179,6 +212,9 @@ def main() -> int: parser.add_argument("--grep", default=None, help="only lines containing this text (matches the raw line)") parser.add_argument("--json", action="store_true", help="emit enriched JSON instead of a table") parser.add_argument("--summary", action="store_true", help="count requests per caller and credential") + parser.add_argument("--datasets", action="store_true", help="count requests per dataset (and source), with the distinct callers") + parser.add_argument("--queries", action="store_true", help="count /search queries, most frequent first") + parser.add_argument("--limit", type=int, default=25, help="how many rows --datasets/--queries print (default 25)") parser.add_argument("--quiet", action="store_true", help="drop lines that are not request records") args = parser.parse_args() @@ -230,6 +266,39 @@ def main() -> int: print(f"{len(rows):>7} {'total':<{width}}") return 0 + if args.datasets: + # The question this file was written to answer: which data is used, + # by how many separate callers. Computes are attributed by what the + # handler recorded, reads by what the path spells out. + counts: Counter = Counter() + callers: dict[tuple[str, str], set[str]] = {} + for _, record in rows: + dataset, source = record.get("dataset"), record.get("source") or "-" + if not dataset: + continue + counts[(dataset, source)] += 1 + callers.setdefault((dataset, source), set()).add(record.get("user") or "-") + width = max((len(name) for (name, _) in counts), default=10) + print(f"{'requests':>8} {'callers':>7} {'dataset':<{width}} source") + for (dataset, source), count in counts.most_common(args.limit): + print(f"{count:>8} {len(callers[(dataset, source)]):>7} {dataset:<{width}} {source}") + unattributed = sum(1 for _, record in rows if not record.get("dataset")) + print(f"{len(rows) - unattributed:>8} {len({(u) for c in callers.values() for u in c}):>7} total (plus {unattributed} with no dataset recorded)") + return 0 + + if args.queries: + queries: Counter = Counter() + callers: dict[str, set[str]] = {} + for _, record in rows: + query = record.get("q") + if query is None: + continue + queries[query] += 1 + callers.setdefault(query, set()).add(record.get("user") or "-") + for query, count in queries.most_common(args.limit): + print(f"{count:>7} {len(callers[query]):>3} callers {query}") + return 0 + for when, record in rows: if args.json: print(json.dumps(record)) -- cgit 1.4.1 From 4f609454ba5b8db543863d6f20b042ca15cfe99f Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 27 Nov 2026 10:52:09 +0000 Subject: gn4-log: keep error lines out of the counting views --datasets and --queries are machine-readable like --json and --summary, so a GEMMA backtrace or an error record must not be printed among the counts. Found by running both against the production log, where the week's error records came out first. --- scripts/gn4-log.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'scripts') diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py index c4cf3b0..42031a2 100755 --- a/scripts/gn4-log.py +++ b/scripts/gn4-log.py @@ -248,7 +248,8 @@ def main() -> int: # through in table mode -- the process log interleaves them, and # dropping them would hide the interesting failures -- but never # in a machine-readable mode. - if not args.quiet and not args.json and not args.summary: + if not (args.quiet or args.json or args.summary + or args.datasets or args.queries): print(line) continue rows.append((when, enrich(record, registry, None))) -- cgit 1.4.1