about summary refs log tree commit diff
path: root/scripts/plot-compare.py
blob: 77aeae258bd2ab6c16169aabbefb7b131a685bc0 (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
#!/usr/bin/env python3
"""Scatter plot of two compared traits, as one SVG panel.

Input is the JSON response of POST /compute/compare (saved as-is): the paired
values, the individual names, and the r/p/n they came with. The line is the
ordinary least-squares line implied by r and the two means -- nothing is
refitted here, and nothing is invented beyond what the reply carries.

    python3 plot-compare.py compare.json -o compare.svg --trait "1427571_at vs 1427641_at"

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

W, H = 760, 520
L, R, T, B = 64, 150, 78, 64


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("result", help="saved /compute/compare response (JSON)")
    ap.add_argument("-o", "--out", default="compare.svg")
    ap.add_argument("--trait", default="", help="label for the title")
    ap.add_argument("--title", default=None)
    a = ap.parse_args()

    doc = json.load(open(a.result))
    data = doc.get("data") if isinstance(doc.get("data"), dict) else doc
    pairs = data.get("pairs") or []
    if len(pairs) < 2:
        sys.exit(f"{a.result}: no `pairs` -- post a /compute/compare reply")
    r_value = data.get("r")
    p_value = data.get("p")
    n = data.get("n") or len(pairs)
    first = (data.get("a") or {})
    second = (data.get("b") or {})

    xs = [float(row[1]) for row in pairs]
    ys = [float(row[2]) for row in pairs]
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)
    pad_x = (xmax - xmin) * 0.06 or 0.5
    pad_y = (ymax - ymin) * 0.06 or 0.5
    xmin, xmax = xmin - pad_x, xmax + pad_x
    ymin, ymax = ymin - pad_y, ymax + pad_y

    pw, ph = W - L - R, H - T - B

    def X(v):
        return L + (v - xmin) / (xmax - xmin) * pw

    def Y(v):
        return T + ph - (v - ymin) / (ymax - ymin) * ph

    label = a.trait or (f"{first.get('trait_name', 'a')} vs {second.get('trait_name', 'b')}")
    title = a.title or f"{label}: scatter"
    method = data.get("method") or "pearson"
    sub = (f"{method} r = {r_value:+.4f}" if isinstance(r_value, (int, float)) else f"{method} r = ?")
    if isinstance(p_value, (int, float)):
        sub += f", p = {p_value:.3g}"
    sub += f", n = {n}"
    if data.get("only_one_side"):
        sub += f"  ·  {data['only_one_side']} individual(s) had a value for only one trait"
    desc = (f"Scatter of {first.get('trait_name', 'a')} ({first.get('dataset', '')}) against "
            f"{second.get('trait_name', 'b')} ({second.get('dataset', '')}) over {n} individuals, "
            f"{method} r {r_value}.")

    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;--dot:#2a6fdb;--line:#eb6834}}
@media (prefers-color-scheme:dark){{:root{{--surface:#1a1a19;--ink:#f0efec;--ink2:#c3c2b7;--grid:#333330;--dot:#5b8def;--line:#d95926}}}}
text{{fill:var(--ink2);font-size:12px}} .ttl{{fill:var(--ink);font-size:16px;font-weight:600}}
</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 step in range(5):
        value = ymin + (ymax - ymin) * step / 4
        y = Y(value)
        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">{value:.3g}</text>')
    for step in range(5):
        value = xmin + (xmax - xmin) * step / 4
        x = X(value)
        s.append(f'<text x="{x:.1f}" y="{T + ph + 16}" text-anchor="middle">{value:.3g}</text>')

    # Least-squares line implied by r and the two standard deviations.
    if isinstance(r_value, (int, float)) and n > 2:
        mean_x = sum(xs) / n
        mean_y = sum(ys) / n
        var_x = sum((v - mean_x) ** 2 for v in xs) / (n - 1)
        var_y = sum((v - mean_y) ** 2 for v in ys) / (n - 1)
        if var_x > 0 and var_y > 0:
            slope = r_value * (var_y / var_x) ** 0.5
            y_at = lambda v: mean_y + slope * (v - mean_x)
            s.append(f'<line x1="{X(xmin):.1f}" y1="{Y(y_at(xmin)):.1f}" '
                     f'x2="{X(xmax):.1f}" y2="{Y(y_at(xmax)):.1f}" stroke="var(--line)" '
                     f'stroke-width="2" stroke-dasharray="6 4"/>')

    for row in pairs:
        name, xv, yv = row[0], float(row[1]), float(row[2])
        s.append(f'<circle cx="{X(xv):.1f}" cy="{Y(yv):.1f}" r="4" fill="var(--dot)" '
                 f'fill-opacity="0.85"><title>{name}: {xv:.4g} vs {yv:.4g}</title></circle>')

    s.append(f'<text transform="translate(18 {T + ph / 2}) rotate(-90)" text-anchor="middle">'
             f'{second.get("trait_name", "b")}</text>')
    s.append(f'<text x="{L + pw / 2:.1f}" y="{H - 16}" text-anchor="middle">'
             f'{first.get("trait_name", "a")}</text>')
    s.append(f'<text x="{W - R + 12}" y="{T + 14}">r = {r_value:+.4f}</text>' if isinstance(r_value, (int, float)) else "")
    s.append(f'<text x="{W - R + 12}" y="{T + 34}">n = {n}</text>')
    s.append(f'<text x="{W - R + 12}" y="{T + 54}" opacity="0.75">dashed: OLS</text>')
    s.append(f'<text x="{W - R + 12}" y="{T + 70}" opacity="0.75">from r and the means</text>')
    s.append("</svg>")
    open(a.out, "w").write("\n".join(s) + "\n")
    print(f"{a.out}: {n} points, r {r_value}")


if __name__ == "__main__":
    main()