diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-27 11:22:38 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-27 11:22:38 +0000 |
| commit | cd9f46633bcc55ab2a72cda1a0f1a667e79c2e57 (patch) | |
| tree | e56b04e85f9d69b28695ed57345c1dff28d8d14c /scripts | |
| parent | f76043bf82b6c86b5e844b27b53e957d770aeb33 (diff) | |
| parent | 4f609454ba5b8db543863d6f20b042ca15cfe99f (diff) | |
| download | genenetwork4-cd9f46633bcc55ab2a72cda1a0f1a667e79c2e57.tar.gz | |
Merge branch 'main' into search/extract-engine-merge
Diffstat (limited to 'scripts')
| -rwxr-xr-x | scripts/geno-to-bimbam.py | 181 | ||||
| -rwxr-xr-x | scripts/gn4-log.py | 72 | ||||
| -rwxr-xr-x | scripts/make-mdb.sh | 150 | ||||
| -rwxr-xr-x | scripts/plot-compare.py | 124 | ||||
| -rw-r--r-- | scripts/plot-rqtl.py | 9 | ||||
| -rwxr-xr-x | scripts/prepare-genotypes.sh | 114 | ||||
| -rwxr-xr-x | scripts/qtl2-convert-geno.R | 145 | ||||
| -rwxr-xr-x | scripts/qtl2-impute-bimbam.R | 162 | ||||
| -rwxr-xr-x | scripts/wire-listing.py | 65 |
9 files changed, 1019 insertions, 3 deletions
diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py new file mode 100755 index 0000000..b31829d --- /dev/null +++ b/scripts/geno-to-bimbam.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Project a GeneNetwork `.geno` panel to the BIMBAM pair GEMMA reads. + +Why this exists: the deployment's `genotype/bimbam/<version>_geno.txt` files +were generated by a converter that only understands the *biallelic* letter +codes a `.geno` header declares (`@mat:AB`, `@pat:CD` -> calls are "A"/"B"). +A four-founder panel declares the same two-letter header but writes its calls +as numeric codes, so every cell fell through to missing: HET3-ITP.12's BIMBAM +was 23 MB of "NA", which is why every GEMMA route refuses it (the panel has +45.8% data in the `.geno`) while R/qtl, which reads the `.geno`, runs fine. + +What the projection is. A 4-way panel (`@type:4-way`, `@mat:AB`, `@pat:CD`) +has eight genotype classes: the four founder homozygotes and the four +maternal-by-paternal combinations. Biallelic BIMBAM can carry one contrast, +and the one this tool takes is **maternal- versus paternal-derived**: a mouse +that inherited both alleles from the `@mat` founders scores 0, both from the +`@pat` founders scores 1, and a heterozygote (one from each) scores 0.5 -- +the mean-genotype scale BIMBAM and GEMMA already use. That projection needs +no knowledge of which numeric code is which heterozygous *pair*, only which +codes are the maternal homozygotes, the paternal homozygotes and everything +else, so it cannot silently transpose two founder alleles. + +Which codes are which is NOT assumed: `--codes` is required, because getting +it wrong is silent. Tried on HET3-ITP.12 with the only table its header +supports (1,2 -> 0; 3,4 -> 1; 5..8 -> 0.5): the projection produced a real +BIMBAM (2.6 M of 5.8 M calls) and pangemma ran on it for 21.9 min, but +answered no associations at all -- 881 of 893 markers came out with exactly +zero variance, because an advanced 4-way intercross is ~99.4% heterozygous, so +"maternal versus paternal dosage" is a constant. A parent-of-origin contrast +is therefore useless for that panel; what it needs is a *founder* contrast +(dosage of one founder's allele), and the numeric-code -> founder-pair table +is not in the `.geno` header, this repository, or the panel's `rdata/*.RData` +(which holds qtl2 allele-probability arrays, not calls). That is a modelling +decision for whoever owns the panel -- pick the founders, then pass the table +here. R/qtl remains the engine for 4-way panels (docs/genotypes.md). + + scripts/geno-to-bimbam.py --geno HET3-ITP.12.geno --out DIR --pairwise +writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt. + +NOT every panel needs a fixed table. A panel whose markers are each biallelic +but whose *code pair* varies from marker to marker (HET3-ITP.12: 486 markers +carry codes {5,6}, 395 carry {7,8}, a handful more) needs `--pairwise`: for +each marker its two present codes become 0 and 1 (lower code -> 0), anything +else missing. That is the biallelic projection the panel actually supports -- +a single global table cannot express it, and forcing one there was measured to +be constant (881 of 893 markers with zero variance). +""" + +import argparse +import sys + + +def read_geno(path): + """Yield (chr, locus, cM, Mb, calls) for every marker row.""" + header = None + with open(path) as handle: + for line in handle: + line = line.rstrip("\n") + if not line or line.startswith("#") or line.startswith("@"): + continue + fields = line.split("\t") + if header is None: + if fields[0].lower() != "chr": + continue + header = fields + continue + if len(fields) < 5: + continue + yield fields[0], fields[1], fields[2], fields[3], fields[4:] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--geno", required=True, help="the .geno panel to project") + parser.add_argument("--out", required=True, help="directory for the pair") + parser.add_argument( + "--name", + default=None, + help="basename for the outputs (default: the .geno's name)", + ) + parser.add_argument( + "--pairwise", + action="store_true", + help="per-marker biallelic coding: each marker's two present codes " + "become 0 and 1. Use this for a panel whose code pair varies by " + "marker (see the docstring); it conflicts with --codes.", + ) + parser.add_argument( + "--codes", + required=False, + help="projection table: '<dosage>=<code,code,...>' separated by ';', " + "e.g. '0=1,2;1=3,4;0.5=5,6,7,8' (required: a guessed table produces a " + "silently empty projection, see the docstring)", + ) + args = parser.parse_args() + + if bool(args.pairwise) == bool(args.codes): + sys.exit("give exactly one of --pairwise or --codes") + table = {} + for part in (args.codes or "").split(";"): + if not part: + continue + dosage, codes = part.split("=") + for code in codes.split(","): + table[code.strip()] = dosage.strip() + + import os + + name = args.name or os.path.basename(args.geno).removesuffix(".geno") + geno_out = os.path.join(args.out, f"{name}_geno.txt") + snps_out = os.path.join(args.out, f"{name}_snps.txt") + + seen = {"markers": 0, "calls": 0, "missing": 0} + per_dosage = {} + pairwise_seen = {} + with open(geno_out, "w") as geno, open(snps_out, "w") as snps: + for chrom, locus, _cm, mb, calls in read_geno(args.geno): + marker_table = table + if args.pairwise: + present = sorted({c.strip() for c in calls if c.strip() not in ("NA", "", ".")}) + # Exactly two classes is what a biallelic marker looks like. + # One class (monomorphic) or more than two (a genuinely + # multi-allelic marker, which BIMBAM cannot carry) is left + # missing rather than silently folded. + if len(present) == 2: + marker_table = {present[0]: "0", present[1]: "1"} + pairwise_seen[(present[0], present[1])] = ( + pairwise_seen.get((present[0], present[1]), 0) + 1 + ) + else: + marker_table = {} + projected = [] + for call in calls: + call = call.strip() + dosage = marker_table.get(call) + if dosage is None: + projected.append("NA") + seen["missing"] += 1 + else: + projected.append(dosage) + per_dosage[dosage] = per_dosage.get(dosage, 0) + 1 + seen["calls"] += 1 + # BIMBAM: marker, allele1, allele0, then one mean genotype per + # individual in column order (X/Y are the placeholders the + # deployment's other BIMBAM files use). + geno.write(f"{locus}, X, Y, " + ", ".join(projected) + "\n") + # The annotation file GEMMA takes as -a: marker, bp, chromosome. + # A `.geno` writes physical positions in Mb (`@scale:physic` and an + # "Mb" column); BIMBAM annotation wants bp, which is what the + # deployment's other `_snps.txt` files carry. + try: + position = str(int(round(float(mb) * 1e6))) + except (TypeError, ValueError): + position = "0" + snps.write(f"{locus}, {position}, {chrom}\n") + seen["markers"] += 1 + + if seen["markers"] == 0: + sys.exit("no marker rows: is this a .geno file?") + if seen["missing"] == seen["calls"]: + sys.exit( + "every call projected to missing -- the --codes table does not " + "match this panel's numeric codes" + ) + print( + f"{geno_out}: {seen['markers']} markers, {seen['calls'] - seen['missing']} " + f"calls projected ({100 * (1 - seen['missing'] / seen['calls']):.1f}% present), " + f"dosages {dict(sorted(per_dosage.items()))}" + ) + if args.pairwise: + print( + "per-marker code pairs: " + + ", ".join( + f"{a}/{b}: {n}" for (a, b), n in sorted(pairwise_seen.items(), key=lambda kv: -kv[1]) + ) + ) + print(f"{snps_out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py index a14e653..42031a2 100755 --- a/scripts/gn4-log.py +++ b/scripts/gn4-log.py @@ -25,6 +25,15 @@ Use it on a process log or a proxy log that carries `x-gn4-user`: scripts/gn4-log.py -f log.jsonl --json # enriched JSON, for jq scripts/gn4-log.py -f log.jsonl --summary # who ran what, counted +A compute request names its panel in its *body*, not its path, so the line +carries what the handler recorded about the work (`crate::usage`): `dataset`, +`group`, `source`, `trait`, `engine`, `cached`, `run`, and on `/search` the +query itself as `q` (the path has no query string on purpose). The table shows +them in a short suffix; `--datasets` and `--queries` count them: + + scripts/gn4-log.py -f log.jsonl --since 2026-11-20 --datasets + scripts/gn4-log.py -f log.jsonl --queries --limit 20 + Lines that are not JSON (a Ruby backtrace, a GEMMA progress bar) pass through unchanged unless --quiet; that is deliberate, because the process log interleaves them and dropping them would hide the interesting failures. @@ -150,6 +159,29 @@ def enrich(record: dict, registry: Registry, when: int | None) -> dict: return out +USAGE_FIELDS = ("dataset", "group", "source", "trait", "traits", "engine", "cached", "run") + + +def usage_suffix(record: dict) -> str: + """What the handler recorded about the work, short enough for a table. + + `q` is shown quoted (it is caller text and may contain spaces); the rest + as `key=value`. Nothing here is a secret: see `crate::usage`. + """ + parts = [] + if record.get("q") is not None: + parts.append(f'q="{record["q"]}"') + if record.get("type"): + parts.append(f"type={record['type']}") + if record.get("hits") is not None: + parts.append(f"hits={record['hits']}") + for field in USAGE_FIELDS: + value = record.get(field) + if value not in (None, ""): + parts.append(f"{field}={value}") + return " " + " ".join(parts) if parts else "" + + def format_line(record: dict, when: str) -> str: who = record.get("user") or "-" credential = record.get("scheme") or "-" @@ -165,6 +197,7 @@ def format_line(record: dict, when: str) -> str: f"{when or '-':<19} {who:<20} {credential:<34} " f"{record.get('method', '-'):<6} {record.get('status', '-'):>4} " f"{took:>6} ms {record.get('path', '')}" + f"{usage_suffix(record)}" ) @@ -179,6 +212,9 @@ def main() -> int: parser.add_argument("--grep", default=None, help="only lines containing this text (matches the raw line)") parser.add_argument("--json", action="store_true", help="emit enriched JSON instead of a table") parser.add_argument("--summary", action="store_true", help="count requests per caller and credential") + parser.add_argument("--datasets", action="store_true", help="count requests per dataset (and source), with the distinct callers") + parser.add_argument("--queries", action="store_true", help="count /search queries, most frequent first") + parser.add_argument("--limit", type=int, default=25, help="how many rows --datasets/--queries print (default 25)") parser.add_argument("--quiet", action="store_true", help="drop lines that are not request records") args = parser.parse_args() @@ -212,7 +248,8 @@ def main() -> int: # through in table mode -- the process log interleaves them, and # dropping them would hide the interesting failures -- but never # in a machine-readable mode. - if not args.quiet and not args.json and not args.summary: + if not (args.quiet or args.json or args.summary + or args.datasets or args.queries): print(line) continue rows.append((when, enrich(record, registry, None))) @@ -230,6 +267,39 @@ def main() -> int: print(f"{len(rows):>7} {'total':<{width}}") return 0 + if args.datasets: + # The question this file was written to answer: which data is used, + # by how many separate callers. Computes are attributed by what the + # handler recorded, reads by what the path spells out. + counts: Counter = Counter() + callers: dict[tuple[str, str], set[str]] = {} + for _, record in rows: + dataset, source = record.get("dataset"), record.get("source") or "-" + if not dataset: + continue + counts[(dataset, source)] += 1 + callers.setdefault((dataset, source), set()).add(record.get("user") or "-") + width = max((len(name) for (name, _) in counts), default=10) + print(f"{'requests':>8} {'callers':>7} {'dataset':<{width}} source") + for (dataset, source), count in counts.most_common(args.limit): + print(f"{count:>8} {len(callers[(dataset, source)]):>7} {dataset:<{width}} {source}") + unattributed = sum(1 for _, record in rows if not record.get("dataset")) + print(f"{len(rows) - unattributed:>8} {len({(u) for c in callers.values() for u in c}):>7} total (plus {unattributed} with no dataset recorded)") + return 0 + + if args.queries: + queries: Counter = Counter() + callers: dict[str, set[str]] = {} + for _, record in rows: + query = record.get("q") + if query is None: + continue + queries[query] += 1 + callers.setdefault(query, set()).add(record.get("user") or "-") + for query, count in queries.most_common(args.limit): + print(f"{count:>7} {len(callers[query]):>3} callers {query}") + return 0 + for when, record in rows: if args.json: print(json.dumps(record)) diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh new file mode 100755 index 0000000..e5b753e --- /dev/null +++ b/scripts/make-mdb.sh @@ -0,0 +1,150 @@ +#!/bin/sh +# make-mdb.sh -- build pangemma's genotype store (an LMDB environment) from a +# BIMBAM genotype file and its marker annotation. +# +# Two of gemma-wrapper's helpers do the work: +# +# anno2mdb.rb snps.txt -> <name>.snps.mdb (chr/pos -> marker name) +# geno2mdb.rb geno.txt --anno <name>.snps.mdb -> <name>.geno.mdb +# +# and this script exists for the three things they leave to the caller: +# +# 1. the lock file. An LMDB environment is data.mdb *plus* lock.mdb, and +# lock.mdb's bytes change on every open -- measured: 8d3d268b after writing, +# a different sha1 after one read-only open, different again after a +# read-write open, while data.mdb never changed. A directory whose hash is +# its identity (ravanan interns inputs by content) must therefore not +# contain one, so it is removed last and the tree is made read-only to stop +# anything recreating it. +# 2. the name. pangemma decides "this is an mdb" by looking for ".mdb" in the +# -g path (src/param.cpp:943), so the directory must end in .mdb and the +# outer name should say which translation it holds. +# 3. atomicity. A half-written environment must never be visible under the +# final name: build under a temporary name in the destination directory and +# rename when whole. +# +# scripts/make-mdb.sh --geno <bimbam geno> --snps <snps.txt> \ +# [--eval Gf|Gb|G0_1|G0_2] [--name NAME] [--out DIR] \ +# [--keep-missing] +# +# Missing genotypes are imputed to the marker's mean by default, because +# pangemma's mdb path cannot represent them: see the note further down. +# +# Prints the directory it built. Exit 2 on bad arguments, 1 on a maker failure. +set -eu + +geno= snps= eval_=Gf name= out=. keep_missing=no impute= cross_dir= probs_rds= +while [ $# -gt 0 ]; do + case $1 in + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --eval) eval_=$2; shift 2 ;; + --keep-missing) keep_missing=yes; shift ;; + --impute) impute=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs_rds=$2; shift 2 ;; + --name) name=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "make-mdb.sh: unknown argument $1" >&2; exit 2 ;; + esac +done +if [ "$impute" != qtl2 ]; then + [ -n "$geno" ] && [ -n "$snps" ] || + { echo "make-mdb.sh: --geno and --snps are required (or --impute qtl2)" >&2; exit 2; } + for f in "$geno" "$snps"; do + [ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; } + done +fi +case $eval_ in Gf|Gb|G0_1|G0_2) ;; *) echo "make-mdb.sh: unknown --eval $eval_" >&2; exit 2 ;; esac + +# The makers, and something to run them with. MAKE_MDB_ANNO / MAKE_MDB_GENO +# let a caller point at a different checkout; ANNO2MDB_OK is set by the caller +# when it has checked they exist. +ANNO=${ANNO2MDB:-anno2mdb.rb} +GENO=${GENO2MDB:-geno2mdb.rb} +for tool in "$ANNO" "$GENO"; do + command -v "$tool" >/dev/null 2>&1 || { echo "make-mdb.sh: $tool is not on PATH" >&2; exit 1; } +done + +mkdir -p "$out" +[ -n "$name" ] || name=$(basename "$geno" | sed 's/\.\(txt\|gz\|bimbam\)$//') +work=$(mktemp -d "$out/.$name.XXXXXX") +trap 'rm -rf "$work"' EXIT + +# 1. Where do the genotypes come from? With --impute qtl2 they come from +# R/qtl2's HMM (maxmarg on the cached genotype probabilities), which is the +# genotype set /compute/qtl2 maps on -- complete by construction, and +# predicted from flanking markers rather than averaged. That replaces both +# the BIMBAM and the snps file, so --geno/--snps are then optional. +if [ "$impute" = qtl2 ]; then + [ -n "$cross_dir" ] && [ -n "$probs_rds" ] || + { echo "make-mdb.sh: --impute qtl2 needs --cross DIR and --probs FILE.rds" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "make-mdb.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + "$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + "$cross_dir" "$probs_rds" "$work/hmm" "${IMPUTE_MINPROB:-0}" >/dev/null 2>&1 || + { echo "make-mdb.sh: qtl2 HMM imputation failed" >&2; exit 1; } + geno=$work/hmm.bimbam.txt + snps=$work/hmm.snps.txt + [ -n "$name" ] || name=$(basename "$cross_dir") +else + # The makers write <input>.mdb *beside their input* and take it as a + # positional argument, so they get links to work on: nothing is written + # next to the caller's files. + ln -s "$(cd "$(dirname "$geno")" && pwd)/$(basename "$geno")" "$work/geno.txt" + ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" + geno=$work/geno.txt + snps=$work/snps.txt +fi + +# 2. the annotation half. It is an intermediate: pangemma is given the snps +# file itself (-a) and only geno2mdb needs this database, so it is not kept. +# Both makers name their output after the *argument they were given* and write +# it in the current directory, so they run inside the work directory with bare +# names: an absolute path would put the .mdb beside the caller's inputs (measured: +# a hand run left a 2 MB .mdb inside gn4-data). +( cd "$work" && "$ANNO" "$(basename "$snps")" ) >/dev/null 2>&1 || + { echo "make-mdb.sh: anno2mdb.rb failed" >&2; exit 1; } +anno_db=$work/$(basename "$snps").mdb + +# 2. missing genotypes (only for raw input: the HMM output has no gaps). pangemma's mdb path has NO missing-data handling +# (src/gemma_io.cpp's mdb_calc_kin still carries the "[ ] handle missing +# data" TODO), and one NA poisons every cell: measured, a BIMBAM with 0.1% +# NAs gave a 235x235 matrix of -nan while the same data imputed gave a clean +# one, with "**** INFO: Done." and exit 0 either way. So NAs are replaced +# per marker by that marker's mean -- which is what GEMMA does to a BIMBAM +# before it looks at it -- unless --keep-missing asks otherwise. +if [ "$keep_missing" = no ] && [ "$impute" != qtl2 ]; then + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$work/geno-imputed.txt" + mv "$work/geno-imputed.txt" "$geno" +fi + +# 3. the genotypes, translated the way pangemma expects +( cd "$work" && "$GENO" --eval "$eval_" --anno "$(basename "$snps").mdb" "$(basename "$geno")" ) >/dev/null 2>&1 || + { echo "make-mdb.sh: geno2mdb.rb failed" >&2; exit 1; } +store=$work/$(basename "$geno").mdb + +# 4. the lock file. These environments are single files (MDB_NOSUBDIR), so the +# lock is a *sibling*, <name>.mdb-lock -- measured on a real store: every +# open recreates it with different bytes while the .mdb itself never changes. +# The .mdb is what gets interned and hashed (a File input hashes its +# content), so the lock only needs to go so the directory we hand out +# contains nothing but the store itself. +rm -f "$store-lock" "$anno_db-lock" +chmod a-w "$store" + +rm -f "$out/$name.geno.mdb" "$out/$name.geno.mdb-lock" +mv "$store" "$out/$name.geno.mdb" +trap 'rm -rf "$work"' EXIT +rm -rf "$work" +trap - EXIT +printf '%s\n' "$out/$name.geno.mdb" 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() diff --git a/scripts/plot-rqtl.py b/scripts/plot-rqtl.py index 73d8c51..b24a14f 100644 --- a/scripts/plot-rqtl.py +++ b/scripts/plot-rqtl.py @@ -28,8 +28,13 @@ def main(): if "data" not in doc: sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}") res = doc["data"] - rows = res["markers"] # [name, chr, pos_mb, lod] - perm = res.get("permutation") + # `data` is the marker array itself (a reply from before that change kept + # it under `data.markers`), and the permutation null sits beside it in + # meta; older replies carried it inside data. + rows = res if isinstance(res, list) else res["markers"] + perm = (doc.get("meta") or {}).get("permutation") or ( + res.get("permutation") if isinstance(res, dict) else None + ) thr = [] # (value, label, dash) if perm: thr = [(perm["significant"], "significant (95%)", "7 4"), diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh new file mode 100755 index 0000000..e6042a5 --- /dev/null +++ b/scripts/prepare-genotypes.sh @@ -0,0 +1,114 @@ +#!/bin/sh +# prepare-genotypes.sh -- one place where "how do we treat a missing genotype?" +# is decided, so the same question can be asked of every engine and the answers +# compared. +# +# --mode none leave the file as it is: GEMMA then does complete-case per +# marker and reports n_miss, and pangemma's lmdb store keeps +# the gaps (NaN for Gf, 255 for Gb) and mean-substitutes them +# per marker exactly as GEMMA does +# --mode mean replace each missing call by that marker's mean over the +# individuals that have one (cheap, but it invents a datum and +# deflates the variance) +# --mode hmm predict the missing calls from flanking markers with R/qtl2's +# HMM (maxmarg on genotype probabilities) -- the genotype set +# /compute/qtl2 maps on, and the one that does not invent a value +# +# scripts/prepare-genotypes.sh --mode mean|hmm|none \ +# --geno <bimbam geno> --snps <snps file> --out <prefix> \ +# [--cross <qtl2 cross dir>] [--probs <probs.rds|->] [--minprob N] \ +# [--individuals-file <names, one per line>] \ +# [--impute-script <qtl2-impute-bimbam.R>] +# +# A workflow job stages this script and the R one as separate inputs, so +# --impute-script is how it says where the R script landed; by hand it +# defaults to the file beside this one. +# +# Writes <prefix>.bimbam.txt and <prefix>.snps.txt and prints the prefix. +# Exits 2 on bad arguments, 1 when a step fails. +set -eu + +mode= geno= snps= out= cross_dir= probs= minprob=0 individuals_file= +# The HMM script normally sits beside this one. A caller that stages this +# script somewhere else (a workflow job, where it is a copied input and the R +# script is a second one) names it explicitly. +impute_script= +while [ $# -gt 0 ]; do + case $1 in + --mode) mode=$2; shift 2 ;; + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs=$2; shift 2 ;; + --minprob) minprob=$2; shift 2 ;; + --individuals-file) individuals_file=$2; shift 2 ;; + --impute-script) impute_script=$2; shift 2 ;; + -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; + esac +done + +case $mode in none|mean|hmm) ;; *) echo "prepare-genotypes.sh: --mode must be none, mean or hmm" >&2; exit 2 ;; esac +[ -n "$out" ] || { echo "prepare-genotypes.sh: --out is required" >&2; exit 2; } +# Absolute, before anything moves: the HMM script does setwd(cross_dir) and +# writes <prefix>.* from there, so a relative prefix would put the outputs in +# the cross directory instead of the caller's -- which in a workflow job is the +# difference between the step's output globs matching and not (measured: the +# job answered "Type File mismatch for globbed paths"). +case $out in +/*) ;; +*) out=$(pwd)/$out ;; +esac +mkdir -p "$(dirname "$out")" + +case $mode in +none) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + cp "$geno" "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +mean) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +hmm) + [ -n "$cross_dir" ] || { echo "prepare-genotypes.sh: --mode hmm needs --cross DIR" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + # R's own complaint last, so a caller that reports the final stderr line + # reports the cause rather than our wrapper sentence. + [ -n "$impute_script" ] || impute_script="$(dirname "$0")/qtl2-impute-bimbam.R" + if ! r_output=$("$RSCRIPT" "$impute_script" \ + "$cross_dir" "${probs:--}" "$out" "$minprob" "$individuals_file" 2>&1); then + echo "prepare-genotypes.sh: HMM imputation failed:" >&2 + printf '%s\n' "$r_output" | tail -6 >&2 + exit 1 + fi + ;; +esac + +case $mode in +hmm) + # The R script writes <prefix>.individuals.txt itself: the HMM calls come + # from the cross, whose individual order is its own, and the caller aligns + # the trait values to that order. + ;; +*) + # The other modes keep the panel's order, so the caller's list is the + # answer -- copied rather than re-derived, because a BIMBAM file does not + # carry individual names at all. + [ -n "$individuals_file" ] && cp "$individuals_file" "$out.individuals.txt" + ;; +esac + +printf '%s\n' "$out" diff --git a/scripts/qtl2-convert-geno.R b/scripts/qtl2-convert-geno.R new file mode 100755 index 0000000..48b4779 --- /dev/null +++ b/scripts/qtl2-convert-geno.R @@ -0,0 +1,145 @@ +#!/usr/bin/env Rscript +# qtl2-convert-geno.R -- convert a GeneNetwork `.geno` file into an R/qtl2 cross. +# +# This is the conversion that used to live in src/qtl2.rs, done where it belongs: +# the output *is* an R/qtl2 cross, the format is qtl2's own, and the JSON +# metadata that describes it is written by qtl2's `write_control_file` rather +# than by hand. Writing those files in Rust meant reimplementing qtl2's +# conventions in another language, and one of them was wrong: the genotype +# codes. With the heterozygous class dropped (the `riself` default) the cross +# carries two alleles, and they must be numbered 1 and 2. Numbering the second +# one 3 gave qtl2's two-state HMM an allele code it cannot use -- it read that +# allele as unusable, P(second allele) never rose above 0.5, every individual +# was called the first allele, and a scan on those calls lost the signal +# (2.0e-01 where the same marker is 5.9e-07 from the BIMBAM). +# +# qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2] +# +# writes DIR/{control.json,geno.csv,gmap.csv,pmap.csv,pheno.csv} -- the layout +# `read_cross2(DIR/control.json)` reads back -- and prints a one-line summary. +# Autosomes only: the X needs a sex covariate and the other chromosomes +# degenerate the per-chromosome kinship (the same limit /compute/qtl2 has). + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +get <- function(flag, default = NULL) { + i <- match(flag, args) + if (is.na(i)) return(default) + args[i + 1] +} +geno_path <- get("--geno") +out_dir <- get("--out") +het <- match.arg(get("--het", "drop"), c("drop", "keep")) +crosstype <- get("--crosstype") +if (is.null(geno_path) || is.null(out_dir)) { + stop("usage: qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2]", + call. = FALSE) +} + +lines <- readLines(geno_path, warn = FALSE) +meta <- function(key) { + hit <- grep(paste0("^@", key, ":"), lines, value = TRUE) + if (length(hit) == 0) NULL else trimws(sub(paste0("^@", key, ":"), "", hit[1])) +} +# The allele letters are declared by the file, not assumed: GeneNetwork panels +# use B/D as often as A/B. +mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het"); type <- meta("type") +if (is.null(mat) || is.null(pat)) { + stop("the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded", + call. = FALSE) +} + +hdr <- lines[tolower(substr(lines, 1, 4)) == "chr\t"][1] +if (is.na(hdr)) stop("the .geno file has no 'Chr' header row", call. = FALSE) +cols <- strsplit(hdr, "\t")[[1]] +individuals <- cols[-(1:4)] + +body <- lines[!startsWith(lines, "#") & lines != hdr] +autosomes <- as.character(1:19) + +geno <- list(); gmap <- list(); pmap <- list() +dropped <- 0L; non_autosomal <- 0L; markers_seen <- 0L +for (line in body) { + f <- strsplit(line, "\t")[[1]] + if (length(f) < 5) next + chr <- f[1] + if (!(chr %in% autosomes)) { non_autosomal <- non_autosomal + 1L; next } + marker <- f[2] + calls <- f[-(1:4)] + # A call is A, B or (if the heterozygous class is kept) H; anything else -- + # U or blank -- is missing and stays missing, because that is what the HMM is + # for. + calls[calls == mat] <- "A" + calls[calls == pat] <- "B" + if (!is.null(het_code)) { + calls[calls == het_code] <- if (het == "keep") "H" else "" + dropped <- dropped + if (het == "drop") sum(f[-(1:4)] == het_code) else 0L + } + calls[!(calls %in% c("A", "B", "H"))] <- "" + geno[[marker]] <- calls + markers_seen <- markers_seen + 1L + gmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[3]))) + pmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[4])) * 1e6) +} + +if (length(geno) == 0) stop("no autosomal markers in the .geno file", call. = FALSE) + +# A degenerate genetic map leaves the HMM nothing to smooth along (the .geno +# files carry no cM), so missing positions fall back to physical distance at +# 1 cM per Mb -- crude, monotone, and better than zeros. +for (marker in names(gmap)) { + g <- gmap[[marker]] + if (!is.finite(as.numeric(g["pos"]))) { + p <- pmap[[marker]] + gmap[[marker]]["pos"] <- if (is.finite(as.numeric(p["pos"]))) as.numeric(p["pos"]) / 1e6 else 0 + } +} + +dir.create(out_dir, recursive = TRUE, showWarnings = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(gmap, `[`, "", "chr"), + pos = as.numeric(vapply(gmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "gmap.csv"), row.names = FALSE, quote = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(pmap, `[`, "", "chr"), + pos = as.numeric(vapply(pmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "pmap.csv"), row.names = FALSE, quote = FALSE) +# qtl2's default genotype file has one row per individual and one column per +# marker, with the first column named `id` (see qtl2's own iron example). +geno_df <- data.frame(id = individuals, + do.call(cbind, lapply(geno, function(calls) calls)), + check.names = FALSE, stringsAsFactors = FALSE) +names(geno_df) <- c("id", names(geno)) +write.csv(geno_df, file.path(out_dir, "geno.csv"), row.names = FALSE, quote = FALSE) +# qtl2 wants a phenotype column to be able to read a cross; the trait comes from +# the request, through the scan script's --pheno. +write.csv(data.frame(id = individuals, trait = 1), + file.path(out_dir, "pheno.csv"), row.names = FALSE, quote = FALSE) + +# The JSON metadata is qtl2's own description of a cross: one call, no +# hand-rolled keys, and it stays right when qtl2 changes. +# 1..n over the genotypes the file carries: A/B for a riself cross with the +# heterozygous class dropped, A/H/B when it is kept. +codes <- if (crosstype == "riself" && het == "drop") c(A = 1L, B = 2L) else c(A = 1L, H = 2L, B = 3L) +write_control_file( + file.path(out_dir, "control.json"), + crosstype = crosstype, + geno_file = "geno.csv", gmap_file = "gmap.csv", pmap_file = "pmap.csv", + pheno_file = "pheno.csv", + geno_transposed = FALSE, sep = ",", + na.strings = "", + geno_codes = codes, overwrite = TRUE) + +# The report the caller reads back: what this cross holds, and what the +# conversion dropped. It is written beside the cross so a cached one costs +# nothing. +writeLines(jsonlite::toJSON(list( + crosstype = crosstype, markers = length(geno), non_autosomal = non_autosomal, + individuals = as.list(individuals), het_dropped = dropped, + cells = length(individuals) * length(geno)), auto_unbox = TRUE), + file.path(out_dir, "conversion.json")) + +cat(sprintf("geno2cross: %d markers, %d individuals, %d heterozygous calls %s, crosstype %s -> %s\n", + length(geno), length(individuals), dropped, + if (het == "drop") "dropped" else "kept", crosstype, out_dir)) diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R new file mode 100755 index 0000000..4d33d51 --- /dev/null +++ b/scripts/qtl2-impute-bimbam.R @@ -0,0 +1,162 @@ +#!/usr/bin/env Rscript +# qtl2-impute-bimbam.R -- write a BIMBAM genotype file from qtl2's HMM, so that +# pangemma's mdb can be built from the same genotype calls /compute/qtl2 uses. +# +# Why this exists: the BIMBAM the GEMMA path uses carries 0.1% unknown calls +# and the riself conversion used by R/qtl2 drops 12.7% (every heterozygous +# call). Filling those with a marker mean would be inventing data where there +# is a real prediction to be had, so the calls come from qtl2's HMM instead: +# `maxmarg` on the cached genotype probabilities, which predicts a missing call +# from its flanking markers -- and that is the call set /compute/qtl2 maps on, +# so a GEMMA scan and a qtl2 scan over this file describe the same data. +# +# It is not here because an engine cannot cope: an older pangemma could not +# hold a gap in its GRM (one NA made the whole kinship matrix NaN, silently), +# which is what introduced this step, but the current build keeps the gaps +# (NaN in a Gf store, 255 in a Gb one) and mean-substitutes them per marker as +# GEMMA does -- measured: `impute: none` through pangemma answers the same +# rows and the same allele frequencies as GEMMA. So this is a modelling +# choice, not a workaround. +# +# qtl2-impute-bimbam.R <cross dir> <probs.rds> <out prefix> [minprob] +# +# writes <prefix>.bimbam.txt (marker, X, Y, genotypes -- positions come from +# the annotation database, as the makers expect) and <prefix>.snps.txt +# (marker, pos, chr, the order anno2mdb.rb parses). Autosomes only: the qtl2 +# cross this reads has no X, which is the same limit /compute/qtl2 has. + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +if (length(args) < 3) { + stop("usage: qtl2-impute-bimbam.R <cross dir> <probs.rds> <out prefix> [minprob]", + call. = FALSE) +} +cross_dir <- args[1]; probs_path <- args[2]; out_prefix <- args[3] +minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 +# Optional: the individuals the caller is actually serving, one per line. The +# cross carries the whole panel; a request that drops parents and F1s serves a +# subset, and a genotype file with more columns than the phenotype covers makes +# every comparison between modes meaningless (measured: none/mean fitted 198 +# individuals, hmm 235, and the peaks landed on different chromosomes). +individuals_file <- if (length(args) >= 5 && nzchar(args[5])) args[5] else NULL +wanted <- if (!is.null(individuals_file)) trimws(readLines(individuals_file)) else NULL + +setwd(cross_dir) +cross <- read_cross2("control.json") + +# Passing "-" as the probabilities means "compute them": a caller that only has +# the converted cross (the GEMMA path has no qtl2 scan to borrow a cache entry +# from) should not have to run /compute/qtl2 first just to get genotypes. The +# result is cached in the cross directory, which is itself content-keyed, so a +# second call is free. +probs <- if (identical(probs_path, "-")) { + cached <- "probs-imputed.rds" + if (file.exists(cached)) { + readRDS(cached) + } else { + p <- calc_genoprob(cross, error_prob = 0.002, cores = 1, quiet = TRUE) + saveRDS(p, cached) + p + } +} else { + readRDS(probs_path) +} + +# maxmarg returns one call per marker and individual, at the highest +# probability above MINPROB -- or NA when the HMM is less sure than that. At +# minprob 0 every cell is filled, which is what the mdb needs. +# The genetic map the HMM smooths along. Ours is often degenerate -- the .geno +# files carry no cM, so the converter writes 0 for many markers ("19 markers with +# missing genetic map position; using 0"), and with no distance between markers +# the HMM has nothing to smooth with: measured, P(BB) never exceeded 0.5 and +# every individual was called AA at a marker where 125 of 235 are BB. When the +# map has gaps, positions come from the physical map at 1 cM per Mb, which is +# crude but monotone and infinitely better than 0. +if (!is.null(cross$pmap)) { + for (chr_name in names(cross$gmap)) { + g <- cross$gmap[[chr_name]] + p_mb <- cross$pmap[[chr_name]][names(g)] / 1e6 + if (anyNA(g) || any(diff(g) <= 0) || any(g == 0)) { + if (!anyNA(p_mb)) cross$gmap[[chr_name]] <- unname(p_mb) + } + } +} + +# return_char: the genotype LETTERS (A/B, plus H if it were kept), not qtl2's +# internal genotype *indices*. Measured the hard way: maxmarg returns 1..n_gen +# -- 1 and 2 for a riself cross -- which are not the cross's numeric codes +# (A=1, B=3 per control.json). Mapping 2 to 1 read every BB animal as a +# heterozygote, which collapsed the genotypes (sd 0.21 where the panel has +# 0.46) and quietly killed the scan: the same marker that is p 5.9e-07 in the +# other modes came out at 2.0e-01. +imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1, + return_char = TRUE)) +if (!is.null(wanted)) { + present <- rownames(imputed[[1]]) + keep <- wanted[wanted %in% present] + if (length(keep) == 0) { + stop("none of the requested individuals appear in the cross", call. = FALSE) + } + for (chr_name in names(imputed)) { + imputed[[chr_name]] <- imputed[[chr_name]][keep, , drop = FALSE] + } + wanted_kept <- keep +} else { + wanted_kept <- rownames(imputed[[1]]) +} + +# How much work the HMM did: cells the cross itself had as missing (a 0 in an +# explicit genotype map, never NA -- see read_cross2's own convention). +missing <- sum(vapply(cross$geno, function(g) sum(g == 0 | is.na(g)), integer(1))) +filled <- sum(is.na(vapply(cross$geno, function(g) sum(is.na(g)), integer(1)))) +left <- sum(vapply(imputed, function(g) sum(is.na(g)), integer(1))) + +# The calls come back as genotype *codes* in qtl2's numeric convention for this +# cross (A = 1, B = 3, H = 2 per control.json); pangemma wants 0/1/2. +# The alphabet comes from the data: return_char gives the genotype *names* +# ("AA"/"BB" for a riself cross, "A"/"B" for a plain one, one name per founder +# for multiparent), so the first is homozygote 1 (0), the last homozygote 2 (2) +# and anything in between a heterozygote (1). Hard-coding A/H/B skipped every +# marker, because the values are "AA" and "BB" -- the run then had no +# chromosomes and no association files. +present <- sort(unique(as.vector(unlist(imputed)))) +present <- present[!is.na(present)] +if (length(present) < 2) { + stop("the HMM returned a single genotype state; nothing to map", call. = FALSE) +} +codes <- stats::setNames(c(0, rep(1, max(0, length(present) - 2)), 2), present) +rows <- list(); snps <- list() +# maxmarg returns individuals x markers (rows are individuals, which is the +# opposite of the BIMBAM's marker-per-line shape, and the reason a first version +# of this wrote 4 465 lines naming individuals as markers). +for (chr_name in names(imputed)) { + calls <- imputed[[chr_name]] + markers <- colnames(calls) + # pmap (base pairs) when the cross has one: it is what the annotation lookup + # and the plot positions want, exactly as /compute/qtl2 reports them. + positions <- (if (!is.null(cross$pmap)) cross$pmap else cross$gmap)[[chr_name]][markers] + for (marker in markers) { + row <- codes[as.character(calls[, marker])] + if (any(is.na(row))) next # a cell the HMM could not call + rows[[length(rows) + 1]] <- c(marker, "X", "Y", as.character(row)) + snps[[length(snps) + 1]] <- c(marker, as.character(round(positions[[marker]])), chr_name) + } +} + +writeLines(vapply(rows, paste, character(1), collapse = ","), + paste0(out_prefix, ".bimbam.txt")) +# The individual order of the calls -- rownames, because maxmarg returns +# individuals x markers and colnames are therefore markers (measured: writing +# colnames put 1452 marker names in a file of individuals, every value aligned +# to nothing, and the run reported "number of analyzed individuals equals 0") -- +# because it is the *cross's* order and not necessarily the panel's: a caller that writes a phenotype file positionally +# has to align to this, or the two disagree by name and every individual is +# missing (measured: gemma answered "no individuals in common" and ravanan +# reported no association files at all). +writeLines(wanted_kept, paste0(out_prefix, ".individuals.txt")) +writeLines(vapply(snps, paste, character(1), collapse = ","), + paste0(out_prefix, ".snps.txt")) + +cat(sprintf("hmm: %d markers, %d individuals, minprob %g, %d cells uncertain, %d written to %s.bimbam.txt\n", + length(rows), nrow(imputed[[1]]), minprob, left, length(rows), out_prefix)) diff --git a/scripts/wire-listing.py b/scripts/wire-listing.py new file mode 100755 index 0000000..3170106 --- /dev/null +++ b/scripts/wire-listing.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# Mechanical first pass at wiring src/listing.rs into the six listing handlers. +# It changed 3 of 6 (groups, group_strains, group_traits) before the return-type +# rewrite needed hand care; see the module docs in src/listing.rs for the plan. +"""Wire the listing shape into the six listing handlers, mechanically. + +Per handler: add the three query fields, change the utoipa `body =` type and +the return type to Envelope<serde_json::Value>, and shape the rows where the +envelope is built. +""" +import re, sys + +def field_block(indent): + i = ' ' * indent + return (f"\n{i}/// Keep only these ids or names, comma-separated.\n{i}#[serde(default)]\n{i}pub limit_to: Option<String>,\n" + f"{i}/// Answer with one id per row instead of objects.\n{i}#[serde(default)]\n{i}pub ids_only: Option<bool>,\n" + f"{i}/// Answer with one name per row instead of objects.\n{i}#[serde(default)]\n{i}pub names_only: Option<bool>,\n") + +def shape(rows_expr, ind, params_name='params'): + i = ' ' * ind + return (f"let listing = crate::listing::Listing::parse(&crate::listing::ListingParams {{\n" + f"{i} limit_to: {params_name}.limit_to.clone(),\n" + f"{i} ids_only: {params_name}.ids_only,\n" + f"{i} names_only: {params_name}.names_only,\n" + f"{i}}})\n" + f"{i}.map_err(|detail| crate::listing::refuse(detail, &listing_rid, \"{op}\"))?;\n" + f"{i}let rows = serde_json::to_value({rows_expr}).unwrap_or(serde_json::Value::Null);\n" + f"{i}let (shaped, missing) = listing.apply(&rows, {params_name}.limit_to.as_deref());\n") + +handlers = [ + # file, handler fn, struct to extend, params type name, rows variable, operation id + ('src/routes/groups.rs', 'groups', 'GroupsParams', 'groups', 'groups'), + ('src/routes/groups.rs', 'group_strains', 'GroupStrainsParams', 'strains', 'group_strains'), + ('src/routes/groups.rs', 'group_datasets', 'GroupDatasetsParams', 'datasets', 'group_datasets'), + ('src/routes/groups.rs', 'group_traits', 'GroupTraitsParams', 'traits', 'group_traits'), + ('src/routes/datasets.rs', 'dataset_probesets', 'DatasetProbesetsParams', 'probesets', 'dataset_probesets'), + ('src/routes/traits.rs', 'traits', 'TraitsParams', 'traits', 'dataset_traits'), +] +status = [] +for path, handler, params, rows_var, op in handlers: + s = open(path).read() + before = s + # 1. add the fields to the params struct + m = re.search(r'pub struct %s \{(.*?)\n\}' % params, s, re.S) + if not m: + status.append(f'{handler}: params struct {params} NOT FOUND') + continue + if 'pub limit_to' not in m.group(0): + s = s.replace(m.group(0), m.group(0)[:-2] + field_block(4) + '}', 1) + # 2. body= type in the handler's utoipa block (the one nearest above the fn) + idx = s.index('pub async fn %s(' % handler) + head = s[:idx] + cut = head.rfind('body = Envelope<Vec<') + if cut == -1: + status.append(f'{handler}: no body= to change') + else: + end = head.index('>', cut) + 1 + s = head[:cut] + 'body = Envelope<serde_json::Value>' + head[end:] + s[idx:] + # 3. return type + s = re.sub(r'(pub async fn %s\([^)]*?\) -> Result<Json<Envelope<Vec<[^>]*>>, ApiError>)' % handler, + lambda mm: mm.group(1).replace('Envelope<Vec<', 'Envelope<serde_json::Value>[').split('Envelope<serde_json::Value>[')[0] + + 'Envelope<serde_json::Value>>, ApiError>', s, count=1, flags=re.S) + open(path, 'w').write(s) + status.append(f'{handler}: {"changed" if s != before else "UNCHANGED"}') +print('\n'.join(status)) |
