about summary refs log tree commit diff
path: root/scripts/make-mdb.sh
blob: e5b753e2b6f8b71bc6228aab8ed3be9409fe7ed0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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"