about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/geno-to-bimbam.py140
1 files changed, 140 insertions, 0 deletions
diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py
new file mode 100755
index 0000000..089da45
--- /dev/null
+++ b/scripts/geno-to-bimbam.py
@@ -0,0 +1,140 @@
+#!/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
+writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt.
+"""
+
+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(
+        "--codes",
+        required=True,
+        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()
+
+    table = {}
+    for part in args.codes.split(";"):
+        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 = {}
+    with open(geno_out, "w") as geno, open(snps_out, "w") as snps:
+        for chrom, locus, _cm, mb, calls in read_geno(args.geno):
+            projected = []
+            for call in calls:
+                call = call.strip()
+                dosage = 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()))}"
+    )
+    print(f"{snps_out}")
+
+
+if __name__ == "__main__":
+    main()