about summary refs log tree commit diff
path: root/scripts/plot-bulklmm.py
blob: 67ef418320affb45e7d1bf150aaeae793709a5d4 (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
#!/usr/bin/env python3
"""LOD plot of a GN4 BulkLMM result, as one SVG panel.

Input is the JSON response of POST /gn4/compute/bulklmm (saved as-is). The
rows are positional -- marker, chr, pos (Mb), lod, beta, h2 -- so this reads
`meta.columns` to find them. Thresholds come from the reply's own `notes`
("alpha 0.05: LOD 3.81"), which is where the endpoint puts them, so posting a
response back draws the picture a peak has to be judged against.

    python3 plot-bulklmm.py scan.json -o scan.svg --trait BXD::16627

Standard library only; writes plain SVG (light/dark aware).
"""
import argparse, json, math, re, sys

def chr_key(c):
    return (0, int(c), "") if c.isdigit() else (1, 0, c)

def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("result", help="saved /compute/bulklmm response (JSON)")
    ap.add_argument("-o", "--out", default="bulklmm_lod.svg")
    ap.add_argument("--trait", default="", help="trait label for the title")
    ap.add_argument("--title", default=None, help="override the title text")
    ap.add_argument("--all-thresholds", action="store_true",
                    help="also draw the loosest line the reply reports (alpha 0.10); the default "
                         "is the genome-wide 0.05 and the stricter 0.01")
    ap.add_argument("--threshold", action="append", default=[],
                    help="extra reference line as VALUE[:LABEL]")
    a = ap.parse_args()

    doc = json.load(open(a.result))
    if "data" not in doc:
        sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}")
    columns = (doc.get("meta") or {}).get("columns") or ["marker", "chr", "pos", "lod", "beta", "h2"]
    rows = [r for r in doc["data"] if isinstance(r, list) and len(r) >= 4]
    if not rows:
        sys.exit(f"{a.result}: no rows to plot")
    idx = {name: i for i, name in enumerate(columns)}
    name_i, chr_i, pos_i, lod_i = idx["marker"], idx["chr"], idx["pos"], idx["lod"]

    # Thresholds: the endpoint writes them into `notes` as "alpha 0.05: LOD 3.81".
    notes = " ".join(doc.get("notes", []))
    # Two lines by default: the genome-wide 0.05 and the stricter 0.01. The
    # reply also reports 0.10, but that is the loosest bar in the set and
    # drawing it invites reading it as the one to clear -- it is available on
    # request (--all-thresholds) and as an explicit --threshold.
    thresholds = []
    for match in re.finditer(r"alpha ([0-9.]+): LOD ([0-9]+(?:\.[0-9]+)?)", notes):
        alpha, lod = float(match.group(1)), float(match.group(2))
        if abs(alpha - 0.05) < 1e-9:
            thresholds.append((lod, "genome-wide (alpha 0.05)", "6 3"))
        elif abs(alpha - 0.01) < 1e-9:
            thresholds.append((lod, "alpha 0.01", "3 3"))
        elif a.all_thresholds and abs(alpha - 0.1) < 1e-9:
            thresholds.append((lod, "alpha 0.10", "1 4"))
    for spec in a.threshold:
        value, _, label = spec.partition(":")
        thresholds.append((float(value), label.strip() or "threshold", "2 4"))
    seed = re.search(r"seed (\d+)", notes)
    h2 = re.search(r"heritability h2 = ([\d.eE+-]+)", notes)
    nperm = re.search(r"from (\d+) rotations", notes)

    by = {}
    for row in rows:
        try:
            lod = float(row[lod_i])
        except (TypeError, ValueError):
            continue
        by.setdefault(str(row[chr_i]), []).append((float(row[pos_i]), lod))
    if not by:
        sys.exit(f"{a.result}: no numeric LODs")
    order = sorted(by, key=chr_key)
    off, tot, gap = {}, 0.0, 8
    for c in order:
        by[c].sort()
        off[c] = tot
        tot += by[c][-1][0] + gap

    top = max(rows, key=lambda r: r[lod_i])
    top_lod = float(top[lod_i])
    ymax = max(2, math.ceil(max([top_lod] + [t[0] for t in thresholds]) + 0.5))
    W, H, L, R, T, B = 1000, 430, 62, 20, 64, 52
    pw, ph = W - L - R, H - T - B
    X = lambda c, p: L + (off[c] + p) / tot * pw
    Y = lambda v: T + ph - min(v, ymax) / ymax * ph

    label = a.trait or "BulkLMM scan"
    title = a.title or f"{label}: LOD along the genome"
    sub = "BulkLMM LMM, global kinship"
    if h2:
        sub += f", h2 {float(h2.group(1)):.3f}"
    sub += (f", thresholds from {nperm.group(1)} rotations (seed {seed.group(1)})"
            if nperm and seed else ", no permutation threshold")

    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" '
        f'viewBox="0 0 {W} {H}" font-family="sans-serif" role="img">',
        "<style>"
        ".bg{fill:#fff}.fg{fill:#333}.grid{stroke:#e8e8e8}.axis{stroke:#999}"
        ".pt{fill:#2b6cb0}.ptalt{fill:#4299e1}.thr{stroke:#c53030;stroke-dasharray:6 3}"
        ".thr2{stroke:#dd6b20;stroke-dasharray:3 3}.lab{font-size:11px;fill:#555}"
        ".ttl{font-size:15px;font-weight:bold;fill:#111}.sub{font-size:11px;fill:#666}"
        "@media (prefers-color-scheme: dark){.bg{fill:#111}.fg{fill:#eee}"
        ".grid{stroke:#2a2a2a}.pt{fill:#63b3ed}.ptalt{fill:#90cdf4}"
        ".thr{stroke:#fc8181}.thr2{stroke:#f6ad55}.lab{fill:#bbb}.ttl{fill:#fff}.sub{fill:#999}}"
        "</style>",
        f'<rect class="bg" width="{W}" height="{H}"/>',
        f'<text class="ttl" x="{L}" y="28">{title}</text>',
        f'<text class="sub" x="{L}" y="46">{sub}</text>',
    ]
    for step in range(0, ymax + 1, max(1, ymax // 5)):
        y = Y(step)
        parts.append(f'<line class="grid" x1="{L}" y1="{y:.1f}" x2="{L + pw}" y2="{y:.1f}"/>')
        parts.append(f'<text class="lab" x="{L - 8}" y="{y + 4:.1f}" text-anchor="end">{step}</text>')
    parts.append(f'<line class="axis" x1="{L}" y1="{T}" x2="{L}" y2="{T + ph}"/>')
    for index, c in enumerate(order):
        colour = "pt" if index % 2 == 0 else "ptalt"
        for pos, lod in by[c]:
            parts.append(f'<circle class="{colour}" cx="{X(c, pos):.1f}" cy="{Y(lod):.1f}" r="1.6"/>')
        centre = L + (off[c] + by[c][-1][0] / 2) / tot * pw
        parts.append(f'<text class="lab" x="{centre:.1f}" y="{T + ph + 16}" '
                     f'text-anchor="middle">{c}</text>')
    for value, label_text, dash in thresholds:
        y = Y(value)
        parts.append(f'<line class="thr" x1="{L}" y1="{y:.1f}" x2="{L + pw}" y2="{y:.1f}" '
                     f'stroke-dasharray="{dash}"/>')
        parts.append(f'<text class="lab" x="{L + pw - 4}" y="{y - 4:.1f}" '
                     f'text-anchor="end">{label_text}: LOD {value:.2f}</text>')
    parts.append(f'<text class="lab" x="{L - 44}" y="{T - 10}">LOD</text>')
    parts.append(
        f'<desc>The highest peak is LOD {top_lod:.2f} on chromosome {top[chr_i]} at '
        f'{float(top[pos_i]):.1f} Mb ({top[name_i]}).'
        + ("" if not thresholds else
           " Genome-wide threshold (alpha 0.05) LOD "
           + f"{[t[0] for t in thresholds if 'alpha 0.05' in t[1]][0]:.2f}.")
        + "</desc>")
    parts.append("</svg>")
    open(a.out, "w").write("\n".join(parts))
    print(f"BulkLMM scan. The highest peak is LOD {top_lod:.2f} on chromosome {top[chr_i]} "
          f"at {float(top[pos_i]):.1f} Mb ({top[name_i]}).")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())