about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 18:14:29 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 18:14:29 +0000
commit304b92e310df9570a67ef3cdd3bbcc714569bc83 (patch)
tree9ed8dbda8f62f23f04e255bc31d41093a7878eda /scripts
parent061b76a5d963b7d5e2ce9d858094b305929766f2 (diff)
downloadgenenetwork4-304b92e310df9570a67ef3cdd3bbcc714569bc83.tar.gz
correlation: PC traits as basket columns, and compare-two-traits
**PC traits.** `pca.traits` carries each component *as a trait*: PC1, PC2, ...
with a score per individual, so a component can be used the way GN2's "PCA
traits" are -- correlated, mapped, plotted, saved. Scores are the standardised
values projected onto the loadings, standardised with the sample standard
deviation because that is what the correlation matrix was built from; a
constant trait has no z-score and refuses rather than filling a zero. They live
on the complete cases of the kept traits (31 of 34 in the fixture), which is the
honest reading of "a PCA is defined on a rectangle".

The module story is a basket: POST /baskets with a PC's values gives a
per-user, versioned, digest-recorded column (verified: 201, revision 1, values
read back), which the mapping and plotting endpoints already accept. No new
store, no new dataset concept.

**Compare traits.** POST /compute/compare takes two trait references, keeps the
individuals with a value for both, and returns r, p, n *and* the pairs -- the
statistic and the data behind it. It agrees with the matrix: the same pair is
r = 0.6756270426459695 in both. POST /plot/compare draws the scatter (6 303
bytes) with the individual's name in each tooltip and the OLS line implied by r
and the two means; nothing is refitted.

Monitor gained compute-compare and plot-compare; full run 49 ok, 0 failed, 1
skipped.

Not done, deliberately: limit_to/ids_only/names_only. The listing handlers
return typed rows (Envelope<Vec<TraitInfo>>), so "names only" is a shape change
in every one of them -- a pass of its own rather than a query parameter.
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/plot-compare.py124
1 files changed, 124 insertions, 0 deletions
diff --git a/scripts/plot-compare.py b/scripts/plot-compare.py
new file mode 100755
index 0000000..77aeae2
--- /dev/null
+++ b/scripts/plot-compare.py
@@ -0,0 +1,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()