From b3811de4f2fb0e1d65ade757ad3ea992eb3f9f67 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 10 Nov 2026 22:35:45 +0000 Subject: traits: genotypes at a confirmed peak, and the plot of them Returning genotypes is the one thing this API otherwise never does, so it is fenced and the fence is the feature: GET /groups/{group}/traits/{trait_id}/peak-genotypes?marker= * the server re-runs the R/qtl scan for the trait -- the same machinery and gate as /compute/rqtl -- and takes the peak from that run, rather than trusting a client that names a marker; * the marker must lie within ?window= Mb of that peak (default 10), or the answer is 422 not_the_peak quoting the peak's marker, chromosome, Mb and LOD; * the peak must reach ?min_lod= (default 3), or 422 not_a_hit; * only animals that have a value for the trait are listed, and only this marker's calls. Nothing else of the matrix leaves. On DOL 10003 that is UNCHS026345 (chr9 75.76 Mb, LOD 5.86) with 192 animals across A 110 / B 8 / H 74 -- the two a class of eight being exactly the thing worth seeing. POST /plot/genotypes draws R/qtl's Fig 4.1 from it: post the reply's `animals` (or its `genotypes` map) with the trait's values and get an SVG with one point per animal, genotype class across, value up, class means marked. Nothing is recomputed -- the plot is of the numbers the client sends, like the other plots. New script scripts/plot-genotypes.py (stdlib-only SVG, like its siblings) and the GENOTYPE_PLOTTER key. tests/peakgenotypes.rs: the peak's calls for animals with values (with the counts agreeing with the rows), the SVG, and a marker on another chromosome refused with the peak quoted. Also keeps /compute/rqtl's error order: naming both a group and a file is "ambiguous" even when the request also forgot its values. --- scripts/plot-genotypes.py | 134 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100755 scripts/plot-genotypes.py (limited to 'scripts/plot-genotypes.py') diff --git a/scripts/plot-genotypes.py b/scripts/plot-genotypes.py new file mode 100755 index 0000000..99f409a --- /dev/null +++ b/scripts/plot-genotypes.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Plot a trait's values grouped by genotype class at one marker, as one SVG. + +This is the picture R/qtl's book uses to look at a QTL by hand (Fig 4.1): +each animal is a point, x is its genotype call at the peak marker, y is its +phenotype value. A class whose points sit apart from the others is what a +mapping score is made of -- and a class with two points is a warning. + +Input is the JSON the peak-genotypes endpoint returns, with the trait's +values beside it: + + {"marker": "UNC26663082", "chr": "16", + "points": [{"individual": "TB001", "genotype": "B", "value": 3.4}, ...]} + + python3 plot-genotypes.py points.json -o genotypes.svg + +Standard library only; writes plain SVG (light/dark aware), like the other +plotters here. +""" +import argparse, json, sys + +WIDTH, HEIGHT = 760, 420 +MARGIN_LEFT, MARGIN_RIGHT = 70, 24 +MARGIN_TOP, MARGIN_BOTTOM = 54, 62 + +# A deterministic jitter: two animals with one call would otherwise land on +# top of each other, and a stack of points is a fact about the data (many +# animals, one class), not noise to hide. +def jitter(index, count): + if count <= 1: + return 0.0 + step = 0.6 / max(count - 1, 1) + return (index - (count - 1) / 2.0) * step + + +def esc(text): + return (str(text).replace("&", "&").replace("<", "<").replace(">", ">") + .replace('"', """)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("document", help="JSON: marker, optional chr, points[]") + ap.add_argument("--trait", + default=json.loads(open(sys.argv[1]).read()).get("trait", "trait")) + ap.add_argument("--title", default=None) + ap.add_argument("-o", "--out", default=None) + arguments = ap.parse_args() + + document = json.load(open(arguments.document)) + points = [p for p in document.get("points", []) if p.get("value") is not None] + if not points: + print("no points with a value", file=sys.stderr) + return 1 + marker = document.get("marker", "marker") + chromosome = document.get("chr") + title = arguments.title or f"{arguments.trait}: {marker}" + ( + f" (chr {chromosome})" if chromosome else "") + + classes = sorted({str(p["genotype"]) for p in points}) + values = [float(p["value"]) for p in points] + low, high = min(values), max(values) + if high == low: + high = low + 1.0 + span = high - low + + plot_width = WIDTH - MARGIN_LEFT - MARGIN_RIGHT + plot_height = HEIGHT - MARGIN_TOP - MARGIN_BOTTOM + + def y_of(value): + return MARGIN_TOP + plot_height * (1 - (value - low) / span) + + def x_of(class_index): + return MARGIN_LEFT + plot_width * (class_index + 0.5) / len(classes) + + parts = [ + f'', + "", + f'', + f'{esc(title)}', + f'' + f'genotype at {esc(marker)} ({len(points)} animals with a value)', + ] + + # Y grid and labels. + for step in range(0, 5): + value = low + span * step / 4.0 + y = y_of(value) + parts.append(f'') + parts.append(f'{value:.2f}') + parts.append(f'') + + # Points, class by class, with the class mean drawn through them. + for index, genotype in enumerate(classes): + members = [p for p in points if str(p["genotype"]) == genotype] + centre = x_of(index) + for order, point in enumerate(sorted(members, key=lambda p: float(p["value"]))): + x = centre + jitter(order, len(members)) * plot_width / len(classes) + parts.append(f'{esc(point.get("individual", ""))}: ' + f'{float(point["value"]):.3f}') + mean = sum(float(p["value"]) for p in members) / len(members) + half = 0.32 * plot_width / len(classes) + parts.append(f'') + parts.append(f'{esc(genotype)} (n={len(members)})') + parts.append(f'mean {mean:.2f}') + parts.append("") + + out = arguments.out + if out: + open(out, "w").write("\n".join(parts)) + print(f"wrote {out}", file=sys.stderr) + else: + print("\n".join(parts)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) -- cgit 1.4.1