diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-07 18:23:36 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-07 18:23:36 +0000 |
| commit | c087e4186874921f48caefa2d8630f5bf05b3c0d (patch) | |
| tree | df827dd62afdb72476f89f31fa69cac5b5d4c92a /src | |
| parent | f9ba0f12e3bf52919fc363c037fbf0a0deda8c17 (diff) | |
| download | genenetwork4-c087e4186874921f48caefa2d8630f5bf05b3c0d.tar.gz | |
plot: take a posted result, and never re-run the mapping
The plot endpoints ran the mapping themselves, which meant the picture
could come from a different run than the one the caller was looking at,
and cost a scan to draw. They now take the mapping's own response -- the
JSON /compute/{rqtl,gemma} returned, posted back -- and hand it straight
to the plotter, which is what the scripts were written for
(`python3 plot-rqtl.py result.json -o out.svg --trait …`).
Validation replaces the run: `/plot/rqtl` needs `data.markers` with
positional 4+ column rows, `/plot/gemma` needs `data` rows *and*
`meta.columns` (its plotter reads the column names to find `p_lrt`), and
anything else is a 422 saying "post that response back". `/plot/rqtl`
also accepts just the `data` member; GEMMA cannot, and says why.
The mapping's `actions` suggestion now describes posting its own response
and carries no body -- duplicating a 21 000-row response into a
suggestion would double the envelope for nothing, and the caller already
holds it.
* src/routes/plot.rs: posted result, shape validation, `?trait`/`?title`
and `?bonferroni=false` passthrough to the scripts; no compute imports.
* src/routes/{rqtl,gemma}.rs: the plot suggestion loses its body.
* tests/plot.rs: canned results instead of real mappings -- the tests now
need only the plotter, no Rscript or gemma; covers both engines, the
bare-`data` form, and the 422 for a body that is a request.
* README.md, docs/www/ai-instruction.md (4a), docs/www/operator-checklist.md:
"post the response back", and why GEMMA needs `meta.columns`.
Diffstat (limited to 'src')
| -rw-r--r-- | src/routes/gemma.rs | 31 | ||||
| -rw-r--r-- | src/routes/plot.rs | 218 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 16 |
3 files changed, 163 insertions, 102 deletions
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 628ac4a..4842b58 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -346,26 +346,17 @@ 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)), - }); - } + // The picture: post this response back (no body duplicated here + // -- it is the response the caller already has). + envelope = envelope.with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: "/plot/gemma".to_string(), + description: "Draw this GWAS: POST this response back to /plot/gemma (as-is, or its \ + `data` member) and get an SVG Manhattan plot of -log10(p_lrt) per \ + marker, with a Bonferroni reference line." + .to_string(), + body: None, + }); // GEMMA has no permutation test and this endpoint passes it no // permutation option (gemma-wrapper's own --permutate shuffles diff --git a/src/routes/plot.rs b/src/routes/plot.rs index ae12ad2..bd4a68b 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -1,11 +1,12 @@ //! `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. +//! They take the **mapping's own response** -- the JSON a +//! `/compute/rqtl` or `/compute/gemma` call returned, posted back as-is -- +//! and hand it to the deployment's plotter (`scripts/plot-rqtl.py`, +//! `scripts/plot-gemma.py`), which is what those scripts were written +//! for: `src/plot.rs` does the running. Nothing is recomputed, so a plot +//! costs one script run and can be redrawn from a result you kept. //! //! 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 @@ -18,79 +19,144 @@ 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. + /// Label for the plot's title, e.g. the trait id. Defaults to "rqtl" + /// or "gemma". #[serde(rename = "trait")] pub trait_label: Option<String>, + /// Override the plot's title text. + pub title: Option<String>, + /// GEMMA only: set to false to omit the Bonferroni reference line. + pub bonferroni: Option<String>, +} + +/// What `/plot/gemma` validates in a posted GEMMA result: GEMMA's own +/// `.assoc` rows are positional, 11 columns wide, with `rs` second and +/// `p_lrt` last. +fn check_gemma_result(posted: &serde_json::Value) -> Result<(), String> { + let rows = posted["data"].as_array().ok_or( + "`data` must be the array of GEMMA rows from /compute/gemma -- post that response back, not a request", + )?; + if rows.is_empty() { + return Err("`data` is empty: nothing to plot".to_string()); + } + let columns = posted["meta"]["columns"] + .as_array() + .ok_or( + "post the whole /compute/gemma response, not just its `data`: the plotter needs `meta.columns` to know which column is `p_lrt`", + )?; + let names: Vec<&str> = columns.iter().filter_map(|name| name.as_str()).collect(); + for needed in ["chr", "rs", "ps", "p_lrt"] { + if !names.contains(&needed) { + return Err(format!( + "meta.columns {names:?} has no '{needed}'; GEMMA rows from lmm 9 are [name, chr, ps, ..., p_lrt]" + )); + } + } + let first = rows[0] + .as_array() + .ok_or("`data` rows must be positional arrays (see meta.columns)")?; + if first.len() < names.len() { + return Err(format!( + "`data` rows have {} columns but meta.columns lists {}", + first.len(), + names.len() + )); + } + Ok(()) +} + +/// 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")?; + if rows.is_empty() { + return Err("`data.markers` is empty: nothing to plot".to_string()); + } + let first = rows[0] + .as_array() + .ok_or("marker rows must be positional arrays (see meta.columns)")?; + if first.len() < 4 { + return Err(format!( + "marker rows have {} columns; R/qtl rows are [name, chr, pos, lod, ...]", + first.len() + )); + } + Ok(()) +} + +/// The document handed to the plotter: the posted response as-is when it +/// is a whole envelope, or wrapped when the caller posted only the `data` +/// member (the scripts read `data` and `notes`). +fn as_plot_document(posted: &serde_json::Value) -> serde_json::Value { + if posted.get("data").is_some() { + posted.clone() + } else { + serde_json::json!({"data": posted, "notes": []}) + } } #[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.", + summary = "Draw the Manhattan (LOD) plot of an R/qtl result, as an SVG", + description = "Post the response of POST /compute/rqtl back (as-is, or just its `data` \ +member) and get the plot scripts/plot-rqtl.py draws from it: LOD per marker with the \ +permutation thresholds as dashed lines when the result carried them. Nothing is recomputed. \ +The reply 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, + request_body = serde_json::Value, 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) + (status = 422, description = "The posted body is not an R/qtl result", body = ApiError), + (status = 502, description = "The plotter could not run, or failed", body = ApiError) ) )] #[gnauth(token_only)] pub async fn plot_rqtl( ctx: Ctx, - token: AuthToken, - Query(params): Query<ComputeRqtlParams>, + _token: AuthToken, Query(plot_params): Query<PlotParams>, - Json(request): Json<PlotRqtlRequest>, + Json(posted): Json<serde_json::Value>, ) -> 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 document = as_plot_document(&posted); + if let Err(detail) = check_rqtl_result(&document) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "not_an_rqtl_result", + "Not an R/qtl result", + detail, + "plot_rqtl", + ) + .with_request_id(rid)); + } let config = Config::load(); + let mut extra: Vec<String> = 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.rqtl_plotter, std::path::Path::new(&config.rqtl_cache_dir), - &body, - label.as_deref().unwrap_or("rqtl"), - &[], + &document, + plot_params.trait_label.as_deref().unwrap_or("rqtl"), + &borrowed, ) .await .map_err(|e| { @@ -107,51 +173,57 @@ pub async fn plot_rqtl( } #[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.", + summary = "Draw the Manhattan plot of a GEMMA result, as an SVG", + description = "Post the response of POST /compute/gemma back (as-is, or just its `data` \ +member) and get the plot scripts/plot-gemma.py draws from it: -log10(p_lrt) per marker, with \ +a Bonferroni reference line by default (GEMMA has no permutation test). Nothing is recomputed. \ +image/svg+xml, not the JSON envelope; `x-plot-summary` carries the plotter's one-line peak \ +summary.", params(PlotParams), - request_body = GemmaRequest, + request_body = serde_json::Value, 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) + (status = 422, description = "The posted body is not a GEMMA result", body = ApiError), + (status = 502, description = "The plotter could not run, or failed", body = ApiError) ) )] #[gnauth(token_only)] pub async fn plot_gemma( ctx: Ctx, - token: AuthToken, - Query(params): Query<ComputeGemmaParams>, + _token: AuthToken, Query(plot_params): Query<PlotParams>, - Json(request): Json<PlotGemmaRequest>, + Json(posted): Json<serde_json::Value>, ) -> 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 document = posted; + if let Err(detail) = check_gemma_result(&document) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "not_a_gemma_result", + "Not a GEMMA result", + detail, + "plot_gemma", + ) + .with_request_id(rid)); + } let config = Config::load(); + let mut extra: Vec<String> = Vec::new(); + if let Some(title) = plot_params.title.as_deref() { + extra.push("--title".to_string()); + extra.push(title.to_string()); + } + if matches!(plot_params.bonferroni.as_deref(), Some("false") | Some("0") | Some("no")) { + extra.push("--no-bonferroni".to_string()); + } + let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect(); 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"), - &[], + &document, + plot_params.trait_label.as_deref().unwrap_or("gemma"), + &borrowed, ) .await .map_err(|e| { diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 9271921..e82194f 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -356,19 +356,17 @@ pub async fn compute_rqtl( 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)); - } + // The picture: post this response back. The body is not + // duplicated here -- it is the response the caller already has. 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." + description: "Draw this scan: POST this response back to /plot/rqtl (as-is, or its \ + `data` member) and get an SVG Manhattan plot of these rows, with the \ + permutation thresholds as dashed lines when nperm > 0. Nothing is \ + recomputed." .to_string(), - body: Some(serde_json::Value::Object(plot_body)), + body: None, }); // A scan without permutations gives LOD scores, not thresholds. |
