diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-11 19:49:57 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-11 19:49:57 +0000 |
| commit | 9e03cf40b875790c19d3fa1623297841b72b553e (patch) | |
| tree | 95b891af0f3015fbdd74243c23c4533fee97ae24 /src | |
| parent | 8e13f31ceca05aa06b8a98b76e1141763b6a4140 (diff) | |
| download | genenetwork4-9e03cf40b875790c19d3fa1623297841b72b553e.tar.gz | |
gemma: add POST /compute/gemma, backed by the real gemma-wrapper/GEMMA
Maps a QTL from a genotype file, a SNP annotation file and trait
values, by running gemma-wrapper's K-matrix step then its LMM
association step, both synchronously (axum/tokio awaits the subprocess
directly, no job queue needed) and returning the parsed .assoc.txt
rows in the standard envelope.
Both steps use a bare --loco (gemma-wrapper derives the chromosome
list from the SNP annotation file). This was arrived at empirically,
not from GeneNetwork3's or GeneNetwork2's own gemma code: run for real
against the BXD fixtures,
- GeneNetwork3's gn3/computations/gemma.py composes a GWA command that
always keeps "-gk" alongside "-lmm"; real GEMMA rejects that
combination outright ("only one of -gk ... -lmm ... options is
allowed"), so none of its gwa-compute/k-gwa-compute endpoints can
produce output. Unsurprising: tests/integration/test_gemma.py is
entirely @unittest.skip, so this was never exercised.
- GeneNetwork2's wqflask/marker_regression/gemma_mapping.py correctly
omits "-gk" from the GWA step, but its non-LOCO branch fails too,
the same way my own first (non-LOCO) attempt did: gemma-wrapper only
ever archives a non-LOCO kinship matrix into a .tar.xz, with no
loose file at the path its own non-LOCO GWA code assumes
("Enforce failed for file_kin ... open file"). Only --loco, which
gemma-wrapper's own USAGE banner documents and which does unpack
that archive, actually works.
A --loco run's .assoc.txt files (one per chromosome) are themselves
only ever inside gemma-wrapper's own output archive, never loose, so
gemma.rs shells out to `tar` (one of gemma-wrapper's own propagated
dependencies) to extract them before concatenating all chromosomes'
rows into the response.
guix.scm now depends on (gn packages gemma) from guix-bioinformatics
for gemma-wrapper (propagated-input: it's invoked as a subprocess, not
linked, and this makes it land in a consuming profile too, same as
GeneNetwork3's and GeneNetwork2's own packages do it). That dependency
needed guix-bioinformatics' own gn/packages/gemma.scm fixed first (see
that repo's fix/gemma-which-shadowing branch) -- gemma-gn2 would not
build at all before that fix.
Verified end to end: `cargo test` passes in full, including a real
(non-mocked, non-skipped) run of gemma-wrapper/GEMMA against the BXD
fixtures copied from genenetwork3/tests/test_data, producing exactly
7320 association rows (one per marker in BXD_snps.txt) in ~19s.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 24 | ||||
| -rw-r--r-- | src/gemma.rs | 406 | ||||
| -rw-r--r-- | src/lib.rs | 4 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 90 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 |
5 files changed, 524 insertions, 1 deletions
diff --git a/src/config.rs b/src/config.rs index 10f5755..16286b5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -60,6 +60,14 @@ pub struct Config { pub dev_token_client_secret: String, pub dev_token_username: String, pub dev_token_password: String, + /// The gemma-wrapper executable to invoke for POST /compute/gemma. + /// Same GEMMA_WRAPPER_CMD config key GeneNetwork3 uses. Defaults to + /// "gemma-wrapper", resolved via PATH. + pub gemma_wrapper_cmd: String, + /// Directory gemma-wrapper uses to cache K matrices and association + /// results between calls (its own --cache-dir switch). Defaults to + /// a "gn4-gemma" directory under the system temp dir. + pub gemma_cache_dir: String, } impl Config { @@ -102,6 +110,14 @@ impl Config { values.insert("GN3_TIMEOUT_SECS".to_string(), "30".to_string()); values.insert("XAPIAN_DB_PATH".to_string(), String::new()); values.insert("SEARCH_ENGINE".to_string(), "forward".to_string()); + values.insert("GEMMA_WRAPPER_CMD".to_string(), "gemma-wrapper".to_string()); + values.insert( + "GEMMA_CACHE_DIR".to_string(), + std::env::temp_dir() + .join("gn4-gemma") + .to_string_lossy() + .into_owned(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -127,6 +143,8 @@ impl Config { "GN3_TIMEOUT_SECS", "XAPIAN_DB_PATH", "SEARCH_ENGINE", + "GEMMA_WRAPPER_CMD", + "GEMMA_CACHE_DIR", ] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); @@ -153,6 +171,8 @@ impl Config { dev_token_client_secret: values["GN_AUTH_DEV_CLIENT_SECRET"].clone(), dev_token_username: values["GN_AUTH_DEV_USERNAME"].clone(), dev_token_password: values["GN_AUTH_DEV_PASSWORD"].clone(), + gemma_wrapper_cmd: values["GEMMA_WRAPPER_CMD"].clone(), + gemma_cache_dir: values["GEMMA_CACHE_DIR"].clone(), } } } @@ -223,6 +243,8 @@ mod tests { "GN3_TIMEOUT_SECS", "XAPIAN_DB_PATH", "SEARCH_ENGINE", + "GEMMA_WRAPPER_CMD", + "GEMMA_CACHE_DIR", ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); @@ -232,6 +254,8 @@ mod tests { let config = Config::load(); assert!(config.sql_uri.contains("db_webqtl")); assert_eq!(config.port, 3000); + assert_eq!(config.gemma_wrapper_cmd, "gemma-wrapper"); + assert!(config.gemma_cache_dir.ends_with("gn4-gemma")); assert_eq!(config.auth_server_url, "http://127.0.0.1:8081/"); assert_eq!(config.bind, "0.0.0.0"); assert!(config.test_token_enabled, "on by default"); diff --git a/src/gemma.rs b/src/gemma.rs new file mode 100644 index 0000000..b1f17ed --- /dev/null +++ b/src/gemma.rs @@ -0,0 +1,406 @@ +//! Core logic for POST /compute/gemma: compose and run gemma-wrapper +//! against a genotype file, a SNP annotation file and trait values, and +//! parse the resulting GEMMA association output into QTL mapping rows. +//! +//! Mirrors gn3/computations/gemma.py and gn3/api/gemma.py +//! (GeneNetwork3), but synchronously: axum/tokio can await an external +//! process directly, so there is no need for GeneNetwork3's Redis job +//! queue. The actual invocation also differs from GeneNetwork3's in two +//! respects, both found by running the real gemma-wrapper/GEMMA binaries +//! against the BXD fixtures rather than trusting GeneNetwork3's own +//! (entirely @unittest.skip'd) integration tests -- see `compute_gwa` +//! and `compute` below. + +use std::io; +use std::path::Path; +use std::process::Output; + +use serde_json::Value; +use tokio::process::Command; + +/// One phenotype value per strain (genotype-file order), or `None` for +/// a missing ("NA") sample. +pub type TraitValues = Vec<Option<f64>>; + +#[derive(Debug)] +pub enum GemmaError { + /// Failed to spawn or run a child process. + Io(io::Error), + /// gemma-wrapper exited non-zero; carries its stderr. + CommandFailed { step: &'static str, stderr: String }, + /// gemma-wrapper's own --json stdout record was not valid JSON, or + /// reported an error (its own `errno` field was non-zero). + WrapperError { step: &'static str, detail: String }, + /// The real GEMMA `.assoc.txt` file gemma-wrapper pointed to could + /// not be found or read. + AssocFile(io::Error), + /// gemma-wrapper's GWA output archive did not list any files. + NoAssocFiles, +} + +impl std::fmt::Display for GemmaError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + GemmaError::Io(e) => write!(f, "failed to run gemma-wrapper: {e}"), + GemmaError::CommandFailed { step, stderr } => { + write!(f, "gemma-wrapper ({step}) failed: {stderr}") + } + GemmaError::WrapperError { step, detail } => { + write!(f, "gemma-wrapper ({step}) reported an error: {detail}") + } + GemmaError::AssocFile(e) => write!(f, "could not read GEMMA association output: {e}"), + GemmaError::NoAssocFiles => { + write!(f, "gemma-wrapper's response listed no association output files") + } + } + } +} + +/// Write `values` as a GEMMA/BIMBAM phenotype file: one value per line, +/// "NA" for a missing sample. Mirrors +/// gn3.computations.gemma.generate_pheno_txt_file, minus its hash-based +/// cache filename (the caller picks the path; see `compute`). +pub fn write_pheno_file(path: &Path, values: &TraitValues) -> io::Result<()> { + let mut contents = String::new(); + for value in values { + match value { + Some(v) => contents.push_str(&v.to_string()), + None => contents.push_str("NA"), + } + contents.push('\n'); + } + std::fs::write(path, contents) +} + +async fn run(cmd: &str, args: &[&str]) -> io::Result<Output> { + Command::new(cmd).args(args).output().await +} + +fn parse_wrapper_output(step: &'static str, output: Output) -> Result<Value, GemmaError> { + if !output.status.success() { + return Err(GemmaError::CommandFailed { + step, + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }); + } + let stdout = String::from_utf8_lossy(&output.stdout); + let record: Value = serde_json::from_str(&stdout).map_err(|e| GemmaError::WrapperError { + step, + detail: format!("could not parse gemma-wrapper's --json output: {e}"), + })?; + if record.get("errno").and_then(Value::as_i64).unwrap_or(0) != 0 { + return Err(GemmaError::WrapperError { + step, + detail: record + .get("error") + .and_then(Value::as_str) + .unwrap_or("gemma-wrapper reported a non-zero errno") + .to_string(), + }); + } + Ok(record) +} + +/// Run gemma-wrapper's `--json` K-matrix step and return its stdout +/// record (parsed JSON). +/// +/// `--loco` (bare, no chromosome list) is required here: confirmed by +/// actually running gemma-wrapper against the BXD fixtures, a plain +/// (non-LOCO) `-gk` only ever leaves its kinship matrix inside a +/// `.tar.xz` archive in `--cache-dir`, with no loose file at the path +/// the non-LOCO branch of gemma-wrapper's own GWA step later assumes -- +/// that combination errors out (`gemma: ... open file ... CheckParam`). +/// `--loco` is the combination gemma-wrapper's own USAGE banner +/// documents and the one whose GWA-side code path actually unpacks the +/// archive it needs (see `compute_gwa` and `compute`). Passing it with +/// no chromosome list makes gemma-wrapper derive the full chromosome +/// list from the SNP annotation file itself. +async fn compute_kinship( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + pheno_file: &str, + snps_file: &str, +) -> Result<Value, GemmaError> { + let output = run( + gemma_wrapper_cmd, + &[ + "--json", + "--cache-dir", + cache_dir, + "--loco", + "--", + "-g", + genotype_file, + "-p", + pheno_file, + "-a", + snps_file, + "-gk", + ], + ) + .await + .map_err(GemmaError::Io)?; + parse_wrapper_output("kinship", output) +} + +/// Run gemma-wrapper's `--json` GWA (association) step, given the +/// K-step's JSON record written to `k_json_path` (gemma-wrapper's +/// `--input` takes a file path, not stdin), and return its stdout +/// record. `--loco` is required here for the same reason as in +/// `compute_kinship`. +/// +/// Note: unlike GeneNetwork3's `generate_gemma_cmd` +/// (gn3/computations/gemma.py), which always appends a literal "-gk" to +/// the forwarded GEMMA args regardless of whether an LMM run was +/// requested, this passes `-lmm` without `-gk`, matching gemma-wrapper's +/// own documented usage (its USAGE banner in bin/gemma-wrapper). +/// gemma-wrapper decides K-only vs. GWA purely by whether "-gk" is +/// present in those args (`DO_COMPUTE_KINSHIP = +/// gemma_args.include?("-gk")`); passing both flags together, as +/// GeneNetwork3 does, makes every one of its calls a K-only run, and the +/// `-lmm` value is silently ignored. That GeneNetwork3 code path has no +/// non-skipped test covering it (tests/integration/test_gemma.py is +/// `@unittest.skip`), so it is not knowingly replicated here. +async fn compute_gwa( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + pheno_file: &str, + snps_file: &str, + lmm: u8, + k_json_path: &str, +) -> Result<Value, GemmaError> { + let lmm_str = lmm.to_string(); + let output = run( + gemma_wrapper_cmd, + &[ + "--json", + "--cache-dir", + cache_dir, + "--loco", + "--input", + k_json_path, + "--", + "-g", + genotype_file, + "-p", + pheno_file, + "-a", + snps_file, + "-lmm", + &lmm_str, + ], + ) + .await + .map_err(GemmaError::Io)?; + parse_wrapper_output("gwa", output) +} + +/// The association output basenames gemma-wrapper's GWA-step JSON +/// record points at: `record["files"]` is a list of +/// `[chr, log_basename, data_basename]`, one entry per chromosome in a +/// `--loco` run (see `compute`). +fn assoc_file_basenames(record: &Value) -> Vec<&str> { + record + .get("files") + .and_then(Value::as_array) + .map(|files| { + files + .iter() + .filter_map(|entry| entry.as_array()?.get(2)?.as_str()) + .collect() + }) + .unwrap_or_default() +} + +/// One row of a GEMMA `.assoc.txt` file, keyed by its header column +/// names. Columns vary with `-lmm` (1/2/3 run one test; 4 runs all +/// three), so this stays a generic map rather than a fixed struct. +pub type AssocRow = serde_json::Map<String, Value>; + +/// Parse a GEMMA `.assoc.txt` file (tab-separated, header row first) +/// into one row per marker. A value that parses as a number is kept +/// numeric; "NA" and anything else stays a string. +fn parse_assoc_file(contents: &str) -> Vec<AssocRow> { + let mut lines = contents.lines(); + let Some(header) = lines.next() else { + return Vec::new(); + }; + let columns: Vec<&str> = header.split('\t').collect(); + lines + .filter(|line| !line.is_empty()) + .map(|line| { + let mut row = AssocRow::new(); + for (column, value) in columns.iter().zip(line.split('\t')) { + let json_value = value + .parse::<f64>() + .map(|n| serde_json::json!(n)) + .unwrap_or_else(|_| Value::String(value.to_string())); + row.insert((*column).to_string(), json_value); + } + row + }) + .collect() +} + +/// Extract `archive` (a `.tar.xz`, relative to `cache_dir`) into +/// `dest_dir`. Confirmed necessary by actually running the real +/// binaries: a `--loco` GWA run's `.assoc.txt` files (one per +/// chromosome) only ever end up inside this archive, never as loose +/// files in `cache_dir` -- unlike the kinship step's `.cXX.txt` files, +/// which do also appear loose (gemma-wrapper itself is inconsistent +/// about this between the two steps). +async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Result<(), GemmaError> { + let archive_path = Path::new(cache_dir).join(archive); + let output = run( + "tar", + &[ + "xJf", + &archive_path.to_string_lossy(), + "-C", + dest_dir, + ], + ) + .await + .map_err(GemmaError::Io)?; + if !output.status.success() { + return Err(GemmaError::CommandFailed { + step: "extract-archive", + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }); + } + Ok(()) +} + +fn nanos_since_epoch() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) +} + +/// Run the full gemma-wrapper flow -- compute kinship, then run the LMM +/// association test, both `--loco` -- and return the mapped QTL as a +/// JSON array of rows (each a JSON object), concatenated across every +/// chromosome's `.assoc.txt` from the real GEMMA output. The result is +/// one `Value::Array`, not a `Vec<Value>`: utoipa (for the OpenAPI +/// schema) implements `ToSchema` for `serde_json::Value` itself, but +/// `Vec<serde_json::Value>` needs `Value: ComposeSchema`, which it does +/// not implement in this utoipa version. +pub async fn compute( + gemma_wrapper_cmd: &str, + cache_dir: &str, + genotype_file: &str, + snps_file: &str, + trait_values: &TraitValues, + lmm: u8, +) -> Result<Value, GemmaError> { + std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; + let unique = format!("{}-{}", std::process::id(), nanos_since_epoch()); + let pheno_path = Path::new(cache_dir).join(format!("{unique}-pheno.txt")); + write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?; + let pheno_file = pheno_path.to_string_lossy().into_owned(); + + let k_record = compute_kinship( + gemma_wrapper_cmd, + cache_dir, + genotype_file, + &pheno_file, + snps_file, + ) + .await?; + let k_json_path = Path::new(cache_dir).join(format!("{unique}-k.json")); + std::fs::write(&k_json_path, k_record.to_string()).map_err(GemmaError::Io)?; + + let gwa_record = compute_gwa( + gemma_wrapper_cmd, + cache_dir, + genotype_file, + &pheno_file, + snps_file, + lmm, + &k_json_path.to_string_lossy(), + ) + .await?; + + let basenames = assoc_file_basenames(&gwa_record); + if basenames.is_empty() { + return Err(GemmaError::NoAssocFiles); + } + let archive = gwa_record + .get("archive") + .and_then(Value::as_str) + .ok_or_else(|| GemmaError::WrapperError { + step: "gwa", + detail: "gemma-wrapper's response did not list an output archive".to_string(), + })?; + let extract_dir = Path::new(cache_dir).join(format!("{unique}-gwa-extract")); + std::fs::create_dir_all(&extract_dir).map_err(GemmaError::Io)?; + extract_archive(cache_dir, archive, &extract_dir.to_string_lossy()).await?; + + let mut rows = Vec::new(); + for basename in basenames { + let contents = std::fs::read_to_string(extract_dir.join(basename)) + .map_err(GemmaError::AssocFile)?; + rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object)); + } + let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless + Ok(Value::Array(rows)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_pheno_file_writes_one_value_per_line_and_na_for_missing() { + let path = std::env::temp_dir().join(format!("gn4-gemma-test-{}", std::process::id())); + write_pheno_file(&path, &vec![Some(9.944), None, Some(8.572)]).unwrap(); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents, "9.944\nNA\n8.572\n"); + } + + #[test] + fn parse_assoc_file_parses_header_and_numeric_rows() { + let contents = "chr\trs\tps\tp_wald\n1\trs001\t3010274\t0.05\n1\trs002\t3492195\tNA\n"; + let rows = parse_assoc_file(contents); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0]["chr"], serde_json::json!(1.0)); + assert_eq!(rows[0]["rs"], serde_json::json!("rs001")); + assert_eq!(rows[0]["p_wald"], serde_json::json!(0.05)); + assert_eq!(rows[1]["p_wald"], serde_json::json!("NA")); + } + + #[test] + fn parse_assoc_file_empty_contents_yields_no_rows() { + assert_eq!(parse_assoc_file("").len(), 0); + } + + #[test] + fn assoc_file_basenames_reads_the_third_element_of_every_file_entry() { + let record = serde_json::json!({ + "files": [["1", "a.log.txt", "a.assoc.txt"], ["2", "b.log.txt", "b.assoc.txt"]] + }); + assert_eq!(assoc_file_basenames(&record), vec!["a.assoc.txt", "b.assoc.txt"]); + } + + #[test] + fn assoc_file_basenames_missing_files_yields_empty() { + assert_eq!(assoc_file_basenames(&serde_json::json!({})), Vec::<&str>::new()); + } + + #[test] + fn parse_wrapper_output_rejects_non_zero_errno() { + use std::os::unix::process::ExitStatusExt; + let output = Output { + status: std::process::ExitStatus::from_raw(0), + stdout: br#"{"errno": 1, "error": "boom"}"#.to_vec(), + stderr: Vec::new(), + }; + let err = parse_wrapper_output("kinship", output).unwrap_err(); + assert!(matches!(err, GemmaError::WrapperError { step: "kinship", .. })); + assert_eq!(err.to_string(), "gemma-wrapper (kinship) reported an error: boom"); + } +} diff --git a/src/lib.rs b/src/lib.rs index cfe2c59..ab88fff 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod config; mod db; pub mod embedded; mod error; +mod gemma; pub mod response; mod routes; pub mod search; @@ -76,7 +77,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::correlation::correlation)); + .routes(routes!(routes::correlation::correlation)) + .routes(routes!(routes::gemma::compute_gemma)); // Registered -- and so reachable and listed in /openapi.json -- unless // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides // per request whether the caller is local. See src/routes/dev.rs. diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs new file mode 100644 index 0000000..1506f1b --- /dev/null +++ b/src/routes/gemma.rs @@ -0,0 +1,90 @@ +//! Compute domain: /compute/gemma invokes gemma-wrapper (and the real +//! GEMMA binary it wraps) to map a QTL from a genotype file, a SNP +//! annotation file and a list of trait values. See `crate::gemma` for +//! the invocation itself. + +use axum::Json; +use axum::http::StatusCode; +use serde::Deserialize; + +use crate::auth::AuthToken; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::gemma::{self, GemmaError}; +use crate::response::{Ctx, Envelope, RequestInfo}; + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct GemmaRequest { + /// Path to a BIMBAM genotype file (plain text or gzipped), passed + /// as GEMMA's `-g`. + pub genotype_file: String, + /// Path to a SNP annotation file (rs id, position, chromosome), + /// passed as GEMMA's `-a`. + pub snps_file: String, + /// One phenotype value per strain, in the genotype file's strain + /// order; `null` for a missing value. + pub trait_values: Vec<Option<f64>>, + /// GEMMA's `-lmm` model selector: 1 = Wald, 2 = LRT, 3 = score, + /// 4 = all three. Defaults to 4 when omitted. + pub lmm: Option<u8>, +} + +#[utoipa::path(post, path = "/compute/gemma", + summary = "Map a QTL from a genotype file and trait values using GEMMA", + description = "Runs gemma-wrapper's K-matrix step, then its LMM \ +association step, over the given genotype and SNP annotation files and \ +trait values, and returns the resulting rows of GEMMA's own \ +.assoc.txt output.", + request_body = GemmaRequest, + responses( + (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as a JSON array of row objects", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 422, description = "lmm out of range (must be 1-4)", body = ApiError), + (status = 502, description = "gemma-wrapper or GEMMA failed", body = ApiError) + ))] +pub async fn compute_gemma( + ctx: Ctx, + _token: AuthToken, + Json(request): Json<GemmaRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let lmm = request.lmm.unwrap_or(4); + if !(1..=4).contains(&lmm) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_lmm", + "Invalid lmm", + format!("lmm must be 1-4 (got {lmm}); 1=Wald, 2=LRT, 3=score, 4=all three."), + "compute_gemma", + ) + .with_request_id(rid)); + } + + let config = Config::load(); + gemma::compute( + &config.gemma_wrapper_cmd, + &config.gemma_cache_dir, + &request.genotype_file, + &request.snps_file, + &request.trait_values, + lmm, + ) + .await + .map(|rows| { + Json(ctx.envelope(rows).with_note( + "Rows come from GEMMA's own .assoc.txt output; column names depend on the lmm value used.", + )) + }) + .map_err(|e| gemma_error_to_api_error(e, rid)) +} + +fn gemma_error_to_api_error(error: GemmaError, rid: RequestInfo) -> ApiError { + ApiError::new( + StatusCode::BAD_GATEWAY, + "gemma_failed", + "GEMMA computation failed", + error.to_string(), + "compute_gemma", + ) + .with_request_id(rid) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 55227e0..3a9f3e3 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod correlation; pub mod datasets; pub mod dev; +pub mod gemma; pub mod groups; pub mod mapping_methods; pub mod publications; |
