diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 22:35:45 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 22:35:45 +0000 |
| commit | b3811de4f2fb0e1d65ade757ad3ea992eb3f9f67 (patch) | |
| tree | aad2b1cb2b97f08e202f1931bcd590ecba408e56 /scripts | |
| parent | 62cc5f73cb94fe85c31a2f177d1d150e643e84b1 (diff) | |
| download | genenetwork4-b3811de4f2fb0e1d65ade757ad3ea992eb3f9f67.tar.gz | |
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=<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.
Diffstat (limited to 'scripts')
| -rwxr-xr-x | scripts/plot-genotypes.py | 134 |
1 files changed, 134 insertions, 0 deletions
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'<svg xmlns="http://www.w3.org/2000/svg" width="{WIDTH}" height="{HEIGHT}" ' + f'viewBox="0 0 {WIDTH} {HEIGHT}" font-family="sans-serif">', + "<style>" + ".bg{fill:#ffffff}.fg{fill:#222222}.axis{stroke:#888888;stroke-width:1}" + ".grid{stroke:#e4e4e4;stroke-width:1}.pt{fill:#2b6cb0;fill-opacity:0.75}" + ".mean{stroke:#c53030;stroke-width:2}.label{font-size:12px;fill:#444444}" + ".title{font-size:15px;fill:#111111;font-weight:bold}" + "@media (prefers-color-scheme: dark){" + ".bg{fill:#111111}.fg{fill:#eeeeee}.grid{stroke:#2a2a2a}.pt{fill:#63b3ed}" + ".mean{stroke:#fc8181}.label{fill:#bbbbbb}.title{fill:#ffffff}}" + "</style>", + f'<rect class="bg" width="{WIDTH}" height="{HEIGHT}"/>', + f'<text class="title" x="{MARGIN_LEFT}" y="30">{esc(title)}</text>', + f'<text class="label" x="{MARGIN_LEFT}" y="{HEIGHT - 30}">' + f'genotype at {esc(marker)} ({len(points)} animals with a value)</text>', + ] + + # Y grid and labels. + for step in range(0, 5): + value = low + span * step / 4.0 + y = y_of(value) + parts.append(f'<line class="grid" x1="{MARGIN_LEFT}" y1="{y:.1f}" ' + f'x2="{WIDTH - MARGIN_RIGHT}" y2="{y:.1f}"/>') + parts.append(f'<text class="label" x="{MARGIN_LEFT - 8}" y="{y + 4:.1f}" ' + f'text-anchor="end">{value:.2f}</text>') + parts.append(f'<line class="axis" x1="{MARGIN_LEFT}" y1="{MARGIN_TOP}" ' + f'x2="{MARGIN_LEFT}" y2="{MARGIN_TOP + plot_height}"/>') + + # 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'<circle class="pt" cx="{x:.1f}" cy="{y_of(float(point["value"])):.1f}" ' + f'r="3.2"><title>{esc(point.get("individual", ""))}: ' + f'{float(point["value"]):.3f}</title></circle>') + mean = sum(float(p["value"]) for p in members) / len(members) + half = 0.32 * plot_width / len(classes) + parts.append(f'<line class="mean" x1="{centre - half:.1f}" y1="{y_of(mean):.1f}" ' + f'x2="{centre + half:.1f}" y2="{y_of(mean):.1f}"/>') + parts.append(f'<text class="label" x="{centre:.1f}" y="{HEIGHT - MARGIN_BOTTOM + 20}" ' + f'text-anchor="middle">{esc(genotype)} (n={len(members)})</text>') + parts.append(f'<text class="label" x="{centre:.1f}" y="{HEIGHT - MARGIN_BOTTOM + 36}" ' + f'text-anchor="middle">mean {mean:.2f}</text>') + parts.append("</svg>") + + 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()) |
