about summary refs log tree commit diff
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
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).
-rw-r--r--README.md12
-rw-r--r--docs/www/SKILL.md5
-rwxr-xr-xscripts/plot-bnw.py235
-rw-r--r--src/config.rs8
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/plot.rs115
-rw-r--r--tests/plot.rs98
7 files changed, 473 insertions, 1 deletions
diff --git a/README.md b/README.md
index a5b90b6..f88c672 100644
--- a/README.md
+++ b/README.md
@@ -34,8 +34,10 @@ A Rust/Axum-based API server for GeneNetwork.
 | GET    | `/compute/gemma/status/{run_id}`                  | Poll a gemma run's progress.      |
 | POST   | `/compute/gemma/ravanan`                          | Map a QTL via ravanan (see below).|
 | POST   | `/compute/rqtl`                                   | Map a QTL with R/qtl (see below). |
+| POST   | `/compute/bnw`                                    | Learn a Bayesian network (BNW).   |
 | POST   | `/plot/rqtl`                                      | The R/qtl Manhattan plot, as SVG. |
 | POST   | `/plot/gemma`                                     | The GEMMA Manhattan plot, as SVG. |
+| POST   | `/plot/bnw`                                       | The BNW network, as SVG.          |
 | GET    | `/compute/rqtl/status/{run_id}`                   | Poll an rqtl run's progress.      |
 | POST   | `/get-test-token`                                 | Get a test bearer token (local).  |
 | GET    | `/search`                                         | Search traits (free-text).        |
@@ -2075,6 +2077,16 @@ ordering, not about surprise, and not an effect size. At most 40 variables
 every variable: BNW models a complete multivariate normal, so a sample missing
 any value is dropped and the reply says how many survived.
 
+`POST /plot/bnw` draws it from the posted reply, the same way `/plot/gemma`
+does — an SVG back, nothing recomputed, the plotter's one-line summary in
+`x-plot-summary`. The default figure is the **network**: nodes on a circle, one
+arrow per edge that survived the threshold, arrow width and label = the edge
+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 the view that says how
+close a rejected edge came to the threshold. Pure-Python SVG (`BNW_PLOTTER`,
+run by `PLOT_PYTHON`), so no graphviz is needed in the deployment.
+
 The driver's contract is documented in
 [gn-bnw/info_files/gn4-integration-plan.md](../gn-bnw/info_files/gn4-integration-plan.md);
 `tests/bnw.rs` checks the endpoint against the answer the BNW *web
diff --git a/docs/www/SKILL.md b/docs/www/SKILL.md
index bb8bd3e..b14d08e 100644
--- a/docs/www/SKILL.md
+++ b/docs/www/SKILL.md
@@ -160,7 +160,10 @@ header (peak, and the reference lines drawn when you asked for them).
   this sample, so quote it as a structural claim and never as a threshold on a
   QTL. Parameters default to BNW's own (maxparents 4, k 1, tiers 3, threshold
   0.5) and the reply names the ones used. At most 40 variables, at least 3
-  samples complete across every variable.
+  samples complete across every variable. `POST /plot/bnw` draws it from the
+  posted reply — the network by default, `?kind=posterior` for the matrix of
+  every candidate edge (arrow width and label are the posterior; dotted lines
+  are edges that did not clear the threshold).
 * `/compute/fitqtl`: **how big** an effect is, not just where. Give it the
   marker names a scan found (its peaks) and it fits R/qtl's `fitqtl` at
   each: columns `marker, chr, pos, lod, pct_var, additive, se, t, p`. Use it
