about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-16 20:20:20 +0000
committerPjotr <wrk@bosa.lan>2026-11-16 20:20:20 +0000
commit7f6d92b546892ea5dba5a3f5df541c77c229f1e4 (patch)
tree8fd8d02e4a050cbcf4f14b69ea0d7bf48c724a20 /src
parent94d08ecb58619ae60f048059f24536cac1f1e6e0 (diff)
downloadgenenetwork4-7f6d92b546892ea5dba5a3f5df541c77c229f1e4.tar.gz
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 <prefix>.bimbam.txt
and <prefix>.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/
<panel>-<mode>, 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.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs10
-rw-r--r--src/routes/gemma.rs252
2 files changed, 260 insertions, 2 deletions
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<u32>,
     /// Refused unless 0, as `nperm`.
     pub permutate: Option<u32>,
+
+    /// 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<String>,
 }
 
 /// 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<String>,
+}
+
+/// 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<String>,
+    version: Option<&str>,
+    rid: RequestInfo,
+) -> Result<PreparedGenotypes, ApiError> {
+    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<String> = 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<String> = 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);
         }