about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-16 20:00:23 +0000
committerPjotr <wrk@bosa.lan>2026-11-16 20:00:23 +0000
commit94d08ecb58619ae60f048059f24536cac1f1e6e0 (patch)
treefdded1c8c0e6ab661c4c4be638bfc68f0515d943 /scripts
parentc9777828482d03affc912688bed316f1a16c5640 (diff)
downloadgenenetwork4-94d08ecb58619ae60f048059f24536cac1f1e6e0.tar.gz
make-mdb.sh: HMM genotypes from qtl2, for the pangemma path
The pangemma endpoint is to agree with R/qtl2, not with GEMMA, so the store's
genotypes now come from qtl2's HMM rather than from a marker mean: maxmarg on
the genotype probabilities /compute/qtl2 already computes and caches, at
minprob 0 so every cell is called.  GEMMA's own endpoints are untouched.

  scripts/make-mdb.sh --impute qtl2 --cross <qtl2 cross dir> --probs <probs.rds>

writes a BIMBAM from the HMM's calls (marker, X, Y, genotypes -- the annotation
mdb carries the positions, as the makers expect), the snps file from the cross's
physical map, and then the store as before: lock file deleted, .mdb made
read-only, renamed into place.  Measured on BXD.8: 7 s for the HMM over 20 453
markers x 235 individuals, 4.7 s for geno2mdb, 28.9 MB as Gf, no gaps left.

Three things found while wiring it, each now handled:

* maxmarg returns individuals x markers -- the transpose of a BIMBAM -- and a
  first version wrote 4 465 lines with individuals where markers belong;
* both makers name their output after their argument and write it in the
  current directory, so they now run inside the work directory with bare names.
  A hand run with absolute paths had put a 2 MB .mdb inside gn4-data;
* pangemma's startup smoke test wants the working directory to be its own
  source root.  Run from anywhere else it exits in 0.03 s having done nothing,
  which looks like a very fast scan rather than a failure.

Comparison, three BXD traits, 20 451 markers, each engine with its own kinship
matrix, positional phenotype in the cross's individual order:

  trait   same top marker   Spearman rho   top-50 overlap   median |d(-log10 p)|
  10001   yes (rs27829136)      0.99732         48/50              0.008
  16627   yes (rs29388476)      0.98415         43/50              0.029
  16769   yes (rs29388476)      0.98339         32/50              0.029

K 0.13 s against gemma's 0.84 s; the LMM scan 2.5 s against 3.0 s.
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/make-mdb.sh73
-rwxr-xr-xscripts/qtl2-impute-bimbam.R72
2 files changed, 125 insertions, 20 deletions
diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh
index b5fd3df..e5b753e 100755
--- a/scripts/make-mdb.sh
+++ b/scripts/make-mdb.sh
@@ -33,23 +33,29 @@
 # 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
+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
-[ -n "$geno" ] && [ -n "$snps" ] || { echo "make-mdb.sh: --geno and --snps are required" >&2; exit 2; }
-for f in "$geno" "$snps"; do
-	[ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; }
-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
@@ -66,25 +72,51 @@ mkdir -p "$out"
 work=$(mktemp -d "$out/.$name.XXXXXX")
 trap 'rm -rf "$work"' EXIT
 
-# 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"
+# 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
 
-# 1. the annotation half.  It is an intermediate: pangemma is given the snps
+# 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.
-"$ANNO" "$work/snps.txt" >/dev/null 2>&1 ||
+# 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.  pangemma's mdb path has NO missing-data handling
+# 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 ]; then
+if [ "$keep_missing" = no ] && [ "$impute" != qtl2 ]; then
 	awk -F, 'BEGIN { OFS = "," }
 	         {
 	           sum = 0; n = 0
@@ -92,13 +124,14 @@ if [ "$keep_missing" = no ]; then
 	           mean = (n ? sum / n : 0)
 	           for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean)
 	           print
-	         }' "$work/geno.txt" > "$work/geno-imputed.txt"
-	mv "$work/geno-imputed.txt" "$work/geno.txt"
+	         }' "$geno" > "$work/geno-imputed.txt"
+	mv "$work/geno-imputed.txt" "$geno"
 fi
 
 # 3. the genotypes, translated the way pangemma expects
-"$GENO" --eval "$eval_" --anno "$work/snps.txt.mdb" "$work/geno.txt" >/dev/null 2>&1 ||
+( 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
@@ -106,11 +139,11 @@ fi
 #    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 "$work/geno.txt.mdb-lock" "$work/snps.txt.mdb-lock"
-chmod a-w "$work/geno.txt.mdb"
+rm -f "$store-lock" "$anno_db-lock"
+chmod a-w "$store"
 
 rm -f "$out/$name.geno.mdb" "$out/$name.geno.mdb-lock"
-mv "$work/geno.txt.mdb" "$out/$name.geno.mdb"
+mv "$store" "$out/$name.geno.mdb"
 trap 'rm -rf "$work"' EXIT
 rm -rf "$work"
 trap - EXIT
diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R
new file mode 100755
index 0000000..1a9cd1b
--- /dev/null
+++ b/scripts/qtl2-impute-bimbam.R
@@ -0,0 +1,72 @@
+#!/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: pangemma's LMDB path cannot represent a missing genotype
+# (one NA makes the whole kinship matrix NaN, silently), while 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.
+#
+#   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
+
+setwd(cross_dir)
+cross <- read_cross2("control.json")
+probs <- 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.
+imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 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.
+codes <- c(`1` = 0, `2` = 1, `3` = 2)
+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"))
+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))