diff --git a/scripts/plot-bnw.py b/scripts/plot-bnw.py
new file mode 100755
index 0000000..248c4cb
--- /dev/null
+++ b/scripts/plot-bnw.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python3
+"""Network diagram of a GN4 BNW result, as one SVG panel.
+
+Input is the JSON response of POST /gn4/compute/bnw (saved as-is).  The rows
+are positional -- from, to, posterior, in_structure -- so this reads
+`meta.columns` to find them.
+
+    python3 plot-bnw.py network.json -o network.svg --trait BXD::hippocampus
+
+Two figures, chosen with --kind:
+
+  network   the learned structure: nodes on a circle, an arrow per edge that
+            survived the threshold, labelled with its posterior, drawn thicker
+            the stronger the posterior.  Edges below the threshold are faint
+            dotted lines, so a reader can see what was *considered* as well as
+            what survived.
+  posterior every candidate edge as a cell in a matrix, dark = high posterior,
+            with the surviving ones outlined.  This is the view that says how
+            close to the threshold an edge was, which the diagram cannot.
+
+Standard library only; writes plain SVG (light/dark aware).  A network diagram
+without graphviz keeps the deployment dependency-free: a circular layout is
+less pretty than a force-directed one, but it is deterministic, and a reader of
+a 10-node network does not need the extra cleverness.
+"""
+import argparse
+import json
+import math
+import sys
+
+
+def read_edges(doc):
+    """The posted reply's rows as (from, to, posterior, in_structure) tuples."""
+    if "data" not in doc:
+        sys.exit(f"no 'data' member (error response?): {str(doc)[:200]}")
+    columns = (doc.get("meta") or {}).get("columns") or ["from", "to", "posterior", "in_structure"]
+    idx = {name: i for i, name in enumerate(columns)}
+    for wanted in ("from", "to", "posterior"):
+        if wanted not in idx:
+            sys.exit(f"the rows have no {wanted!r} column: {columns}")
+    rows = []
+    for row in doc["data"]:
+        if not isinstance(row, list) or len(row) < 3:
+            continue
+        try:
+            posterior = float(row[idx["posterior"]])
+        except (TypeError, ValueError):
+            continue
+        in_structure = bool(row[idx["in_structure"]]) if "in_structure" in idx else posterior >= 0.5
+        rows.append((str(row[idx["from"]]), str(row[idx["to"]]), posterior, in_structure))
+    if not rows:
+        sys.exit("no edges to plot")
+    return rows, doc
+
+
+def parameters(doc):
+    """The parameter note the endpoint writes, if it is there."""
+    for note in doc.get("notes") or []:
+        if note.startswith("Parameters:"):
+            return note.split(".", 1)[0]
+    return ""
+
+
+def head(width, height):
+    return [
+        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
+        f'viewBox="0 0 {width} {height}" font-family="sans-serif" role="img">',
+        "<style>"
+        ".bg{fill:#fff}.fg{fill:#222}.muted{fill:#666}.axis{stroke:#bbb}"
+        ".survive{stroke:#1a5fb4;stroke-opacity:.9}.below{stroke:#999;stroke-opacity:.45;"
+        "stroke-dasharray:3 3}"
+        "@media (prefers-color-scheme: dark){.bg{fill:#111}.fg{fill:#eee}.muted{fill:#aaa}"
+        ".axis{stroke:#555}.survive{stroke:#6cb4ff}.below{stroke:#777}}"
+        "</style>",
+        f'<rect class="bg" width="{width}" height="{height}"/>',
+    ]
+
+
+def network_svg(rows, doc, label, title_override):
+    names = []
+    for source, target, _, _ in rows:
+        for name in (source, target):
+            if name not in names:
+                names.append(name)
+    names.sort()
+    n = len(names)
+    radius = max(110.0, 26.0 * n)
+    W = int(2 * radius + 360)
+    H = int(2 * radius + 150)
+    cx, cy = radius + 40, radius + 100
+    angle = {name: (2 * math.pi * i / n) - math.pi / 2 for i, name in enumerate(names)}
+    pos = {name: (cx + radius * math.cos(angle[name]), cy + radius * math.sin(angle[name]))
+           for name in names}
+    # Shorten each arrow so it stops at the node circle, not at its centre.
+    node_radius = 17.0
+
+    def edge_points(source, target):
+        x1, y1 = pos[source]
+        x2, y2 = pos[target]
+        dx, dy = x2 - x1, y2 - y1
+        length = math.hypot(dx, dy) or 1.0
+        return (x1 + dx / length * node_radius, y1 + dy / length * node_radius,
+                x2 - dx / length * (node_radius + 7), y2 - dy / length * (node_radius + 7))
+
+    title = title_override or f"{label}: Bayesian network"
+    subtitle = parameters(doc)
+    survived = sum(1 for row in rows if row[3])
+    subtitle = (subtitle + ". " if subtitle else "") + \
+        f"{n} variables, {len(rows)} candidate edges, {survived} above the threshold"
+
+    parts = head(W, H)
+    parts.append('<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" '
+                 'markerWidth="6" markerHeight="6" orient="auto-start-reverse">'
+                 '<path d="M 0 0 L 10 5 L 0 10 z" fill="#1a5fb4"/></marker></defs>')
+    parts.append(f'<text class="fg" x="24" y="30" font-size="19">{escape(title)}</text>')
+    parts.append(f'<text class="muted" x="24" y="52" font-size="12">{escape(subtitle)}</text>')
+
+    # Faint first, so the surviving edges sit on top.
+    for source, target, posterior, in_structure in sorted(rows, key=lambda r: r[3]):
+        x1, y1, x2, y2 = edge_points(source, target)
+        css = "survive" if in_structure else "below"
+        width = 0.8 + 3.2 * posterior if in_structure else 0.8
+        marker = ' marker-end="url(#arrow)"' if in_structure else ""
+        parts.append(f'<line class="{css}" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" '
+                     f'y2="{y2:.1f}" stroke-width="{width:.2f}"{marker}/>')
+        if in_structure:
+            mx, my = (x1 + x2) / 2, (y1 + y2) / 2
+            parts.append(f'<text class="muted" x="{mx:.1f}" y="{my - 4:.1f}" font-size="10">'
+                         f'{posterior:.2f}</text>')
+
+    for name in names:
+        x, y = pos[name]
+        parts.append(f'<circle class="bg" cx="{x:.1f}" cy="{y:.1f}" r="{node_radius}" '
+                     f'stroke="#1a5fb4" stroke-width="1.2"/>')
+        parts.append(f'<text class="fg" x="{x:.1f}" y="{y + 4:.1f}" font-size="11" '
+                     f'text-anchor="middle">{escape(short(name))}</text>')
+        # The full name below the circle, when it was shortened above it.
+        if short(name) != name:
+            label_y = y + node_radius + 13 * (1 if math.sin(angle[name]) >= 0 else -1) + 4
+            parts.append(f'<text class="muted" x="{x:.1f}" y="{label_y:.1f}" font-size="9" '
+                         f'text-anchor="middle">{escape(name)}</text>')
+
+    parts.append(f'<text class="muted" x="24" y="{H - 16}" font-size="11">'
+                 f'Solid arrows survived the threshold, width and label = edge posterior; dotted '
+                 f'lines were considered and did not. A posterior is the share of the k-best '
+                 f'networks containing the edge, not a p-value.</text>')
+    parts.append("</svg>")
+    top = max(rows, key=lambda row: row[2])
+    return "\n".join(parts), (
+        f"BNW network over {n} variables. {survived} of {len(rows)} candidate edges survive the "
+        f"threshold; the strongest is {top[0]} -> {top[1]} (posterior {top[2]:.3f}).")
+
+
+def posterior_svg(rows, doc, label, title_override):
+    names = sorted({name for source, target, _, _ in rows for name in (source, target)})
+    n = len(names)
+    cell = max(16, min(34, int(760 / max(n, 1))))
+    left, top = 210, 110
+    W, H = left + cell * n + 40, top + cell * n + 90
+    posterior = {(source, target): value for source, target, value, _ in rows}
+    title = title_override or f"{label}: edge posteriors"
+
+    parts = head(W, H)
+    parts.append(f'<text class="fg" x="24" y="30" font-size="19">{escape(title)}</text>')
+    subtitle = parameters(doc)
+    parts.append(f'<text class="muted" x="24" y="52" font-size="12">{escape(subtitle)}</text>')
+    parts.append(f'<text class="muted" x="{left}" y="{top - 26}" font-size="11">'
+                 f'from (rows) x to (columns); dark = high posterior</text>')
+    for i, name in enumerate(names):
+        parts.append(f'<text class="muted" x="{left - 6}" y="{top + i * cell + cell / 2 + 4:.1f}" '
+                     f'font-size="10" text-anchor="end">{escape(short(name))}</text>')
+        parts.append(f'<text class="muted" x="{top + i * cell + cell / 2:.1f}" y="{top - 8}" '
+                     f'font-size="10" text-anchor="start" transform="rotate(-60 '
+                     f'{top + i * cell + cell / 2:.1f} {top - 8})">{escape(short(name))}</text>')
+    for i, source in enumerate(names):
+        for j, target in enumerate(names):
+            value = posterior.get((source, target))
+            x, y = left + j * cell, top + i * cell
+            if value is None:
+                parts.append(f'<rect class="bg" x="{x}" y="{y}" width="{cell - 2}" '
+                             f'height="{cell - 2}" stroke="#ddd" stroke-width="0.5"/>')
+                continue
+            shade = int(round(255 * (1 - min(max(value, 0.0), 1.0)) * 0.82))
+            parts.append(f'<rect x="{x}" y="{y}" width="{cell - 2}" height="{cell - 2}" '
+                         f'fill="rgb({shade},{shade},{shade})" stroke="#1a5fb4" '
+                         f'stroke-width="{2 if value >= 0.5 else 0.6}"/>')
+            if cell >= 24 and value >= 0.995:
+                parts.append(f'<text class="muted" x="{x + cell / 2 - 1:.1f}" '
+                             f'y="{y + cell / 2 + 3:.1f}" font-size="9" text-anchor="middle">'
+                             f'{value:.2f}</text>')
+    parts.append(f'<text class="muted" x="24" y="{H - 16}" font-size="11">'
+                 f'A cell is the posterior of that directed edge; outlined cells survive the '
+                 f'threshold. Blank cells are pairs the search did not report.</text>')
+    parts.append("</svg>")
+    top_edge = max(rows, key=lambda row: row[2])
+    return "\n".join(parts), (
+        f"BNW edge posteriors over {n} variables; strongest {top_edge[0]} -> {top_edge[1]} "
+        f"(posterior {top_edge[2]:.3f}).")
+
+
+def short(name, limit=9):
+    """Node labels on a small circle: keep the distinguishing tail of an id."""
+    if len(name) <= limit:
+        return name
+    return "…" + name[-limit + 1:]
+
+
+def escape(text):
+    return (str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+    parser.add_argument("result", help="saved /compute/bnw response (JSON)")
+    parser.add_argument("-o", "--out", default="bnw_network.svg")
+    parser.add_argument("--trait", default="", help="label for the title")
+    parser.add_argument("--title", default=None, help="override the title text")
+    parser.add_argument("--kind", choices=("network", "posterior"), default="network",
+                        help="network diagram (default) or the posterior matrix")
+    args = parser.parse_args()
+
+    doc = json.load(open(args.result))
+    rows, doc = read_edges(doc)
+    label = args.trait or "BNW"
+    if args.kind == "posterior":
+        svg, summary = posterior_svg(rows, doc, label, args.title)
+    else:
+        svg, summary = network_svg(rows, doc, label, args.title)
+    with open(args.out, "w") as handle:
+        handle.write(svg + "\n")
+    print(summary)
+
+
+if __name__ == "__main__":
+    main()
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> {
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}");
+    }
+}