-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCLI_pannot_fct.py
236 lines (213 loc) · 9.22 KB
/
CLI_pannot_fct.py
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import gzip
import pandas as pd
import numpy as np
import time
import argparse
import ldspec
"""
Create proximity-based pannot annotations.
Basic functional proximity-based annotation:
--pgen_file
--dist_lb
--dist_ub
--out_path
--maf_ratio_thres
Stratifying by LD
--ld_file : LDSPEC-computed LD matrices
--snp_range_file : corresponding LDSEPC SNP-range file
--ld_lb
--ld_ub
Stratifying by MAF:
--maf_bin_file :
Example:
common 0.05 0.5
lf 0.005 0.05
"""
def main(args):
sys_start_time = time.time()
PGEN_FILE = args.pgen_file
ANNOT_FILE = args.annot_file
LD_FILE = args.ld_file
SNP_RANGE_FILE = args.snp_range_file
DIST_LB = int(args.dist_lb)
DIST_UB = int(args.dist_ub)
LD_LB = float(args.ld_lb)
LD_UB = float(args.ld_ub)
MAF_BIN_FILE = args.maf_bin_file
MAF_RATIO_THRES = int(args.maf_ratio_thres)
FLAG_MAF_BLOCK = args.flag_maf_block
OUT_PATH = args.out_path
print("--pgen_file %s" % PGEN_FILE)
print("--annot_file %s" % ANNOT_FILE)
print("--ld_file %s" % LD_FILE)
print("--snp_range_file %s" % SNP_RANGE_FILE)
print("--dist_lb %s" % DIST_LB)
print("--dist_ub %s" % DIST_UB)
print("--ld_lb %s" % LD_LB)
print("--ld_ub %s" % LD_UB)
print("--maf_bin_file %s" % MAF_BIN_FILE)
print("--maf_ratio_thres %s" % MAF_RATIO_THRES)
print("--flag_maf_block %s" % FLAG_MAF_BLOCK)
print("--out_path %s" % OUT_PATH)
# Data loading
df_snp_chr = ldspec.util.read_pgen(PGEN_FILE)["pvar"]
df_snp_chr = df_snp_chr[["CHR", "SNP", "BP"]].copy()
CHR = df_snp_chr["CHR"][0]
df_snp_chr["AF"] = ldspec.util.read_pgen(PGEN_FILE)["afreq"]["MAF"].astype(
np.float32
)
df_snp_chr["MAF"] = [min(x, 1 - x) for x in df_snp_chr["AF"]]
dic_bp = {x: y for x, y in zip(df_snp_chr["SNP"], df_snp_chr["BP"])}
dic_maf = {x: y for x, y in zip(df_snp_chr["SNP"], df_snp_chr["MAF"])}
print("n_snp", df_snp_chr.shape[0])
# Data loading: stratifying by LD
if LD_FILE is not None:
snp_range_list = list(pd.read_csv(SNP_RANGE_FILE, header=None)[0])
snp_range_list_chr = [x for x in snp_range_list if x.startswith("c%d_" % CHR)]
# Data loading: stratifying by MAF
if MAF_BIN_FILE is not None:
df_mbin = pd.read_csv(MAF_BIN_FILE, delim_whitespace=True, header=None)
else:
df_mbin = pd.DataFrame(data={0: ["all"], 1: [0], 2: [1]})
if FLAG_MAF_BLOCK: # Disable MAF_RATIO_THRES
MAF_RATIO_THRES = 1e6
print(df_mbin)
# Data loading: annot_file
temp_df = ldspec.util.read_annot(ANNOT_FILE)
AN_list = []
for col in temp_df:
if col.startswith('AN:') is False:
continue
if 'flanking' in col:
continue
if 'mbin' in col:
continue
if 'all' in col:
continue
if set(temp_df[col]) != set([0,1]):
continue
if col.endswith('_common') is False:
continue
AN = col.replace('_common', '')
AN_list.append(AN)
temp_dic = {
x: y|z for x,y,z in zip(temp_df["SNP"], temp_df['%s_common' % AN], temp_df['%s_lf' % AN])
}
df_snp_chr[AN] = np.array(
[temp_dic[x] if x in temp_dic else 0 for x in df_snp_chr['SNP']],
dtype=bool,
)
# Computation for each AN in AN_list
snp_list = list(df_snp_chr["SNP"])
dic_snp_list1 = {x:[] for x in AN_list}
dic_snp_list2 = {x:[] for x in AN_list}
if LD_FILE is None:
for AN in AN_list:
temp_set = set(df_snp_chr["SNP"][df_snp_chr[AN]])
# No LD stratification
for i in range(len(snp_list)):
if snp_list[i] not in temp_set:
continue
for j in range(i + 1, len(snp_list)):
if snp_list[j] not in temp_set:
continue
dist = dic_bp[snp_list[j]] - dic_bp[snp_list[i]]
if dist > DIST_UB:
break
maf_ratio = dic_maf[snp_list[i]] / dic_maf[snp_list[j]]
maf_ratio = max(maf_ratio, 1 / maf_ratio)
if (dist >= DIST_LB) & (dist < DIST_UB) & (maf_ratio < MAF_RATIO_THRES):
dic_snp_list1[AN].append(snp_list[i])
dic_snp_list2[AN].append(snp_list[j])
else:
# LD stratification
for snp_range in snp_range_list_chr:
print(" snp_range=%s" % snp_range)
mat_ld, dic_range = ldspec.util.read_ld(LD_FILE.replace("@", snp_range))
for AN in AN_list:
temp_set = set(df_snp_chr["SNP"][df_snp_chr[AN]])
for i in range(dic_range["start"], dic_range["end"]):
if snp_list[i] not in temp_set:
continue
v_ld = mat_ld[:, i - dic_range["start"]].toarray().flatten()
for j in range(i + 1, len(snp_list)):
if snp_list[j] not in temp_set:
continue
dist = dic_bp[snp_list[j]] - dic_bp[snp_list[i]]
if dist > DIST_UB:
break
ld = v_ld[j]
maf_ratio = dic_maf[snp_list[i]] / dic_maf[snp_list[j]]
maf_ratio = max(maf_ratio, 1 / maf_ratio)
if (
(ld >= LD_LB)
& (ld <= LD_UB)
& (dist >= DIST_LB)
& (dist < DIST_UB)
& (maf_ratio < MAF_RATIO_THRES)
):
dic_snp_list1[AN].append(snp_list[i])
dic_snp_list2[AN].append(snp_list[j])
for AN in AN_list:
print("%s n_pair=%d" % (AN, len(dic_snp_list1[AN])))
# MAF-bin & write files
LD_LB = max(-1, LD_LB)
LD_UB = min(1, LD_UB)
for AN in AN_list:
for mbin, maf_lb, maf_ub in zip(df_mbin[0], df_mbin[1], df_mbin[2]):
temp_snp_list1 = []
temp_snp_list2 = []
if FLAG_MAF_BLOCK: # snps in the same MAF bin
for snp1, snp2 in zip(dic_snp_list1[AN], dic_snp_list2[AN]):
if (
(dic_maf[snp1] >= maf_lb)
& (dic_maf[snp1] < maf_ub)
& (dic_maf[snp2] >= maf_lb)
& (dic_maf[snp2] < maf_ub)
):
temp_snp_list1.append(snp1)
temp_snp_list2.append(snp2)
else: # snps with geometric mean in the MAF bin
for snp1, snp2 in zip(dic_snp_list1[AN], dic_snp_list2[AN]):
mean_maf = np.sqrt(dic_maf[snp1] * dic_maf[snp2])
if (mean_maf >= maf_lb) & (mean_maf < maf_ub):
temp_snp_list1.append(snp1)
temp_snp_list2.append(snp2)
snp_pair_list = [(x, y) for x, y in zip(temp_snp_list1, temp_snp_list2)]
if len(snp_pair_list) > 10:
str_prox = "proxy_%d_%d" % (DIST_LB, DIST_UB)
LDLB_str = (
"n%d" % (int(-LD_LB * 100)) if LD_LB < 0 else "p%d" % (int(LD_LB * 100))
)
LDUB_str = (
"n%d" % (int(-LD_UB * 100)) if LD_UB < 0 else "p%d" % (int(LD_UB * 100))
)
str_ld = (
"ld_full" if LD_FILE is None else "ld_%s_%s" % (LDLB_str, LDUB_str)
)
str_maf = (
"maf_%s_block" % mbin if FLAG_MAF_BLOCK else "maf_%s_geomean" % mbin
)
file_name = "%s.%s.%s.%s.c%d" % (AN.replace('AN:',''), str_prox, str_ld, str_maf, CHR)
print("%-50s" % file_name, "n_pair=%d" % len(snp_pair_list))
ldspec.util.write_pannot_mat(
snp_pair_list, list(df_snp_chr["SNP"]), OUT_PATH + "/" + file_name
)
print("# Finished, time=%0.1fs" % (time.time() - sys_start_time))
print("# All finished, time=%0.1fs" % (time.time() - sys_start_time))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="ldspec")
parser.add_argument("--pgen_file", type=str, default=None, required=True)
parser.add_argument("--annot_file", type=str, default=None, required=True)
parser.add_argument("--ld_file", type=str, default=None, required=False)
parser.add_argument("--snp_range_file", type=str, default=None, required=False)
parser.add_argument("--dist_lb", type=str, default="0", required=False)
parser.add_argument("--dist_ub", type=str, default="1000", required=False)
parser.add_argument("--ld_lb", type=str, default="-1", required=False)
parser.add_argument("--ld_ub", type=str, default="1", required=False)
parser.add_argument("--maf_bin_file", type=str, default=None, required=False)
parser.add_argument("--maf_ratio_thres", type=str, default="5", required=False)
parser.add_argument("--flag_maf_block", type=bool, default=True, required=False)
parser.add_argument("--out_path", type=str, default=None, required=False)
args = parser.parse_args()
main(args)