47
|
1 import argparse
|
|
2 import logging
|
|
3 import sys
|
|
4 import os
|
|
5 import re
|
|
6
|
0
|
7 from collections import defaultdict
|
47
|
8
|
|
9 def main():
|
|
10 parser = argparse.ArgumentParser()
|
|
11 parser.add_argument("--input", help="The '7_V-REGION-mutation-and-AA-change-table' and '10_V-REGION-mutation-hotspots' merged together, with an added 'best_match' annotation")
|
|
12 parser.add_argument("--genes", help="The genes available in the 'best_match' column")
|
|
13 parser.add_argument("--empty_region_filter", help="Where does the sequence start?", choices=['leader', 'FR1', 'CDR1', 'FR2'])
|
|
14 parser.add_argument("--output", help="Output file")
|
0
|
15
|
47
|
16 args = parser.parse_args()
|
|
17
|
|
18 infile = args.input
|
|
19 genes = str(args.genes).split(",")
|
|
20 empty_region_filter = args.empty_region_filter
|
|
21 outfile = args.output
|
0
|
22
|
47
|
23 genedic = dict()
|
0
|
24
|
47
|
25 mutationdic = dict()
|
62
|
26 mutationMatcher = re.compile("^(.)(\d+).(.),?[ ]?(.)?(\d+)?.?(.)?(.?.?.?.?.?)?")
|
|
27 mutationMatcher = re.compile("^([actg])(\d+).([actg]),?[ ]?([A-Z])?(\d+)?.?([A-Z])?(.*)?")
|
|
28 mutationMatcher = re.compile("^([actg])(\d+).([actg]),?[ ]?([A-Z])?(\d+)?[>]?([A-Z;])?(.*)?")
|
|
29 mutationMatcher = re.compile("^([nactg])(\d+).([nactg]),?[ ]?([A-Z])?(\d+)?[>]?([A-Z;])?(.*)?")
|
47
|
30 NAMatchResult = (None, None, None, None, None, None, '')
|
|
31 geneMatchers = {gene: re.compile("^" + gene + ".*") for gene in genes}
|
|
32 linecount = 0
|
0
|
33
|
47
|
34 IDIndex = 0
|
|
35 best_matchIndex = 0
|
|
36 fr1Index = 0
|
|
37 cdr1Index = 0
|
|
38 fr2Index = 0
|
|
39 cdr2Index = 0
|
|
40 fr3Index = 0
|
|
41 first = True
|
|
42 IDlist = []
|
|
43 mutationList = []
|
|
44 mutationListByID = {}
|
|
45 cdr1LengthDic = {}
|
|
46 cdr2LengthDic = {}
|
|
47
|
|
48 fr1LengthDict = {}
|
|
49 fr2LengthDict = {}
|
|
50 fr3LengthDict = {}
|
|
51
|
|
52 cdr1LengthIndex = 0
|
|
53 cdr2LengthIndex = 0
|
0
|
54
|
47
|
55 fr1SeqIndex = 0
|
|
56 fr2SeqIndex = 0
|
|
57 fr3SeqIndex = 0
|
|
58
|
|
59 tandem_sum_by_class = defaultdict(int)
|
|
60 expected_tandem_sum_by_class = defaultdict(float)
|
0
|
61
|
47
|
62 with open(infile, 'ru') as i:
|
|
63 for line in i:
|
|
64 if first:
|
|
65 linesplt = line.split("\t")
|
|
66 IDIndex = linesplt.index("Sequence.ID")
|
|
67 best_matchIndex = linesplt.index("best_match")
|
|
68 fr1Index = linesplt.index("FR1.IMGT")
|
|
69 cdr1Index = linesplt.index("CDR1.IMGT")
|
|
70 fr2Index = linesplt.index("FR2.IMGT")
|
|
71 cdr2Index = linesplt.index("CDR2.IMGT")
|
|
72 fr3Index = linesplt.index("FR3.IMGT")
|
|
73 cdr1LengthIndex = linesplt.index("CDR1.IMGT.seq")
|
|
74 cdr2LengthIndex = linesplt.index("CDR2.IMGT.seq")
|
|
75 fr1SeqIndex = linesplt.index("FR1.IMGT.seq")
|
|
76 fr2SeqIndex = linesplt.index("FR2.IMGT.seq")
|
|
77 fr3SeqIndex = linesplt.index("FR3.IMGT.seq")
|
|
78 first = False
|
|
79 continue
|
|
80 linecount += 1
|
0
|
81 linesplt = line.split("\t")
|
47
|
82 ID = linesplt[IDIndex]
|
|
83 genedic[ID] = linesplt[best_matchIndex]
|
62
|
84
|
|
85 mutationdic[ID + "_FR1"] = []
|
|
86 if len(linesplt[fr1Index]) > 5 and empty_region_filter == "leader":
|
|
87 mutationdic[ID + "_FR1"] = [mutationMatcher.match(x).groups() for x in linesplt[fr1Index].split("|") if x]
|
|
88
|
|
89 mutationdic[ID + "_CDR1"] = []
|
|
90 if len(linesplt[cdr1Index]) > 5 and empty_region_filter in ["leader", "FR1"]:
|
|
91 mutationdic[ID + "_CDR1"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr1Index].split("|") if x]
|
|
92
|
|
93 mutationdic[ID + "_FR2"] = []
|
|
94 if len(linesplt[fr2Index]) > 5 and empty_region_filter in ["leader", "FR1", "CDR1"]:
|
|
95 mutationdic[ID + "_FR2"] = [mutationMatcher.match(x).groups() for x in linesplt[fr2Index].split("|") if x]
|
|
96
|
|
97 mutationdic[ID + "_CDR2"] = []
|
|
98 if len(linesplt[cdr2Index]) > 5:
|
|
99 mutationdic[ID + "_CDR2"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr2Index].split("|") if x]
|
|
100
|
|
101 mutationdic[ID + "_FR2-CDR2"] = mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"]
|
|
102
|
|
103 mutationdic[ID + "_FR3"] = []
|
|
104 if len(linesplt[fr3Index]) > 5:
|
|
105 mutationdic[ID + "_FR3"] = [mutationMatcher.match(x).groups() for x in linesplt[fr3Index].split("|") if x]
|
|
106
|
47
|
107 try:
|
62
|
108 pass
|
47
|
109 except Exception as e:
|
|
110 print "Something went wrong while processing this line:"
|
62
|
111 print "line:", linecount
|
|
112 print "fr1 len:", len(linesplt[fr1Index]), "value:", linesplt[fr1Index]
|
|
113 print "cdr1 len:", len(linesplt[cdr1Index]), "value:", linesplt[cdr1Index]
|
|
114 print "fr2 len:", len(linesplt[fr2Index]), "value:", linesplt[fr2Index]
|
|
115 print "cdr2 len:", len(linesplt[cdr2Index]), "value:", linesplt[cdr2Index]
|
|
116 print "fr3 len:", len(linesplt[fr3Index]), "value:", linesplt[fr3Index]
|
|
117 print ID + "_FR1 in mutationdic", ID + "_FR1" in mutationdic
|
|
118 print ID + "_CDR1 in mutationdic", ID + "_CDR1" in mutationdic
|
|
119 print ID + "_FR2 in mutationdic", ID + "_FR2" in mutationdic
|
|
120 print ID + "_CDR2 in mutationdic", ID + "_CDR2" in mutationdic
|
|
121 print ID + "_FR3 in mutationdic", ID + "_FR3" in mutationdic
|
47
|
122 print linesplt
|
|
123 print e
|
|
124 mutationList += mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
|
125 mutationListByID[ID] = mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
|
126
|
|
127 cdr1Length = len(linesplt[cdr1LengthIndex])
|
|
128 cdr2Length = len(linesplt[cdr2LengthIndex])
|
|
129
|
|
130 #print linesplt[fr2SeqIndex]
|
|
131 fr1Length = len(linesplt[fr1SeqIndex]) if empty_region_filter == "leader" else 0
|
|
132 fr2Length = len(linesplt[fr2SeqIndex]) if empty_region_filter in ["leader", "FR1", "CDR1"] else 0
|
|
133 fr3Length = len(linesplt[fr3SeqIndex])
|
|
134
|
|
135 cdr1LengthDic[ID] = cdr1Length
|
|
136 cdr2LengthDic[ID] = cdr2Length
|
|
137
|
|
138 fr1LengthDict[ID] = fr1Length
|
|
139 fr2LengthDict[ID] = fr2Length
|
|
140 fr3LengthDict[ID] = fr3Length
|
|
141
|
|
142 IDlist += [ID]
|
62
|
143 print "len(mutationdic) =", len(mutationdic)
|
47
|
144
|
62
|
145 with open(os.path.join(os.path.dirname(os.path.abspath(infile)), "mutationdict.txt"), 'w') as out_handle:
|
|
146 for ID, lst in mutationdic.iteritems():
|
|
147 for mut in lst:
|
|
148 out_handle.write("{0}\t{1}\n".format(ID, "\t".join([str(x) for x in mut])))
|
47
|
149
|
|
150 #tandem mutation stuff
|
|
151 tandem_frequency = defaultdict(int)
|
|
152 mutation_frequency = defaultdict(int)
|
48
|
153
|
|
154 mutations_by_id_dic = {}
|
|
155 first = True
|
|
156 mutation_by_id_file = os.path.join(os.path.dirname(outfile), "mutation_by_id.txt")
|
|
157 with open(mutation_by_id_file, 'r') as mutation_by_id:
|
|
158 for l in mutation_by_id:
|
|
159 if first:
|
|
160 first = False
|
|
161 continue
|
|
162 splt = l.split("\t")
|
|
163 mutations_by_id_dic[splt[0]] = int(splt[1])
|
|
164
|
47
|
165 tandem_file = os.path.join(os.path.dirname(outfile), "tandems_by_id.txt")
|
|
166 with open(tandem_file, 'w') as o:
|
|
167 highest_tandem_length = 0
|
|
168
|
|
169 o.write("Sequence.ID\tnumber_of_mutations\tnumber_of_tandems\tregion_length\texpected_tandems\tlongest_tandem\ttandems\n")
|
|
170 for ID in IDlist:
|
|
171 mutations = mutationListByID[ID]
|
|
172 if len(mutations) == 0:
|
|
173 continue
|
|
174 last_mut = max(mutations, key=lambda x: int(x[1]))
|
|
175
|
|
176 last_mut_pos = int(last_mut[1])
|
|
177
|
|
178 mut_positions = [False] * (last_mut_pos + 1)
|
|
179
|
|
180 for mutation in mutations:
|
|
181 frm, where, to, frmAA, whereAA, toAA, thing = mutation
|
|
182 where = int(where)
|
|
183 mut_positions[where] = True
|
|
184
|
|
185 tandem_muts = []
|
|
186 tandem_start = -1
|
|
187 tandem_length = 0
|
|
188 for i in range(len(mut_positions)):
|
|
189 if mut_positions[i]:
|
|
190 if tandem_start == -1:
|
|
191 tandem_start = i
|
|
192 tandem_length += 1
|
|
193 #print "".join(["1" if x else "0" for x in mut_positions[:i+1]])
|
|
194 else:
|
|
195 if tandem_length > 1:
|
|
196 tandem_muts.append((tandem_start, tandem_length))
|
|
197 #print "{0}{1} {2}:{3}".format(" " * (i - tandem_length), "^" * tandem_length, tandem_start, tandem_length)
|
|
198 tandem_start = -1
|
|
199 tandem_length = 0
|
|
200 if tandem_length > 1: # if the sequence ends with a tandem mutation
|
|
201 tandem_muts.append((tandem_start, tandem_length))
|
|
202
|
|
203 if len(tandem_muts) > 0:
|
|
204 if highest_tandem_length < len(tandem_muts):
|
|
205 highest_tandem_length = len(tandem_muts)
|
0
|
206
|
47
|
207 region_length = fr1LengthDict[ID] + cdr1LengthDic[ID] + fr2LengthDict[ID] + cdr2LengthDic[ID] + fr3LengthDict[ID]
|
|
208 longest_tandem = max(tandem_muts, key=lambda x: x[1]) if len(tandem_muts) else (0, 0)
|
48
|
209 num_mutations = mutations_by_id_dic[ID] # len(mutations)
|
47
|
210 f_num_mutations = float(num_mutations)
|
|
211 num_tandem_muts = len(tandem_muts)
|
|
212 expected_tandem_muts = f_num_mutations * (f_num_mutations - 1.0) / float(region_length)
|
|
213 o.write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n".format(ID,
|
|
214 str(num_mutations),
|
|
215 str(num_tandem_muts),
|
|
216 str(region_length),
|
|
217 str(round(expected_tandem_muts, 2)),
|
|
218 str(longest_tandem[1]),
|
|
219 str(tandem_muts)))
|
|
220 gene = genedic[ID]
|
|
221 if gene.find("unmatched") == -1:
|
|
222 tandem_sum_by_class[gene] += num_tandem_muts
|
|
223 expected_tandem_sum_by_class[gene] += expected_tandem_muts
|
0
|
224
|
47
|
225 tandem_sum_by_class["all"] += num_tandem_muts
|
|
226 expected_tandem_sum_by_class["all"] += expected_tandem_muts
|
0
|
227
|
47
|
228 gene = gene[:3]
|
|
229 if gene in ["IGA", "IGG"]:
|
|
230 tandem_sum_by_class[gene] += num_tandem_muts
|
|
231 expected_tandem_sum_by_class[gene] += expected_tandem_muts
|
|
232 else:
|
|
233 tandem_sum_by_class["unmatched"] += num_tandem_muts
|
|
234 expected_tandem_sum_by_class["unmatched"] += expected_tandem_muts
|
|
235
|
40
|
236
|
47
|
237 for tandem_mut in tandem_muts:
|
|
238 tandem_frequency[str(tandem_mut[1])] += 1
|
|
239 #print "\t".join([ID, str(len(tandem_muts)), str(longest_tandem[1]) , str(tandem_muts)])
|
|
240
|
|
241 tandem_freq_file = os.path.join(os.path.dirname(outfile), "tandem_frequency.txt")
|
|
242 with open(tandem_freq_file, 'w') as o:
|
|
243 for frq in sorted([int(x) for x in tandem_frequency.keys()]):
|
|
244 o.write("{0}\t{1}\n".format(frq, tandem_frequency[str(frq)]))
|
0
|
245
|
47
|
246 tandem_row = []
|
|
247 genes_extra = list(genes)
|
|
248 genes_extra.append("all")
|
|
249 for x, y, in zip([tandem_sum_by_class[x] for x in genes_extra], [expected_tandem_sum_by_class[x] for x in genes_extra]):
|
|
250 if y != 0:
|
|
251 tandem_row += [x, round(y, 2), round(x / y, 2)]
|
|
252 else:
|
|
253 tandem_row += [x, round(y, 2), 0]
|
0
|
254
|
47
|
255 tandem_freq_file = os.path.join(os.path.dirname(outfile), "shm_overview_tandem_row.txt")
|
|
256 with open(tandem_freq_file, 'w') as o:
|
|
257 o.write("Tandems/Expected (ratio),{0}\n".format(",".join([str(x) for x in tandem_row])))
|
|
258
|
|
259 #print mutationList, linecount
|
|
260
|
62
|
261 AALength = (int(max(mutationList, key=lambda i: int(i[4]) if i[4] and i[5] != ";" else 0)[4]) + 1) # [4] is the position of the AA mutation, None if silent
|
47
|
262 if AALength < 60:
|
|
263 AALength = 64
|
|
264
|
|
265 AA_mutation = [0] * AALength
|
|
266 AA_mutation_dic = {"IGA": AA_mutation[:], "IGG": AA_mutation[:], "IGM": AA_mutation[:], "IGE": AA_mutation[:], "unm": AA_mutation[:], "all": AA_mutation[:]}
|
|
267 AA_mutation_empty = AA_mutation[:]
|
|
268
|
|
269 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/aa_id_mutations.txt"
|
|
270 with open(aa_mutations_by_id_file, 'w') as o:
|
|
271 o.write("ID\tbest_match\t" + "\t".join([str(x) for x in range(1,AALength)]) + "\n")
|
|
272 for ID in mutationListByID.keys():
|
|
273 AA_mutation_for_ID = AA_mutation_empty[:]
|
|
274 for mutation in mutationListByID[ID]:
|
|
275 if mutation[4]:
|
|
276 AA_mutation_position = int(mutation[4])
|
|
277 AA_mutation[AA_mutation_position] += 1
|
|
278 AA_mutation_for_ID[AA_mutation_position] += 1
|
|
279 clss = genedic[ID][:3]
|
|
280 AA_mutation_dic[clss][AA_mutation_position] += 1
|
|
281 o.write(ID + "\t" + genedic[ID] + "\t" + "\t".join([str(x) for x in AA_mutation_for_ID[1:]]) + "\n")
|
0
|
282
|
|
283
|
|
284
|
47
|
285 #absent AA stuff
|
|
286 absentAACDR1Dic = defaultdict(list)
|
|
287 absentAACDR1Dic[5] = range(29,36)
|
|
288 absentAACDR1Dic[6] = range(29,35)
|
|
289 absentAACDR1Dic[7] = range(30,35)
|
|
290 absentAACDR1Dic[8] = range(30,34)
|
|
291 absentAACDR1Dic[9] = range(31,34)
|
|
292 absentAACDR1Dic[10] = range(31,33)
|
|
293 absentAACDR1Dic[11] = [32]
|
0
|
294
|
47
|
295 absentAACDR2Dic = defaultdict(list)
|
|
296 absentAACDR2Dic[0] = range(55,65)
|
|
297 absentAACDR2Dic[1] = range(56,65)
|
|
298 absentAACDR2Dic[2] = range(56,64)
|
|
299 absentAACDR2Dic[3] = range(57,64)
|
|
300 absentAACDR2Dic[4] = range(57,63)
|
|
301 absentAACDR2Dic[5] = range(58,63)
|
|
302 absentAACDR2Dic[6] = range(58,62)
|
|
303 absentAACDR2Dic[7] = range(59,62)
|
|
304 absentAACDR2Dic[8] = range(59,61)
|
|
305 absentAACDR2Dic[9] = [60]
|
0
|
306
|
47
|
307 absentAA = [len(IDlist)] * (AALength-1)
|
|
308 for k, cdr1Length in cdr1LengthDic.iteritems():
|
|
309 for c in absentAACDR1Dic[cdr1Length]:
|
|
310 absentAA[c] -= 1
|
0
|
311
|
47
|
312 for k, cdr2Length in cdr2LengthDic.iteritems():
|
|
313 for c in absentAACDR2Dic[cdr2Length]:
|
|
314 absentAA[c] -= 1
|
0
|
315
|
|
316
|
47
|
317 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/absent_aa_id.txt"
|
|
318 with open(aa_mutations_by_id_file, 'w') as o:
|
|
319 o.write("ID\tcdr1length\tcdr2length\tbest_match\t" + "\t".join([str(x) for x in range(1,AALength)]) + "\n")
|
|
320 for ID in IDlist:
|
|
321 absentAAbyID = [1] * (AALength-1)
|
|
322 cdr1Length = cdr1LengthDic[ID]
|
|
323 for c in absentAACDR1Dic[cdr1Length]:
|
|
324 absentAAbyID[c] -= 1
|
0
|
325
|
47
|
326 cdr2Length = cdr2LengthDic[ID]
|
|
327 for c in absentAACDR2Dic[cdr2Length]:
|
|
328 absentAAbyID[c] -= 1
|
|
329 o.write(ID + "\t" + str(cdr1Length) + "\t" + str(cdr2Length) + "\t" + genedic[ID] + "\t" + "\t".join([str(x) for x in absentAAbyID]) + "\n")
|
0
|
330
|
47
|
331 if linecount == 0:
|
|
332 print "No data, exiting"
|
|
333 with open(outfile, 'w') as o:
|
|
334 o.write("RGYW (%)," + ("0,0,0\n" * len(genes)))
|
|
335 o.write("WRCY (%)," + ("0,0,0\n" * len(genes)))
|
|
336 o.write("WA (%)," + ("0,0,0\n" * len(genes)))
|
|
337 o.write("TW (%)," + ("0,0,0\n" * len(genes)))
|
|
338 import sys
|
0
|
339
|
47
|
340 sys.exit()
|
0
|
341
|
47
|
342 hotspotMatcher = re.compile("[actg]+,(\d+)-(\d+)\((.*)\)")
|
|
343 RGYWCount = {}
|
|
344 WRCYCount = {}
|
|
345 WACount = {}
|
|
346 TWCount = {}
|
0
|
347
|
47
|
348 #IDIndex = 0
|
|
349 ataIndex = 0
|
|
350 tatIndex = 0
|
|
351 aggctatIndex = 0
|
|
352 atagcctIndex = 0
|
|
353 first = True
|
|
354 with open(infile, 'ru') as i:
|
|
355 for line in i:
|
|
356 if first:
|
|
357 linesplt = line.split("\t")
|
|
358 ataIndex = linesplt.index("X.a.t.a")
|
|
359 tatIndex = linesplt.index("t.a.t.")
|
|
360 aggctatIndex = linesplt.index("X.a.g.g.c.t..a.t.")
|
|
361 atagcctIndex = linesplt.index("X.a.t..a.g.c.c.t.")
|
|
362 first = False
|
|
363 continue
|
0
|
364 linesplt = line.split("\t")
|
47
|
365 gene = linesplt[best_matchIndex]
|
|
366 ID = linesplt[IDIndex]
|
|
367 RGYW = [(int(x), int(y), z) for (x, y, z) in
|
|
368 [hotspotMatcher.match(x).groups() for x in linesplt[aggctatIndex].split("|") if x]]
|
|
369 WRCY = [(int(x), int(y), z) for (x, y, z) in
|
|
370 [hotspotMatcher.match(x).groups() for x in linesplt[atagcctIndex].split("|") if x]]
|
|
371 WA = [(int(x), int(y), z) for (x, y, z) in
|
|
372 [hotspotMatcher.match(x).groups() for x in linesplt[ataIndex].split("|") if x]]
|
|
373 TW = [(int(x), int(y), z) for (x, y, z) in
|
|
374 [hotspotMatcher.match(x).groups() for x in linesplt[tatIndex].split("|") if x]]
|
|
375 RGYWCount[ID], WRCYCount[ID], WACount[ID], TWCount[ID] = 0, 0, 0, 0
|
0
|
376
|
62
|
377 with open(os.path.join(os.path.dirname(os.path.abspath(infile)), "RGYW.txt"), 'a') as out_handle:
|
|
378 for hotspot in RGYW:
|
|
379 out_handle.write("{0}\t{1}\n".format(ID, "\t".join([str(x) for x in hotspot])))
|
|
380
|
47
|
381 mutationList = mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
|
|
382 for mutation in mutationList:
|
|
383 frm, where, to, AAfrm, AAwhere, AAto, junk = mutation
|
62
|
384 mutation_in_RGYW = any(((start <= int(where) <= end) for (start, end, region) in RGYW))
|
|
385 mutation_in_WRCY = any(((start <= int(where) <= end) for (start, end, region) in WRCY))
|
|
386 mutation_in_WA = any(((start <= int(where) <= end) for (start, end, region) in WA))
|
|
387 mutation_in_TW = any(((start <= int(where) <= end) for (start, end, region) in TW))
|
0
|
388
|
47
|
389 in_how_many_motifs = sum([mutation_in_RGYW, mutation_in_WRCY, mutation_in_WA, mutation_in_TW])
|
0
|
390
|
47
|
391 if in_how_many_motifs > 0:
|
|
392 RGYWCount[ID] += (1.0 * int(mutation_in_RGYW)) / in_how_many_motifs
|
|
393 WRCYCount[ID] += (1.0 * int(mutation_in_WRCY)) / in_how_many_motifs
|
|
394 WACount[ID] += (1.0 * int(mutation_in_WA)) / in_how_many_motifs
|
|
395 TWCount[ID] += (1.0 * int(mutation_in_TW)) / in_how_many_motifs
|
0
|
396
|
|
397
|
47
|
398 def mean(lst):
|
|
399 return (float(sum(lst)) / len(lst)) if len(lst) > 0 else 0.0
|
0
|
400
|
|
401
|
47
|
402 def median(lst):
|
|
403 lst = sorted(lst)
|
|
404 l = len(lst)
|
|
405 if l == 0:
|
|
406 return 0
|
|
407 if l == 1:
|
|
408 return lst[0]
|
|
409
|
|
410 l = int(l / 2)
|
0
|
411
|
47
|
412 if len(lst) % 2 == 0:
|
|
413 return float(lst[l] + lst[(l - 1)]) / 2.0
|
|
414 else:
|
|
415 return lst[l]
|
0
|
416
|
47
|
417 funcs = {"mean": mean, "median": median, "sum": sum}
|
0
|
418
|
47
|
419 directory = outfile[:outfile.rfind("/") + 1]
|
|
420 value = 0
|
|
421 valuedic = dict()
|
0
|
422
|
47
|
423 for fname in funcs.keys():
|
|
424 for gene in genes:
|
|
425 with open(directory + gene + "_" + fname + "_value.txt", 'r') as v:
|
|
426 valuedic[gene + "_" + fname] = float(v.readlines()[0].rstrip())
|
|
427 with open(directory + "all_" + fname + "_value.txt", 'r') as v:
|
|
428 valuedic["total_" + fname] = float(v.readlines()[0].rstrip())
|
|
429
|
0
|
430
|
47
|
431 def get_xyz(lst, gene, f, fname):
|
|
432 x = round(round(f(lst), 1))
|
|
433 y = valuedic[gene + "_" + fname]
|
|
434 z = str(round(x / float(y) * 100, 1)) if y != 0 else "0"
|
|
435 return (str(x), str(y), z)
|
0
|
436
|
47
|
437 dic = {"RGYW": RGYWCount, "WRCY": WRCYCount, "WA": WACount, "TW": TWCount}
|
|
438 arr = ["RGYW", "WRCY", "WA", "TW"]
|
0
|
439
|
47
|
440 for fname in funcs.keys():
|
|
441 func = funcs[fname]
|
|
442 foutfile = outfile[:outfile.rindex("/")] + "/hotspot_analysis_" + fname + ".txt"
|
|
443 with open(foutfile, 'w') as o:
|
|
444 for typ in arr:
|
|
445 o.write(typ + " (%)")
|
|
446 curr = dic[typ]
|
|
447 for gene in genes:
|
|
448 geneMatcher = geneMatchers[gene]
|
|
449 if valuedic[gene + "_" + fname] is 0:
|
|
450 o.write(",0,0,0")
|
|
451 else:
|
|
452 x, y, z = get_xyz([curr[x] for x in [y for y, z in genedic.iteritems() if geneMatcher.match(z)]], gene, func, fname)
|
|
453 o.write("," + x + "," + y + "," + z)
|
|
454 x, y, z = get_xyz([y for x, y in curr.iteritems() if not genedic[x].startswith("unmatched")], "total", func, fname)
|
|
455 #x, y, z = get_xyz([y for x, y in curr.iteritems()], "total", func, fname)
|
|
456 o.write("," + x + "," + y + "," + z + "\n")
|
0
|
457
|
|
458
|
47
|
459 # for testing
|
|
460 seq_motif_file = outfile[:outfile.rindex("/")] + "/motif_per_seq.txt"
|
|
461 with open(seq_motif_file, 'w') as o:
|
|
462 o.write("ID\tRGYW\tWRCY\tWA\tTW\n")
|
|
463 for ID in IDlist:
|
|
464 #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")
|
|
465 o.write(ID + "\t" + str(RGYWCount[ID]) + "\t" + str(WRCYCount[ID]) + "\t" + str(WACount[ID]) + "\t" + str(TWCount[ID]) + "\n")
|
|
466
|
|
467 if __name__ == "__main__":
|
|
468 main()
|