Debian Codegraph @

Tests/TEST_PHASED_VCF/glm_compare.py

raw
1 #!/usr/bin/env python3
2 """
3 This compares a plink 1.x .assoc.linear or .assoc.logistic file with a plink
4 2.0 .glm.linear or .glm.logistic file, verifying that CHR/CHROM, BP/POS,
5 SNP/ID, A1, TEST, NMISS/OBS_CT, BETA or OR, STAT, and P columns match (or have
6 min(symmetric absolute percentage error, absolute error) within a given
7 tolerance) when both results aren't NA.
8
9 todo:
10 verify plink2 NA frequency isn't too high
11 """
12
13 import argparse
14 import csv
15 import math
16 import sys
17
18 def parse_commandline_args():
19 """
20 Standard command-line parser.
21 """
22 parser = argparse.ArgumentParser(description=__doc__)
23 requiredarg = parser.add_argument_group('Required Arguments')
24 requiredarg.add_argument('-1', '--plink1', type=str, required=True,
25 help="Full plink1 .assoc.linear or .assoc.logistic filename.")
26 requiredarg.add_argument('-2', '--plink2', type=str, required=True,
27 help="Full plink2 .glm.linear or .glm.logistic filename.")
28 requiredarg.add_argument('-t', '--tolerance', type=float, required=True,
29 help="Maximum allowed min(SMAE, absolute error).")
30 cmd_args = parser.parse_args()
31 return cmd_args
32
33
34 # See https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python .
35 def eprint(*args):
36 print(*args, file=sys.stderr)
37
38
39 def float_compare_ok(val1, val2, tol):
40 delta = abs(val1 - val2)
41 if delta < tol:
42 return True
43 # SMAE = (2 * delta) / (abs(val1) + abs(val2))
44 return (2 * delta) < (abs(val1) + abs(val2)) * tol
45
46
47 def main():
48 cmd_args = parse_commandline_args()
49 pc_ct = 0
50 line_num = 0
51 tol = cmd_args.tolerance
52 with open(cmd_args.plink1, 'r') as plink1_file, open(cmd_args.plink2, 'r') as plink2_file:
53 reader1 = csv.reader(plink1_file, delimiter=' ', skipinitialspace=True)
54 reader2 = csv.reader(plink2_file, delimiter='\t')
55 first_line1 = next(reader1)
56 first_line2 = next(reader2)
57 line_num += 1
58 if first_line2.index('#CHROM') != 0:
59 eprint('Unsupported plink2 association file format (this script requires #CHROM in front, even though plink2 can omit it).')
60 sys.exit(1)
61 pos_col2 = first_line2.index('POS')
62 id_col2 = first_line2.index('ID')
63 a1_col2 = first_line2.index('A1')
64 test_col2 = first_line2.index('TEST')
65 obsct_col2 = first_line2.index('OBS_CT')
66 errcode_col2 = first_line2.index('ERRCODE')
67 betaor_col2 = -1
68 stat_col2 = -1
69 is_odds_ratio = False
70 try:
71 betaor_col2 = first_line2.index('BETA')
72 except ValueError:
73 betaor_col2 = first_line2.index('OR')
74 is_odds_ratio = True
75 if not is_odds_ratio:
76 try:
77 stat_col2 = first_line2.index('T_STAT')
78 except ValueError:
79 stat_col2 = first_line2.index('T_OR_F_STAT')
80 else:
81 try:
82 stat_col2 = first_line2.index('Z_STAT')
83 except ValueError:
84 stat_col2 = first_line2.index('Z_OR_F_STAT')
85 p_col2 = first_line2.index('P')
86
87 if (first_line1.index('CHR') != 0) or \
88 (first_line1.index('BP') != 2) or \
89 (first_line1.index('SNP') != 1) or \
90 (first_line1.index('A1') != 3) or \
91 (first_line1.index('TEST') != 4) or \
92 (first_line1.index('NMISS') != 5) or \
93 (first_line1.index('STAT') != 7) or \
94 (first_line1.index('P') != 8):
95 eprint('Unexpected plink1 association file format.')
96 sys.exit(1)
97
98 for row1 in reader1:
99 row2 = next(reader2)
100 line_num += 1
101 if row1[0] != row2[0] or \
102 row1[2] != row2[pos_col2] or \
103 row1[1] != row2[id_col2] or \
104 row1[3] != row2[a1_col2] or \
105 row1[4] != row2[test_col2] or \
106 row1[5] != row2[obsct_col2]:
107 eprint('Header column mismatch between association files.')
108 sys.exit(1)
109 if row1[6] != 'NA':
110 # Apple clang 15.0.0 apparent-miscompilation issue is likely to
111 # manifest as an inappropriate ERRCODE=INVALID_RESULT. This is
112 # very unlikely to happen on random data, so error out and then
113 # manually pass if necessary.
114 if row2[errcode_col2] == 'INVALID_RESULT':
115 eprint('Unexpected INVALID_RESULT, line', line_num)
116 sys.exit(1)
117 if row2[betaor_col2] != 'NA':
118 val1 = float(row1[6])
119 val2 = float(row2[betaor_col2])
120 if is_odds_ratio:
121 # this is a more appropriate scale
122 val1 = math.log(val1)
123 val2 = math.log(val2)
124 if not float_compare_ok(val1, val2, tol):
125 eprint('BETA/OR mismatch, line', line_num)
126 sys.exit(1)
127 if row1[7] != 'NA' and row1[7] != 'inf' and row2[stat_col2] != 'NA':
128 val1 = float(row1[7])
129 val2 = float(row2[stat_col2])
130 if row1[4][-2:] != 'DF':
131 # skip GENO_2DF, USER_xDF due to transition to F-statistics
132 if not float_compare_ok(val1, val2, tol):
133 eprint('STAT mismatch, line', line_num)
134 sys.exit(1)
135 if row1[8] != 'NA' and row2[p_col2] != 'NA':
136 val1 = math.log(float(row1[8]))
137 val2 = math.log(float(row2[p_col2]))
138 if not float_compare_ok(val1, val2, tol):
139 eprint('P-value mismatch, line', line_num)
140 sys.exit(1)
141
142
143 if __name__ == '__main__':
144 main()