about summary refs log tree commit diff
path: root/scripts/plot-rqtl.py
blob: 73d8c51efc3a8d30f60a3620ef5fd89a49f0c2b4 (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
#!/usr/bin/env python3
"""Manhattan-style LOD plot of a GeneNetwork4 R/qtl result, as one SVG panel.

Input is the JSON response of POST /gn4/compute/rqtl (saved as-is).
If the request had nperm > 0, the significant and suggestive thresholds
from `data.permutation` are drawn as dashed lines.

    python3 plot.py r20010_p100.json --trait 20010 -o r20010_lod_perm.svg

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/rqtl response (JSON)")
    ap.add_argument("-o", "--out", default="rqtl_lod.svg")
    ap.add_argument("--trait", default="", help="trait label for the title, e.g. 20010")
    ap.add_argument("--title", default=None, help="override the title text")
    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]}")
    res = doc["data"]
    rows = res["markers"]            # [name, chr, pos_mb, lod]
    perm = res.get("permutation")
    thr = []                          # (value, label, dash)
    if perm:
        thr = [(perm["significant"], "significant (95%)", "7 4"),
               (perm["suggestive"], "suggestive", "2 4")]
    nperm = len(perm["values"]) if perm and perm.get("values") else 0

    notes = " ".join(doc.get("notes", []))
    m = re.search(r"(\d+) of (\d+) supplied values", notes)
    ver = re.search(r"version (\S+?),", notes)
    nstr = f"{m.group(1)} strains" if m else ""
    panel = ver.group(1) if ver else ""

    by = {}
    for name, c, pos, lod in rows:
        by.setdefault(str(c), []).append((pos, lod))
    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[3])
    ymax = max(4, math.ceil(max([top[3]] + [t[0] for t in thr]) + 0.3))
    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 - v / ymax * ph
    tx, ty = X(str(top[1]), top[2]), Y(top[3])

    label = f"trait {a.trait}" if a.trait else "R/qtl scan"
    title = a.title or f"{label}: LOD along the genome"
    sub = "R/qtl scanone (Haley-Knott)" + (f", {panel}" if panel else "") + (f", {nstr}" if nstr else "")
    sub += f", thresholds from {nperm} permutations" if thr else ", no permutation threshold"
    desc = (f"R/qtl scan. The highest peak is LOD {top[3]:.2f} on chromosome {top[1]} "
            f"at {top[2]:.1f} Mb ({top[0]})."
            + (f" Permutation thresholds from {nperm} permutations: "
               f"significant LOD {thr[0][0]:.2f}, suggestive LOD {thr[1][0]:.2f}." if thr else ""))

    s = [f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" aria-labelledby="t d" font-family="system-ui,-apple-system,Segoe UI,sans-serif">
<title id="t">{title}</title>
<desc id="d">{desc}</desc>
<style>
:root{{--surface:#fcfcfb;--ink:#0b0b0b;--ink2:#52514e;--grid:#e6e5e1;--band:#f3f2ef;--s1:#2a78d6}}
@media (prefers-color-scheme:dark){{:root{{--surface:#1a1a19;--ink:#f0efec;--ink2:#c3c2b7;--grid:#333330;--band:#222220;--s1:#3987e5}}}}
text{{fill:var(--ink2);font-size:12px}} .ttl{{fill:var(--ink);font-size:16px;font-weight:600}} .ann{{fill:var(--ink);font-size:12px}}
</style>
<rect width="{W}" height="{H}" fill="var(--surface)"/>
<text class="ttl" x="{L}" y="26">{title}</text>
<text x="{L}" y="46">{sub}</text>''']
    for i, c in enumerate(order):
        if i % 2 == 0:
            x0, x1 = X(c, 0), X(c, by[c][-1][0])
            s.append(f'<rect x="{x0:.1f}" y="{T}" width="{x1 - x0:.1f}" height="{ph}" fill="var(--band)"/>')
    for v in range(0, ymax + 1):
        y = Y(v)
        s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" stroke="var(--grid)" stroke-width="1"/>')
        s.append(f'<text x="{L - 8}" y="{y + 4:.1f}" text-anchor="end">{v}</text>')
    s.append(f'<text transform="translate(16 {T + ph / 2}) rotate(-90)" text-anchor="middle">LOD</text>')
    for c in order:
        xm = (X(c, 0) + X(c, by[c][-1][0])) / 2
        s.append(f'<text x="{xm:.1f}" y="{T + ph + 18}" text-anchor="middle">{c}</text>')
    s.append(f'<text x="{L + pw / 2}" y="{H - 10}" text-anchor="middle">Chromosome</text>')
    for c in order:
        pts = " ".join(f"{X(c, p):.1f},{Y(l):.1f}" for p, l in by[c])
        s.append(f'<polyline points="{pts}" fill="none" stroke="var(--s1)" stroke-width="1.5" stroke-linejoin="round"/>')
    for v, name, dash in thr:
        y = Y(v)
        s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" stroke="var(--ink2)" stroke-width="1.25" stroke-dasharray="{dash}"/>')
        s.append(f'<text x="{W - R - 4}" y="{y - 5:.1f}" text-anchor="end">{name}  LOD {v:.2f}</text>')
    s.append(f'<circle cx="{tx:.1f}" cy="{ty:.1f}" r="4.5" fill="var(--s1)" stroke="var(--surface)" stroke-width="2"><title>{top[0]}: chr{top[1]} {top[2]:.1f} Mb, LOD {top[3]:.2f}</title></circle>')
    s.append(f'<text class="ann" x="{tx + 10:.1f}" y="{ty + 4:.1f}">chr{top[1]} {top[2]:.0f} Mb, LOD {top[3]:.2f}</text>')
    s.append("</svg>")
    open(a.out, "w").write("\n".join(s))
    print(f"wrote {a.out}: peak {top[0]} chr{top[1]} {top[2]:.1f} Mb LOD {top[3]:.2f}"
          + (f"; thresholds sig {thr[0][0]:.2f} sugg {thr[1][0]:.2f}" if thr else ""))


if __name__ == "__main__":
    main()