0
|
1 from __future__ import division
|
|
2 from collections import defaultdict
|
|
3 import re
|
|
4 import argparse
|
|
5
|
|
6 parser = argparse.ArgumentParser()
|
|
7 parser.add_argument("--input",
|
|
8 help="The '7_V-REGION-mutation-and-AA-change-table' and '10_V-REGION-mutation-hotspots' merged together, with an added 'best_match' annotation")
|
|
9 parser.add_argument("--genes", help="The genes available in the 'best_match' column")
|
1
|
10 parser.add_argument("--empty_region_filter", help="Where does the sequence start?", choices=['leader', 'FR1', 'CDR1', 'FR2'])
|
0
|
11 parser.add_argument("--output", help="Output file")
|
|
12
|
|
13 args = parser.parse_args()
|
|
14
|
|
15 infile = args.input
|
|
16 genes = str(args.genes).split(",")
|
1
|
17 empty_region_filter = args.empty_region_filter
|
0
|
18 outfile = args.output
|
|
19
|
|
20 genedic = dict()
|
|
21
|
|
22 mutationdic = dict()
|
|
23 mutationMatcher = re.compile("^(.)(\d+).(.),?(.)?(\d+)?.?(.)?(.?.?.?.?.?)?")
|
|
24 NAMatchResult = (None, None, None, None, None, None, '')
|
|
25 linecount = 0
|
|
26
|
|
27 IDIndex = 0
|
|
28 best_matchIndex = 0
|
|
29 fr1Index = 0
|
|
30 cdr1Index = 0
|
|
31 fr2Index = 0
|
|
32 cdr2Index = 0
|
|
33 fr3Index = 0
|
|
34 first = True
|
|
35 IDlist = []
|
|
36 mutationList = []
|
|
37 mutationListByID = {}
|
|
38 cdr1LengthDic = {}
|
|
39 cdr2LengthDic = {}
|
|
40
|
|
41 with open(infile, 'r') as i:
|
|
42 for line in i:
|
|
43 if first:
|
|
44 linesplt = line.split("\t")
|
|
45 IDIndex = linesplt.index("Sequence.ID")
|
|
46 best_matchIndex = linesplt.index("best_match")
|
|
47 fr1Index = linesplt.index("FR1.IMGT")
|
|
48 cdr1Index = linesplt.index("CDR1.IMGT")
|
|
49 fr2Index = linesplt.index("FR2.IMGT")
|
|
50 cdr2Index = linesplt.index("CDR2.IMGT")
|
|
51 fr3Index = linesplt.index("FR3.IMGT")
|
|
52 cdr1LengthIndex = linesplt.index("CDR1.IMGT.length")
|
|
53 cdr2LengthIndex = linesplt.index("CDR2.IMGT.length")
|
|
54 first = False
|
|
55 continue
|
|
56 linecount += 1
|
|
57 linesplt = line.split("\t")
|
|
58 ID = linesplt[IDIndex]
|
|
59 genedic[ID] = linesplt[best_matchIndex]
|
|
60 try:
|
1
|
61 mutationdic[ID + "_FR1"] = [mutationMatcher.match(x).groups() for x in linesplt[fr1Index].split("|") if x] if (linesplt[fr1Index] != "NA" and empty_region_filter == "leader") else []
|
|
62 mutationdic[ID + "_CDR1"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr1Index].split("|") if x] if (linesplt[cdr1Index] != "NA" and empty_region_filter in ["leader", "FR1"]) else []
|
|
63 mutationdic[ID + "_FR2"] = [mutationMatcher.match(x).groups() for x in linesplt[fr2Index].split("|") if x] if (linesplt[fr2Index] != "NA" and empty_region_filter in ["leader", "FR1", "CDR1"]) else []
|
|
64 mutationdic[ID + "_CDR2"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr2Index].split("|") if x] if (linesplt[cdr2Index] != "NA") else []
|
0
|
65 mutationdic[ID + "_FR2-CDR2"] = mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"]
|
|
66 mutationdic[ID + "_FR3"] = [mutationMatcher.match(x).groups() for x in linesplt[fr3Index].split("|") if x] if linesplt[fr3Index] != "NA" else []
|
1
|
67 except Exception as e:
|
|
68 print "Something went wrong while processing this line:"
|
0
|
69 print linesplt
|
|
70 print linecount
|
|
71 print e
|
|
72 mutationList += mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
|
73 mutationListByID[ID] = mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
|
74
|
|
75 cdr1Length = linesplt[cdr1LengthIndex]
|
|
76 cdr2Length = linesplt[cdr2LengthIndex]
|
|
77
|
|
78 cdr1LengthDic[ID] = int(cdr1Length) if cdr1Length != "X" else 0
|
|
79 cdr2LengthDic[ID] = int(cdr2Length) if cdr2Length != "X" else 0
|
|
80
|
|
81 IDlist += [ID]
|
|
82
|
|
83 AALength = (int(max(mutationList, key=lambda i: int(i[4]) if i[4] else 0)[4]) + 1) # [4] is the position of the AA mutation, None if silent
|
|
84 if AALength < 60:
|
|
85 AALength = 64
|
|
86
|
|
87 AA_mutation = [0] * AALength
|
|
88 AA_mutation_dic = {"IGA": AA_mutation[:], "IGG": AA_mutation[:], "IGM": AA_mutation[:], "unm": AA_mutation[:]}
|
|
89 AA_mutation_empty = AA_mutation[:]
|
|
90
|
|
91 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/aa_id_mutations.txt"
|
|
92 with open(aa_mutations_by_id_file, 'w') as o:
|
|
93 o.write("ID\tbest_match\t" + "\t".join([str(x) for x in range(1,AALength)]) + "\n")
|
|
94 for ID in mutationListByID.keys():
|
|
95 AA_mutation_for_ID = AA_mutation_empty[:]
|
|
96 for mutation in mutationListByID[ID]:
|
|
97 if mutation[4]:
|
|
98 AA_mutation_position = int(mutation[4])
|
|
99 AA_mutation[AA_mutation_position] += 1
|
|
100 AA_mutation_for_ID[AA_mutation_position] += 1
|
|
101 clss = genedic[ID][:3]
|
|
102 AA_mutation_dic[clss][AA_mutation_position] += 1
|
|
103 o.write(ID + "\t" + genedic[ID] + "\t" + "\t".join([str(x) for x in AA_mutation_for_ID[1:]]) + "\n")
|
|
104
|
|
105
|
|
106
|
|
107 #absent AA stuff
|
|
108 absentAACDR1Dic = defaultdict(list)
|
|
109 absentAACDR1Dic[5] = range(29,36)
|
|
110 absentAACDR1Dic[6] = range(29,35)
|
|
111 absentAACDR1Dic[7] = range(30,35)
|
|
112 absentAACDR1Dic[8] = range(30,34)
|
|
113 absentAACDR1Dic[9] = range(31,34)
|
|
114 absentAACDR1Dic[10] = range(31,33)
|
|
115 absentAACDR1Dic[11] = [32]
|
|
116
|
|
117 absentAACDR2Dic = defaultdict(list)
|
|
118 absentAACDR2Dic[0] = range(55,65)
|
|
119 absentAACDR2Dic[1] = range(56,65)
|
|
120 absentAACDR2Dic[2] = range(56,64)
|
|
121 absentAACDR2Dic[3] = range(57,64)
|
|
122 absentAACDR2Dic[4] = range(57,63)
|
|
123 absentAACDR2Dic[5] = range(58,63)
|
|
124 absentAACDR2Dic[6] = range(58,62)
|
|
125 absentAACDR2Dic[7] = range(59,62)
|
|
126 absentAACDR2Dic[8] = range(59,61)
|
|
127 absentAACDR2Dic[9] = [60]
|
|
128
|
|
129 absentAA = [len(IDlist)] * (AALength-1)
|
|
130 for k, cdr1Length in cdr1LengthDic.iteritems():
|
|
131 for c in absentAACDR1Dic[cdr1Length]:
|
|
132 absentAA[c] -= 1
|
|
133
|
|
134 for k, cdr2Length in cdr2LengthDic.iteritems():
|
|
135 for c in absentAACDR2Dic[cdr2Length]:
|
|
136 absentAA[c] -= 1
|
|
137
|
|
138
|
|
139 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/absent_aa_id.txt"
|
|
140 with open(aa_mutations_by_id_file, 'w') as o:
|
|
141 o.write("ID\tcdr1length\tcdr2length\tbest_match\t" + "\t".join([str(x) for x in range(1,AALength)]) + "\n")
|
|
142 for ID in IDlist:
|
|
143 absentAAbyID = [1] * (AALength-1)
|
|
144 cdr1Length = cdr1LengthDic[ID]
|
|
145 for c in absentAACDR1Dic[cdr1Length]:
|
|
146 absentAAbyID[c] -= 1
|
|
147
|
|
148 cdr2Length = cdr2LengthDic[ID]
|
|
149 for c in absentAACDR2Dic[cdr2Length]:
|
|
150 absentAAbyID[c] -= 1
|
|
151 o.write(ID + "\t" + str(cdr1Length) + "\t" + str(cdr2Length) + "\t" + genedic[ID] + "\t" + "\t".join([str(x) for x in absentAAbyID]) + "\n")
|
|
152
|
|
153 if linecount == 0:
|
|
154 print "No data, exiting"
|
|
155 with open(outfile, 'w') as o:
|
|
156 o.write("RGYW (%)," + ("0,0,0\n" * len(genes)))
|
|
157 o.write("WRCY (%)," + ("0,0,0\n" * len(genes)))
|
|
158 o.write("WA (%)," + ("0,0,0\n" * len(genes)))
|
|
159 o.write("TW (%)," + ("0,0,0\n" * len(genes)))
|
|
160 import sys
|
|
161
|
|
162 sys.exit()
|
|
163
|
|
164 hotspotMatcher = re.compile("[actg]+,(\d+)-(\d+)\((.*)\)")
|
|
165 RGYWCount = {}
|
|
166 WRCYCount = {}
|
|
167 WACount = {}
|
|
168 TWCount = {}
|
|
169
|
|
170 #IDIndex = 0
|
|
171 ataIndex = 0
|
|
172 tatIndex = 0
|
|
173 aggctatIndex = 0
|
|
174 atagcctIndex = 0
|
|
175 first = True
|
|
176 with open(infile, 'r') as i:
|
|
177 for line in i:
|
|
178 if first:
|
|
179 linesplt = line.split("\t")
|
|
180 ataIndex = linesplt.index("X.a.t.a")
|
|
181 tatIndex = linesplt.index("t.a.t.")
|
|
182 aggctatIndex = linesplt.index("X.a.g.g.c.t..a.t.")
|
|
183 atagcctIndex = linesplt.index("X.a.t..a.g.c.c.t.")
|
|
184 first = False
|
|
185 continue
|
|
186 linesplt = line.split("\t")
|
|
187 gene = linesplt[best_matchIndex]
|
|
188 ID = linesplt[IDIndex]
|
|
189 RGYW = [(int(x), int(y), z) for (x, y, z) in
|
|
190 [hotspotMatcher.match(x).groups() for x in linesplt[aggctatIndex].split("|") if x]]
|
|
191 WRCY = [(int(x), int(y), z) for (x, y, z) in
|
|
192 [hotspotMatcher.match(x).groups() for x in linesplt[atagcctIndex].split("|") if x]]
|
|
193 WA = [(int(x), int(y), z) for (x, y, z) in
|
|
194 [hotspotMatcher.match(x).groups() for x in linesplt[ataIndex].split("|") if x]]
|
|
195 TW = [(int(x), int(y), z) for (x, y, z) in
|
|
196 [hotspotMatcher.match(x).groups() for x in linesplt[tatIndex].split("|") if x]]
|
|
197 RGYWCount[ID], WRCYCount[ID], WACount[ID], TWCount[ID] = 0, 0, 0, 0
|
|
198
|
1
|
199 mutationList = mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
0
|
200 for mutation in mutationList:
|
|
201 frm, where, to, AAfrm, AAwhere, AAto, junk = mutation
|
|
202 mutation_in_RGYW = any([(start <= int(where) <= end) for (start, end, region) in RGYW])
|
|
203 mutation_in_WRCY = any([(start <= int(where) <= end) for (start, end, region) in WRCY])
|
|
204 mutation_in_WA = any([(start <= int(where) <= end) for (start, end, region) in WA])
|
|
205 mutation_in_TW = any([(start <= int(where) <= end) for (start, end, region) in TW])
|
|
206
|
|
207 in_how_many_motifs = sum([mutation_in_RGYW, mutation_in_WRCY, mutation_in_WA, mutation_in_TW])
|
|
208
|
|
209 if in_how_many_motifs > 0:
|
|
210 RGYWCount[ID] += (1.0 * int(mutation_in_RGYW)) / in_how_many_motifs
|
|
211 WRCYCount[ID] += (1.0 * int(mutation_in_WRCY)) / in_how_many_motifs
|
|
212 WACount[ID] += (1.0 * int(mutation_in_WA)) / in_how_many_motifs
|
|
213 TWCount[ID] += (1.0 * int(mutation_in_TW)) / in_how_many_motifs
|
|
214
|
|
215
|
|
216 def mean(lst):
|
|
217 return (float(sum(lst)) / len(lst)) if len(lst) > 0 else 0.0
|
|
218
|
|
219
|
|
220 def median(lst):
|
|
221 lst = sorted(lst)
|
|
222 l = len(lst)
|
|
223 if l == 0:
|
|
224 return 0
|
|
225 if l == 1:
|
|
226 return lst[0]
|
|
227
|
|
228 l = int(l / 2)
|
|
229
|
|
230 if len(lst) % 2 == 0:
|
|
231 return float(lst[l] + lst[(l - 1)]) / 2.0
|
|
232 else:
|
|
233 return lst[l]
|
|
234
|
|
235 funcs = {"mean": mean, "median": median, "sum": sum}
|
|
236
|
|
237 directory = outfile[:outfile.rfind("/") + 1]
|
|
238 value = 0
|
|
239 valuedic = dict()
|
|
240
|
|
241 for fname in funcs.keys():
|
|
242 for gene in genes:
|
|
243 with open(directory + gene + "_" + fname + "_value.txt", 'r') as v:
|
|
244 valuedic[gene + "_" + fname] = float(v.readlines()[0].rstrip())
|
|
245 with open(directory + "all_" + fname + "_value.txt", 'r') as v:
|
|
246 valuedic["total_" + fname] = float(v.readlines()[0].rstrip())
|
|
247
|
|
248
|
|
249 def get_xyz(lst, gene, f, fname):
|
|
250 x = int(round(f(lst)))
|
|
251 y = valuedic[gene + "_" + fname]
|
|
252 z = str(round(x / float(y) * 100, 1)) if y != 0 else "0"
|
|
253 return (str(x), str(y), z)
|
|
254
|
|
255 dic = {"RGYW": RGYWCount, "WRCY": WRCYCount, "WA": WACount, "TW": TWCount}
|
|
256 arr = ["RGYW", "WRCY", "WA", "TW"]
|
|
257
|
|
258 geneMatchers = {gene: re.compile("^" + gene + ".*") for gene in genes}
|
|
259
|
|
260 for fname in funcs.keys():
|
|
261 func = funcs[fname]
|
|
262 foutfile = outfile[:outfile.rindex("/")] + "/hotspot_analysis_" + fname + ".txt"
|
|
263 with open(foutfile, 'w') as o:
|
|
264 for typ in arr:
|
|
265 o.write(typ + " (%)")
|
|
266 curr = dic[typ]
|
|
267 for gene in genes:
|
1
|
268 geneMatcher = geneMatchers[gene]
|
0
|
269 if valuedic[gene + "_" + fname] is 0:
|
|
270 o.write(",0,0,0")
|
|
271 else:
|
|
272 x, y, z = get_xyz([curr[x] for x in [y for y, z in genedic.iteritems() if geneMatcher.match(z)]], gene, func, fname)
|
|
273 o.write("," + x + "," + y + "," + z)
|
|
274
|
|
275 x, y, z = get_xyz([y for x, y in curr.iteritems() if not genedic[x].startswith("unmatched")], "total", func, fname)
|
|
276 o.write("," + x + "," + y + "," + z + "\n")
|
|
277
|
|
278
|
|
279 # for testing
|
|
280 seq_motif_file = outfile[:outfile.rindex("/")] + "/motif_per_seq.txt"
|
|
281 with open(seq_motif_file, 'w') as o:
|
|
282 o.write("ID\tRGYWC\tWRCY\tWA\tTW\n")
|
|
283 for ID in IDlist:
|
|
284 o.write(ID + "\t" + str(round(RGYWCount[ID], 2)) + "\t" + str(round(WRCYCount[ID], 2)) + "\t" + str(round(WACount[ID], 2)) + "\t" + str(round(TWCount[ID], 2)) + "\n")
|