diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-07 18:15:37 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-07 18:15:37 +0000 |
| commit | f9ba0f12e3bf52919fc363c037fbf0a0deda8c17 (patch) | |
| tree | f8ba4f4de75ffe45dd05183d066dc9e079ba6450 /src | |
| parent | b6c5538bc2bf1166ba176a0d80966c04229854ad (diff) | |
| download | genenetwork4-f9ba0f12e3bf52919fc363c037fbf0a0deda8c17.tar.gz | |
plot: draw a mapping, and suggest it from the mapping
The two plotters Pjotr added (scripts/plot-rqtl.py, plot-gemma.py) turn a
saved mapping response into an SVG Manhattan panel. They are now
endpoints, and the mapping that produces the response suggests them:
POST /plot/rqtl same body as /compute/rqtl -> image/svg+xml
POST /plot/gemma same body as /compute/gemma -> image/svg+xml
Taking the mapping's own body rather than the mapping's output means one
call gets you the picture, and the plot cannot describe a run you did not
do: the handlers call the compute handlers and hand the resulting
envelope to the script, exactly as the scripts' docstrings describe
(they read `data.markers`, `data.permutation` and the notes' strain
counts). The mapping is re-run, but through the engines' own caches --
seconds on BXD.
The reply is an SVG, not the JSON envelope: an image is not JSON, and the
plotter's one-line peak summary rides back in `x-plot-summary` so a
caller that cannot see the picture still learns where the peak is.
Both compute responses gain the matching suggestion: `actions` carries
"the same request, plotted" (built from the request that ran, like the
permutation suggestion), so an assistant can map, look, and only then
decide whether the peak is worth the 100-permutation run.
* src/plot.rs: run the configured script over the envelope, read the
SVG back, clean up; a missing script is a 502 naming interpreter and
script, not a panic.
* src/routes/plot.rs: the two handlers (token-gated), delegating to
compute_rqtl/compute_gemma so validation and alignment stay in one
place; `x-plot-summary` sanitised into a header.
* src/routes/{rqtl,gemma}.rs: the plot suggestion, before the
permutation one.
* src/config.rs: PLOT_PYTHON, RQTL_PLOTTER, GEMMA_PLOTTER.
* tests/plot.rs: the suggestion resolves to a complete SVG with a peak
summary, and an invalid mapping request is the mapping's own 422.
* tests/{rqtl,phewas}.rs: find suggestions by href rather than position.
* README.md, docs/www/ai-instruction.md (4a), docs/www/operator-checklist.md
(new "Plotting": python3 must be on the server's PATH).
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 24 | ||||
| -rw-r--r-- | src/lib.rs | 3 | ||||
| -rw-r--r-- | src/plot.rs | 117 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 21 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/plot.rs | 205 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 69 |
7 files changed, 413 insertions, 27 deletions
diff --git a/src/config.rs b/src/config.rs index e7f7fea..d832bbb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -130,6 +130,15 @@ pub struct Config { /// `_snps.txt`, and `parents_and_f1s.json`. See src/genotypes.rs and /// docs/genotypes.md. pub genotype_files_dir: String, + /// Interpreter used to run the plotter scripts (`PLOT_PYTHON`, + /// default `python3`). + pub plot_python: String, + /// `scripts/plot-rqtl.py`: turns a /compute/rqtl response into an SVG + /// Manhattan plot (`RQTL_PLOTTER`). + pub rqtl_plotter: String, + /// `scripts/plot-gemma.py`, for /compute/gemma responses + /// (`GEMMA_PLOTTER`). + pub gemma_plotter: String, } impl Config { @@ -173,6 +182,15 @@ impl Config { "http://127.0.0.1:5003/api/".to_string(), ); values.insert("GN3_TIMEOUT_SECS".to_string(), "30".to_string()); + values.insert("PLOT_PYTHON".to_string(), "python3".to_string()); + values.insert( + "RQTL_PLOTTER".to_string(), + "scripts/plot-rqtl.py".to_string(), + ); + values.insert( + "GEMMA_PLOTTER".to_string(), + "scripts/plot-gemma.py".to_string(), + ); values.insert( "GENOTYPE_FILES".to_string(), "/home/wrk/tmp/ai-root/factory/gn4-data/genotype-files".to_string(), @@ -251,6 +269,9 @@ impl Config { "GN3_URL", "GN3_TIMEOUT_SECS", "GENOTYPE_FILES", + "PLOT_PYTHON", + "RQTL_PLOTTER", + "GEMMA_PLOTTER", "XAPIAN_DB_PATH", "SEARCH_ENGINE", "GEMMA_WRAPPER_CMD", @@ -307,6 +328,9 @@ impl Config { rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), genotype_files_dir: values["GENOTYPE_FILES"].clone(), + plot_python: values["PLOT_PYTHON"].clone(), + rqtl_plotter: values["RQTL_PLOTTER"].clone(), + gemma_plotter: values["GEMMA_PLOTTER"].clone(), } } } diff --git a/src/lib.rs b/src/lib.rs index 96b7b5a..3f7813f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod config; pub mod db; pub mod embedded; pub mod genotypes; +mod plot; mod error; mod gemma; pub mod indexer; @@ -84,6 +85,8 @@ pub fn app() -> Router { .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)) + .routes(routes!(routes::plot::plot_rqtl)) + .routes(routes!(routes::plot::plot_gemma)) .routes(routes!(routes::phewas::group_phewas)) .routes(routes!(routes::genotypes::group_genotypes)) .routes(routes!(routes::genotypes::group_genotype_version)) diff --git a/src/plot.rs b/src/plot.rs new file mode 100644 index 0000000..79edabc --- /dev/null +++ b/src/plot.rs @@ -0,0 +1,117 @@ +//! Running the plotter scripts (`scripts/plot-rqtl.py`, +//! `scripts/plot-gemma.py`) over a mapping response. +//! +//! The plotters take the **saved JSON response** of a mapping and write +//! an SVG, so this writes the envelope the compute endpoint just built to +//! a scratch file, runs the configured script over it, and hands back the +//! SVG text. Nothing is cached: a plot is cheap next to the mapping that +//! produced it, and the mapping itself is what gets cached. + +use std::path::Path; + +/// Why a plot could not be produced. +#[derive(Debug)] +pub enum PlotError { + /// Writing the response, or reading the SVG, failed. + Io(String), + /// The interpreter or script is missing, or the script failed. + Failed(String), +} + +impl std::fmt::Display for PlotError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PlotError::Io(what) => write!(f, "{what}"), + PlotError::Failed(what) => write!(f, "{what}"), + } + } +} + +/// A plot, and the one-line summary the script printed. +#[derive(Debug)] +pub struct Plot { + pub svg: String, + pub summary: String, +} + +/// Run `script` over `response` (the JSON envelope of a mapping) and +/// return the SVG it wrote. +pub async fn render( + python: &str, + script: &str, + scratch_dir: &Path, + response: &serde_json::Value, + trait_label: &str, + extra_args: &[&str], +) -> Result<Plot, PlotError> { + std::fs::create_dir_all(scratch_dir) + .map_err(|e| PlotError::Io(format!("{}: {e}", scratch_dir.display())))?; + let unique = format!( + "{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + ); + let json_path = scratch_dir.join(format!("{unique}-plot.json")); + let svg_path = scratch_dir.join(format!("{unique}-plot.svg")); + std::fs::write( + &json_path, + serde_json::to_vec(response).map_err(|e| PlotError::Io(e.to_string()))?, + ) + .map_err(|e| PlotError::Io(format!("{}: {e}", json_path.display())))?; + + let mut command = tokio::process::Command::new(python); + command + .arg(script) + .arg(&json_path) + .arg("-o") + .arg(&svg_path) + .arg("--trait") + .arg(trait_label) + .args(extra_args); + let output = command.output().await.map_err(|e| { + PlotError::Failed(format!( + "could not run {python} {script} (is the plotter configured? see PLOT_PYTHON, \ + RQTL_PLOTTER, GEMMA_PLOTTER): {e}" + )) + })?; + let summary = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let svg = if output.status.success() { + std::fs::read_to_string(&svg_path) + .map_err(|e| PlotError::Io(format!("{}: {e}", svg_path.display())))? + } else { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(PlotError::Failed(format!( + "{script} failed: {}", + stderr.trim() + ))); + }; + let _ = std::fs::remove_file(&json_path); + let _ = std::fs::remove_file(&svg_path); + Ok(Plot { svg, summary }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_missing_script_is_a_failed_plot_not_a_panic() { + let dir = std::env::temp_dir().join(format!("gn4-plot-{}", std::process::id())); + let error = render( + "python3", + "scripts/does-not-exist.py", + &dir, + &serde_json::json!({"data": {}}), + "t", + &[], + ) + .await + .unwrap_err(); + assert!(matches!(error, PlotError::Failed(_)), "{error}"); + assert!(error.to_string().contains("failed"), "{error}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index faba988..628ac4a 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -346,6 +346,27 @@ pub async fn compute_gemma( "GEMMA reports a p-value per marker, not a permutation threshold: judge a peak \ against the smallest p_lrt it reached, not against a genome-wide threshold.", ); + // The picture: the same run, plotted. + if let Some(group) = request_group.clone() { + let mut plot_body = serde_json::Map::new(); + plot_body.insert("group".to_string(), serde_json::json!(group)); + if let Some(version) = request_genotype_version.clone() { + plot_body.insert("genotype_version".to_string(), serde_json::json!(version)); + } + if let Some(samples) = original_samples.clone() { + plot_body.insert("samples".to_string(), serde_json::Value::Array(samples)); + } + envelope = envelope.with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: "/plot/gemma".to_string(), + description: "Draw this GWAS: the same request to /plot/gemma returns an SVG \ + Manhattan plot of -log10(p_lrt) per marker, with a Bonferroni \ + reference line." + .to_string(), + body: Some(serde_json::Value::Object(plot_body)), + }); + } + // GEMMA has no permutation test and this endpoint passes it no // permutation option (gemma-wrapper's own --permutate shuffles // the phenotype file; see docs/genotypes.md). R/qtl does, on the diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 5407fea..b40c0a4 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -12,6 +12,7 @@ pub mod genotypes; pub mod groups; pub mod mapping_methods; pub mod phewas; +pub mod plot; pub mod publications; pub mod rqtl; pub mod search; diff --git a/src/routes/plot.rs b/src/routes/plot.rs new file mode 100644 index 0000000..ae12ad2 --- /dev/null +++ b/src/routes/plot.rs @@ -0,0 +1,205 @@ +//! `POST /plot/rqtl` and `POST /plot/gemma` -- the Manhattan plot of a +//! mapping, as an SVG. +//! +//! They take the **same request body as the mapping endpoints**, run the +//! mapping through the same handler (so a repeat is as cheap as the +//! engine's own cache makes it), and hand the response to the deployment's +//! plotter (`scripts/plot-rqtl.py`, `scripts/plot-gemma.py`) -- +//! `src/plot.rs` does the running. +//! +//! The reply is an SVG, not an envelope: an image is not JSON, and the two +//! JSON-free responses (`/` and `/openapi.json`) are the precedent. The +//! plotter's one-line summary of the peak goes back in an `x-plot-summary` +//! header, so a caller that cannot see the picture still learns where the +//! peak is. + +use axum::Json; +use axum::extract::Query; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use gnauth_macros::gnauth; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::plot; +use crate::response::Ctx; +use crate::routes::gemma::{ComputeGemmaParams, GemmaRequest, compute_gemma}; +use crate::routes::rqtl::{ComputeRqtlParams, RqtlRequest, compute_rqtl}; +use serde::Deserialize; + +/// `POST /plot/rqtl`'s body: exactly a `/compute/rqtl` request. +pub type PlotRqtlRequest = RqtlRequest; +/// `POST /plot/gemma`'s body: exactly a `/compute/gemma` request. +pub type PlotGemmaRequest = GemmaRequest; + +/// Options shared by both plot endpoints. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct PlotParams { + /// Label for the plot's title, e.g. the trait id. Defaults to the + /// mapping's own trait name. + #[serde(rename = "trait")] + pub trait_label: Option<String>, +} + +#[utoipa::path(post, path = "/plot/rqtl", + summary = "The Manhattan (LOD) plot of an R/qtl mapping, as an SVG", + description = "Takes the same body as POST /compute/rqtl, runs that mapping, and returns \ +the plot the deployment's scripts/plot-rqtl.py draws from the response -- permutation \ +thresholds included when the request asked for them. The response is image/svg+xml, not the \ +JSON envelope, and `x-plot-summary` carries the plotter's one-line peak summary.", + params(PlotParams), + request_body = RqtlRequest, + responses( + (status = 200, description = "The plot, as image/svg+xml", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The mapping request itself was rejected", body = ApiError), + (status = 502, description = "The mapping failed, or the plotter could not run", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_rqtl( + ctx: Ctx, + token: AuthToken, + Query(params): Query<ComputeRqtlParams>, + Query(plot_params): Query<PlotParams>, + Json(request): Json<PlotRqtlRequest>, +) -> Result<Response, ApiError> { + let rid = ctx.request_info(); + let label = plot_params + .trait_label + .clone() + .or_else(|| request.trait_name.clone().into()); + let Json(envelope) = compute_rqtl(ctx, token, Query(params), Json(request)).await?; + let body = serde_json::to_value(&envelope) + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "plot_rqtl", + ) + .with_request_id(rid.clone()) + })?; + let config = Config::load(); + let rendered = plot::render( + &config.plot_python, + &config.rqtl_plotter, + std::path::Path::new(&config.rqtl_cache_dir), + &body, + label.as_deref().unwrap_or("rqtl"), + &[], + ) + .await + .map_err(|e| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "plot_failed", + "Could not draw the plot", + e.to_string(), + "plot_rqtl", + ) + .with_request_id(rid.clone()) + })?; + Ok(svg_response(rendered)) +} + +#[utoipa::path(post, path = "/plot/gemma", + summary = "The Manhattan plot of a GEMMA mapping, as an SVG", + description = "Takes the same body as POST /compute/gemma, runs that mapping, and returns \ +the plot scripts/plot-gemma.py draws from the response: -log10(p_lrt) per marker, with a \ +Bonferroni reference line (GEMMA has no permutation test, so that is the only threshold \ +available). image/svg+xml, not the JSON envelope; `x-plot-summary` carries the plotter's \ +one-line peak summary.", + params(PlotParams), + request_body = GemmaRequest, + responses( + (status = 200, description = "The plot, as image/svg+xml", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The mapping request itself was rejected", body = ApiError), + (status = 502, description = "The mapping failed, or the plotter could not run", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_gemma( + ctx: Ctx, + token: AuthToken, + Query(params): Query<ComputeGemmaParams>, + Query(plot_params): Query<PlotParams>, + Json(request): Json<PlotGemmaRequest>, +) -> Result<Response, ApiError> { + let rid = ctx.request_info(); + let label = plot_params.trait_label.clone(); + let Json(envelope) = compute_gemma(ctx, token, Query(params), Json(request)).await?; + let body = serde_json::to_value(&envelope) + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "plot_gemma", + ) + .with_request_id(rid.clone()) + })?; + let config = Config::load(); + let rendered = plot::render( + &config.plot_python, + &config.gemma_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &body, + label.as_deref().unwrap_or("gemma"), + &[], + ) + .await + .map_err(|e| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "plot_failed", + "Could not draw the plot", + e.to_string(), + "plot_gemma", + ) + .with_request_id(rid.clone()) + })?; + Ok(svg_response(rendered)) +} + +/// The SVG, with the plotter's summary alongside it. +fn svg_response(rendered: plot::Plot) -> Response { + let mut response = rendered.svg.into_response(); + let headers = response.headers_mut(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("image/svg+xml; charset=utf-8"), + ); + if let Ok(summary) = HeaderValue::from_str(&sanitise_header(&rendered.summary)) { + headers.insert("x-plot-summary", summary); + } + response +} + +/// Header values may not contain newlines or non-visible ASCII; the +/// plotter's summary is one line, but this keeps a bad one from becoming a +/// 500. +fn sanitise_header(text: &str) -> String { + text.chars() + .map(|c| if c.is_ascii_graphic() || c == ' ' { c } else { ' ' }) + .take(500) + .collect() +} + +#[cfg(test)] +mod tests { + use super::sanitise_header; + + #[test] + fn a_summary_with_newlines_survives_as_a_header() { + assert_eq!( + sanitise_header("wrote out.svg: peak rs1 chr9 29.9 Mb LOD 4.20\n"), + "wrote out.svg: peak rs1 chr9 29.9 Mb LOD 4.20 " + ); + } +} diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 8fd7cee..9271921 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -332,40 +332,55 @@ pub async fn compute_rqtl( "To plot this: rows are positional, so chr (meta.columns[1]) against LOD \ (meta.columns[3]) is a Manhattan plot with no reshaping.", ); - // A scan without permutations gives LOD scores, not thresholds. - // 100 permutations is GeneNetwork's usual answer to "is this peak - // real?", and it is a POST with a body -- so `actions`, not - // `next` -- rebuilt from what was actually run. - if request_nperm == 0 { - let mut body = serde_json::Map::new(); - match (request_genotype_file.clone(), request_group.clone()) { - (Some(file), None) => { - body.insert("genotype_file".to_string(), serde_json::json!(file)); + // Rebuild the request that ran, once: both suggestions below are + // "the same call, somewhere else". + let mut body = serde_json::Map::new(); + match (request_genotype_file.clone(), request_group.clone()) { + (Some(file), None) => { + body.insert("genotype_file".to_string(), serde_json::json!(file)); + } + _ => { + if let Some(group) = request_group.clone() { + body.insert("group".to_string(), serde_json::json!(group)); } - _ => { - if let Some(group) = request_group.clone() { - body.insert("group".to_string(), serde_json::json!(group)); - } - if let Some(version) = request_genotype_version.clone() { - body.insert("genotype_version".to_string(), serde_json::json!(version)); - } + if let Some(version) = request_genotype_version.clone() { + body.insert("genotype_version".to_string(), serde_json::json!(version)); } } - body.insert("trait_name".to_string(), serde_json::json!(request.trait_name)); - body.insert( - "samples".to_string(), - serde_json::Value::Array(original_samples.clone()), - ); - body.insert("model".to_string(), serde_json::json!(request_model)); - body.insert("method".to_string(), serde_json::json!(request_method)); - body.insert("nperm".to_string(), serde_json::json!(100)); + } + body.insert("trait_name".to_string(), serde_json::json!(request.trait_name)); + body.insert( + "samples".to_string(), + serde_json::Value::Array(original_samples.clone()), + ); + body.insert("model".to_string(), serde_json::json!(request_model)); + body.insert("method".to_string(), serde_json::json!(request_method)); + + // The picture: the same run, plotted. + let mut plot_body = body.clone(); + if request_nperm > 0 { + plot_body.insert("nperm".to_string(), serde_json::json!(request_nperm)); + } + envelope = envelope.with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: "/plot/rqtl".to_string(), + description: "Draw this scan: the same request to /plot/rqtl returns an SVG \ + Manhattan plot of these rows, with the permutation thresholds as \ + dashed lines when nperm > 0." + .to_string(), + body: Some(serde_json::Value::Object(plot_body)), + }); + + // A scan without permutations gives LOD scores, not thresholds. + if request_nperm == 0 { + let mut permutation_body = body; + permutation_body.insert("nperm".to_string(), serde_json::json!(100)); envelope = envelope.with_action(crate::response::SuggestedCall { method: "POST".to_string(), href: "/compute/rqtl".to_string(), - description: "Estimate significance thresholds: the same scan with 100 \ - permutations (nperm=100). The response's `permutation` then carries the suggestive and significant LOD thresholds this scan's peaks can be judged against. Costs about 100 times this run, so pass ?id= and poll its status endpoint." + description: "Estimate significance thresholds: the same scan with 100 permutations (nperm=100). The response's `permutation` then carries the suggestive and significant LOD thresholds this scan's peaks can be judged against. Costs about 100 times this run, so pass ?id= and poll its status endpoint." .to_string(), - body: Some(serde_json::Value::Object(body)), + body: Some(serde_json::Value::Object(permutation_body)), }); } Json(envelope) |
