#!/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'")
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'{escape(title)}')
subtitle = parameters(doc)
parts.append(f'{escape(subtitle)}')
parts.append(f''
f'from (rows) x to (columns); dark = high posterior')
for i, name in enumerate(names):
parts.append(f'{escape(short(name))}')
parts.append(f'{escape(short(name))}')
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'')
continue
shade = int(round(255 * (1 - min(max(value, 0.0), 1.0)) * 0.82))
parts.append(f'= 0.5 else 0.6}"/>')
if cell >= 24 and value >= 0.995:
parts.append(f''
f'{value:.2f}')
parts.append(f''
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.')
parts.append("")
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("&", "&").replace("<", "<").replace(">", ">"))
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()