about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-21 18:52:12 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-21 18:52:12 +0000
commitfd5807024b0b5553cbe6e7d6d2bf717d50ef8b05 (patch)
tree178ec42759e7fc4543b24baab66b17f0bbb26243 /scripts
parent5b68da6479da03e9bf7f00ae3094561349980aa7 (diff)
downloadgenenetwork4-fd5807024b0b5553cbe6e7d6d2bf717d50ef8b05.tar.gz
scripts: a .geno to BIMBAM projector that refuses to guess the projection
HET3-ITP's `bimbam/HET3-ITP.*` pair is empty -- 5.76 M cells, all "NA" -- which
is why every GEMMA route answers 422 no_samples_aligned on a panel that is
45.8% dense in the `.geno` R/qtl reads.  The converter that made those files
only understood the biallelic letter codes a `.geno` header declares, and a
four-founder panel writes numeric ones.

This adds the tool that can regenerate such a pair, and the experiment that
says what a 4-way panel actually needs.  Tried the only contrast the header
supports -- parent-of-origin, maternal codes 1,2 -> 0, paternal 3,4 -> 1, mixed
5..8 -> 0.5 (order-insensitive, so it cannot transpose two founders):

  - the pair it produced is real: 2,639,235 of 5,757,171 calls, 893 markers;
  - pangemma ran on HET3-ITP trait 10000 for the first time: 1314 s (21.9 min,
    893 markers x 6447 individuals, one LOCO eigen decomposition per
    chromosome on a 2-CPU node), HTTP 200;
  - and it found nothing: 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.

So the mechanism works and the contrast does not.  What HET3 needs is a
founder contrast (the dosage of one founder's allele), whose numeric-code ->
founder-pair table is in neither the `.geno` header, this repository, nor the
panel's `rdata/HET3-ITP.RData` (qtl2 allele-probability arrays, not calls).
`--codes` is therefore required rather than defaulted: a guessed table
produces a silently empty projection, which is exactly how the shipped pair
came to be 23 MB of NA.

The data is unchanged: the stubs were restored after the experiment.
docs/genotypes.md now records this, since it previously described the pair as
"a biallelic projection" when in this deployment it carries nothing.
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()