diff options
Diffstat (limited to 'scripts/plot-genotypes.py')
| -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()) |
