about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-13 13:27:06 +0000
committerPjotr <wrk@bosa.lan>2026-11-13 13:27:06 +0000
commite552bb6407718c986123e574a59494ca6184f2e2 (patch)
tree8543d8f5fd3277525cc9685e65913dae30012201 /src
parentd9e1bf7fd9da4e0bae6579b95fd0028296b997ac (diff)
downloadgenenetwork4-e552bb6407718c986123e574a59494ca6184f2e2.tar.gz
plot/bnw: two SVG figures, drawn the way /plot/gemma draws one
Post the reply from /compute/bnw back and get an SVG: the same plumbing as
/plot/gemma and /plot/bulklmm (plot::render, PLOT_PYTHON + BNW_PLOTTER, image/
svg+xml, the plotter's line in x-plot-summary), nothing recomputed.

Two figures, because one cannot say what the other can:

  * the network (default): nodes on a circle, one arrow per edge that survived
    the threshold, arrow width and label = the edge's posterior, and the
    below-threshold edges as faint dotted lines -- so a reader sees what was
    *considered* as well as what survived, which is half of why the posterior
    table exists;
  * ?kind=posterior: every candidate edge as a cell in a matrix, dark = high
    posterior, outlined cells are the ones above the threshold.  The diagram
    cannot show that an edge came within 0.02 of the threshold; this can.

Pure-Python SVG, standard library only: no graphviz in the deployment.  A
circular layout is less pretty than a force-directed one and is deterministic,
which matters more for a figure that accompanies a JSON result.  Node labels
keep the distinguishing tail of a long id, with the full name beside the node.

Verified live on the dev instance: POST /plot/bnw with a saved /compute/bnw
reply returns 200, image/svg+xml, 5 256 bytes, and x-plot-summary naming the
strongest edge (Trait2 -> Trait1, posterior 1.000); ?kind=posterior returns the
second figure.  tests/plot.rs covers both figures plus the 422s (not a BNW
result, unknown kind).
Diffstat (limited to 'src')
-rw-r--r--src/config.rs8
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/plot.rs115
3 files changed, 124 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs
index 0ab3fca..a4654fa 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -158,6 +158,8 @@ pub struct Config {
     pub bnw_bin_dir: String,
     /// Where the per-request matrices are written (`BNW_CACHE_DIR`).
     pub bnw_cache_dir: String,
+    /// The script `/plot/bnw` runs to draw a network (`BNW_PLOTTER`).
+    pub bnw_plotter: String,
     /// The `julia` binary for BulkLMM (`BULKLMM_CMD`), the project its
     /// packages are instantiated into (`BULKLMM_ENV`), the depot they live in
     /// (`BULKLMM_DEPOT`), the driver script (`BULKLMM_SCRIPT`), the threads it
@@ -344,6 +346,10 @@ impl Config {
         values.insert("BNW_CMD".to_string(), "bnw".to_string());
         values.insert("BNW_BIN_DIR".to_string(), String::new());
         values.insert(
+            "BNW_PLOTTER".to_string(),
+            "scripts/plot-bnw.py".to_string(),
+        );
+        values.insert(
             "BNW_CACHE_DIR".to_string(),
             std::env::temp_dir()
                 .join("gn4-bnw")
@@ -450,6 +456,7 @@ impl Config {
             "BNW_CMD",
             "BNW_BIN_DIR",
             "BNW_CACHE_DIR",
+            "BNW_PLOTTER",
             "BULKLMM_CMD",
             "BULKLMM_ENV",
             "BULKLMM_DEPOT",
@@ -507,6 +514,7 @@ impl Config {
             bnw_cmd: values["BNW_CMD"].clone(),
             bnw_bin_dir: values["BNW_BIN_DIR"].clone(),
             bnw_cache_dir: values["BNW_CACHE_DIR"].clone(),
+            bnw_plotter: values["BNW_PLOTTER"].clone(),
             bulklmm_cmd: values["BULKLMM_CMD"].clone(),
             bulklmm_env: values["BULKLMM_ENV"].clone(),
             bulklmm_depot: values["BULKLMM_DEPOT"].clone(),
diff --git a/src/lib.rs b/src/lib.rs
index 2675c6b..7b9182c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -151,6 +151,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::plot::plot_gemma))
         .routes(routes!(routes::plot::plot_genotypes))
         .routes(routes!(routes::plot::plot_bulklmm))
+        .routes(routes!(routes::plot::plot_bnw))
         .routes(routes!(routes::phewas::group_phewas))
         .routes(routes!(routes::frequencies::group_version_frequencies))
         .routes(routes!(routes::frequencies::group_marker_frequencies))
diff --git a/src/routes/plot.rs b/src/routes/plot.rs
index 8bcbd5b..4a0c7ec 100644
--- a/src/routes/plot.rs
+++ b/src/routes/plot.rs
@@ -51,6 +51,11 @@ pub struct PlotParams {
     /// BulkLMM only: also draw the loosest line the reply reports
     /// (alpha 0.10). The default is the genome-wide 0.05 and the stricter 0.01.
     pub all_thresholds: Option<String>,
+    /// BNW only: which figure, `network` (the learned structure, default) or
+    /// `posterior` (every candidate edge as a cell in a matrix). The diagram
+    /// shows what survived; the matrix says how close an edge was to the
+    /// threshold, which the diagram cannot.
+    pub kind: Option<String>,
 }
 
 /// The reference lines a caller passed, validated: `(value, label)`.
@@ -513,6 +518,116 @@ pub async fn plot_genotypes(
     Ok(svg_response(rendered))
 }
 
+/// What `/plot/bnw` validates in a posted BNW result: positional rows whose
+/// `meta.columns` name the edge, the shape `/compute/bnw` returns.
+fn check_bnw_result(result: &serde_json::Value) -> Result<(), String> {
+    let rows = result
+        .get("data")
+        .and_then(|data| data.as_array())
+        .ok_or("the posted body has no `data` array of rows")?;
+    if rows.is_empty() {
+        return Err("the posted body has no rows".to_string());
+    }
+    let columns: Vec<&str> = result
+        .get("meta")
+        .and_then(|meta| meta.get("columns"))
+        .and_then(|columns| columns.as_array())
+        .map(|columns| columns.iter().filter_map(|c| c.as_str()).collect())
+        .unwrap_or_default();
+    if columns.len() < 3 || columns.get(0) != Some(&"from") || columns.get(1) != Some(&"to") {
+        return Err(format!(
+            "expected the columns of /compute/bnw (from, to, posterior, in_structure), got \
+             {columns:?}"
+        ));
+    }
+    Ok(())
+}
+
+#[utoipa::path(post, path = "/plot/bnw",
+    summary = "Draw a BNW network, as an SVG",
+    description = "Post the response of POST /compute/bnw back (as-is) and get the figure \
+scripts/plot-bnw.py draws from it: the learned structure with one arrow per edge that survived \
+the threshold, arrow width and label = the edge's posterior, and the below-threshold edges as \
+faint dotted lines so a reader sees what was considered as well as what survived. \
+`?kind=posterior` draws every candidate edge as a cell in a matrix instead, which is where a \
+reader sees how close an edge came to the threshold. Nothing is recomputed. image/svg+xml, not \
+the JSON envelope; `x-plot-summary` carries the plotter's one-line summary.",
+    params(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 BNW result, or `kind` is not one of network/posterior", body = ApiError),
+        (status = 502, description = "The plotter failed", body = ApiError)
+    )
+)]
+#[gnauth(token_only)]
+pub async fn plot_bnw(
+    ctx: Ctx,
+    _token: AuthToken,
+    Query(plot_params): Query<PlotParams>,
+    Json(posted): Json<serde_json::Value>,
+) -> Result<Response, ApiError> {
+    let rid = ctx.request_info();
+    if let Err(detail) = check_bnw_result(&posted) {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "not_a_bnw_result",
+            "Not a BNW result",
+            detail,
+            "plot_bnw",
+        )
+        .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 let Some(kind) = plot_params.kind.as_deref() {
+        let kind = kind.trim().to_ascii_lowercase();
+        if kind != "network" && kind != "posterior" {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_kind",
+                "Unknown figure",
+                format!("kind must be `network` or `posterior`, not {kind:?}.", ),
+                "plot_bnw",
+            )
+            .with_request_id(rid));
+        }
+        extra.push("--kind".to_string());
+        extra.push(kind);
+    }
+    let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect();
+    let rendered = plot::render(
+        &config.plot_python,
+        &config.bnw_plotter,
+        std::path::Path::new(&config.bnw_cache_dir),
+        &posted,
+        plot_params
+            .trait_label
+            .clone()
+            .or_else(|| trait_from_document(&posted))
+            .as_deref()
+            .unwrap_or("BNW"),
+        &borrowed,
+    )
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::BAD_GATEWAY,
+            "plot_failed",
+            "Could not draw the plot",
+            error.to_string(),
+            "plot_bnw",
+        )
+        .with_request_id(rid.clone())
+    })?;
+    Ok(svg_response(rendered))
+}
+
 /// What `/plot/bulklmm` validates in a posted BulkLMM result: positional rows
 /// whose `meta.columns` carry a LOD, the shape `/compute/bulklmm` returns.
 fn check_bulklmm_result(result: &serde_json::Value) -> Result<(), String> {