about summary refs log tree commit diff
path: root/scripts/plot-bnw.py
blob: 248c4cbf92adba3b64c0e3996cde5de4094326da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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()