From 304b92e310df9570a67ef3cdd3bbcc714569bc83 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:14:29 +0000 Subject: 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>), so "names only" is a shape change in every one of them -- a pass of its own rather than a query parameter. --- scripts/plot-compare.py | 124 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100755 scripts/plot-compare.py (limited to 'scripts/plot-compare.py') 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''' +{title} +{desc} + + +{title} +{sub}'''] + + for step in range(5): + value = ymin + (ymax - ymin) * step / 4 + y = Y(value) + s.append(f'') + s.append(f'{value:.3g}') + for step in range(5): + value = xmin + (xmax - xmin) * step / 4 + x = X(value) + s.append(f'{value:.3g}') + + # 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'') + + for row in pairs: + name, xv, yv = row[0], float(row[1]), float(row[2]) + s.append(f'{name}: {xv:.4g} vs {yv:.4g}') + + s.append(f'' + f'{second.get("trait_name", "b")}') + s.append(f'' + f'{first.get("trait_name", "a")}') + s.append(f'r = {r_value:+.4f}' if isinstance(r_value, (int, float)) else "") + s.append(f'n = {n}') + s.append(f'dashed: OLS') + s.append(f'from r and the means') + s.append("") + open(a.out, "w").write("\n".join(s) + "\n") + print(f"{a.out}: {n} points, r {r_value}") + + +if __name__ == "__main__": + main() -- cgit 1.4.1