about summary refs log tree commit diff
path: root/tests/plot.rs
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 /tests/plot.rs
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 'tests/plot.rs')
-rw-r--r--tests/plot.rs98
1 files changed, 98 insertions, 0 deletions
diff --git a/tests/plot.rs b/tests/plot.rs
index 85d60c7..4e8fa06 100644
--- a/tests/plot.rs
+++ b/tests/plot.rs
@@ -407,3 +407,101 @@ async fn a_gemma_plot_takes_labelled_thresholds_from_another_engine() {
     let error: Value = serde_json::from_slice(&bytes).unwrap();
     assert_eq!(error["code"], "invalid_threshold");
 }
+
+/// `/plot/bnw` is the same deal as `/plot/gemma`: post the engine's own
+/// result back and get an SVG.  Two figures, because a network diagram cannot
+/// say how close a rejected edge came to the threshold and a matrix can.
+#[tokio::test]
+async fn a_posted_bnw_result_is_drawn_in_two_figures() {
+    let Some(token) = auth_token().await else {
+        eprintln!("skipping a_posted_bnw_result_is_drawn_in_two_figures: set GN4_TEST_AUTH_TOKEN");
+        return;
+    };
+    let config = genenetwork4::config::Config::load();
+    if !std::path::Path::new(&config.bnw_plotter).is_file() {
+        eprintln!("skipping a_posted_bnw_result_is_drawn_in_two_figures: no BNW_PLOTTER");
+        return;
+    }
+    // A canned /compute/bnw reply: BNW's own six-trait answer, trimmed to the
+    // edges that matter here.
+    let posted = serde_json::json!({
+        "data": [
+            ["Trait2", "Trait1", 1.0, true],
+            ["Trait2", "Trait4", 1.0, true],
+            ["Trait3", "Trait4", 0.42, false]
+        ],
+        "meta": {"columns": ["from", "to", "posterior", "in_structure"]},
+        "notes": ["Parameters: maxparents 4, k 1, tiers 3, threshold 0.5 -- BNW's own defaults."]
+    });
+
+    for (query, must_contain) in [
+        ("", "posterior"),
+        ("?kind=posterior", "edge posteriors"),
+        ("?kind=network&trait=BXD::hippocampus", "BXD::hippocampus"),
+    ] {
+        let response = post_json_with_token(
+            "POST /plot/bnw",
+            &format!("/plot/bnw{query}"),
+            &token,
+            &posted,
+        )
+        .await;
+        let status = response.status();
+        let summary = response
+            .headers()
+            .get("x-plot-summary")
+            .and_then(|value| value.to_str().ok())
+            .unwrap_or_default()
+            .to_string();
+        let bytes = response.into_body().collect().await.unwrap().to_bytes();
+        let svg = String::from_utf8_lossy(&bytes);
+        assert_eq!(status, StatusCode::OK, "{query}: {svg}");
+        assert!(svg.starts_with("<svg"), "{query}: not an SVG");
+        assert!(svg.contains(must_contain), "{query}: expected {must_contain:?} in the figure");
+        assert!(summary.contains("Trait2 -> Trait1"), "{query}: summary {summary:?}");
+    }
+}
+
+#[tokio::test]
+async fn a_body_that_is_not_a_bnw_result_is_a_422() {
+    let Some(token) = auth_token().await else {
+        eprintln!("skipping a_body_that_is_not_a_bnw_result_is_a_422: set GN4_TEST_AUTH_TOKEN");
+        return;
+    };
+    for (posted, expected) in [
+        (serde_json::json!({"data": [], "meta": {"columns": []}}), "not_a_bnw_result"),
+        (
+            serde_json::json!({"data": [["m1", 1, 2.0]], "meta": {"columns": ["marker", "chr", "lod"]}}),
+            "not_a_bnw_result",
+        ),
+        (
+            serde_json::json!({
+                "data": [["A", "B", 1.0, true]],
+                "meta": {"columns": ["from", "to", "posterior", "in_structure"]}
+            }),
+            "invalid_kind", // with ?kind=nonsense below
+        ),
+   ][..2]
+        .iter()
+        .cloned()
+        .chain(std::iter::once((
+            serde_json::json!({
+                "data": [["A", "B", 1.0, true]],
+                "meta": {"columns": ["from", "to", "posterior", "in_structure"]}
+            }),
+            "invalid_kind",
+        )))
+    {
+        let path = if expected == "invalid_kind" {
+            "/plot/bnw?kind=nonsense".to_string()
+        } else {
+            "/plot/bnw".to_string()
+        };
+        let response = post_json_with_token("POST /plot/bnw", &path, &token, &posted).await;
+        let status = response.status();
+        let bytes = response.into_body().collect().await.unwrap().to_bytes();
+        let reply: Value = serde_json::from_slice(&bytes).unwrap();
+        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{reply}");
+        assert_eq!(reply["code"], expected, "{reply}");
+    }
+}