comparison mutation_analysis.py.bak @ 53:7290a88ea202 draft

Uploaded
author davidvanzessen
date Mon, 29 Feb 2016 10:49:39 -0500
parents
children
comparison
equal deleted inserted replaced
52:d3542f87a304 53:7290a88ea202
1 from collections import defaultdict
2 import re
3 import argparse
4
5 parser = argparse.ArgumentParser()
6 parser.add_argument("--input",
7 help="The '7_V-REGION-mutation-and-AA-change-table' and '10_V-REGION-mutation-hotspots' merged together, with an added 'best_match' annotation")
8 parser.add_argument("--genes", help="The genes available in the 'best_match' column")
9 parser.add_argument("--includefr1", help="The genes available in the 'best_match' column")
10 parser.add_argument("--output", help="Output file")
11
12 args = parser.parse_args()
13
14 infile = args.input
15 genes = str(args.genes).split(",")
16 print "includefr1 =", args.includefr1
17 include_fr1 = True if args.includefr1 == "yes" else False
18 outfile = args.output
19
20 genedic = dict()
21
22 mutationdic = dict()
23 mutationMatcher = re.compile("^(.)(\d+).(.),?(.)?(\d+)?.?(.)?(.?.?.?.?.?)?")
24 linecount = 0
25
26 IDIndex = 0
27 best_matchIndex = 0
28 fr1Index = 0
29 cdr1Index = 0
30 fr2Index = 0
31 cdr2Index = 0
32 fr3Index = 0
33 first = True
34 IDlist = []
35 mutationList = []
36 mutationListByID = {}
37 cdr1LengthDic = {}
38 cdr2LengthDic = {}
39
40 with open(infile, 'r') as i:
41 for line in i:
42 if first:
43 linesplt = line.split("\t")
44 IDIndex = linesplt.index("Sequence.ID")
45 best_matchIndex = linesplt.index("best_match")
46 fr1Index = linesplt.index("FR1.IMGT")
47 cdr1Index = linesplt.index("CDR1.IMGT")
48 fr2Index = linesplt.index("FR2.IMGT")
49 cdr2Index = linesplt.index("CDR2.IMGT")
50 fr3Index = linesplt.index("FR3.IMGT")
51 cdr1LengthIndex = linesplt.index("CDR1.IMGT.Nb.of.nucleotides")
52 cdr2LengthIndex = linesplt.index("CDR2.IMGT.Nb.of.nucleotides")
53 first = False
54 continue
55 linecount += 1
56 linesplt = line.split("\t")
57 ID = linesplt[IDIndex]
58 genedic[ID] = linesplt[best_matchIndex]
59 mutationdic[ID + "_FR1"] = [mutationMatcher.match(x).groups() for x in linesplt[fr1Index].split("|") if x] if include_fr1 else []
60 mutationdic[ID + "_CDR1"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr1Index].split("|") if x]
61 mutationdic[ID + "_FR2"] = [mutationMatcher.match(x).groups() for x in linesplt[fr2Index].split("|") if x]
62 mutationdic[ID + "_CDR2"] = [mutationMatcher.match(x).groups() for x in linesplt[cdr2Index].split("|") if x]
63 mutationdic[ID + "_FR2-CDR2"] = mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"]
64 mutationdic[ID + "_FR3"] = [mutationMatcher.match(x).groups() for x in linesplt[fr3Index].split("|") if x]
65
66 mutationList += mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
67 mutationListByID[ID] = mutationdic[ID + "_FR1"] + mutationdic[ID + "_CDR1"] + mutationdic[ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
68
69 cdr1Length = linesplt[cdr1LengthIndex]
70 cdr2Length = linesplt[cdr2LengthIndex]
71
72 cdr1LengthDic[ID] = int(cdr1Length) / 3
73 cdr2LengthDic[ID] = int(cdr2Length) / 3
74
75 IDlist += [ID]
76
77 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
78
79 AA_mutation = [0] * AALength
80 AA_mutation_empty = AA_mutation[:]
81
82 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/aa_id_mutations.txt"
83 with open(aa_mutations_by_id_file, 'w') as o:
84 for ID in mutationListByID.keys():
85 AA_mutation_for_ID = AA_mutation_empty[:]
86 for mutation in mutationListByID[ID]:
87 if mutation[4]:
88 AA_mutation[int(mutation[4])] += 1
89 AA_mutation_for_ID[int(mutation[4])] += 1
90 o.write(ID + "\t" + "\t".join([str(x) for x in AA_mutation_for_ID[1:]]) + "\n")
91
92
93
94 #absent AA stuff
95 absentAACDR1Dic = defaultdict(list)
96 absentAACDR1Dic[5] = range(29,36)
97 absentAACDR1Dic[6] = range(29,35)
98 absentAACDR1Dic[7] = range(30,35)
99 absentAACDR1Dic[8] = range(30,34)
100 absentAACDR1Dic[9] = range(31,34)
101 absentAACDR1Dic[10] = range(31,33)
102 absentAACDR1Dic[11] = [32]
103
104 absentAACDR2Dic = defaultdict(list)
105 absentAACDR2Dic[0] = range(55,65)
106 absentAACDR2Dic[1] = range(56,65)
107 absentAACDR2Dic[2] = range(56,64)
108 absentAACDR2Dic[3] = range(57,64)
109 absentAACDR2Dic[4] = range(57,63)
110 absentAACDR2Dic[5] = range(58,63)
111 absentAACDR2Dic[6] = range(58,62)
112 absentAACDR2Dic[7] = range(59,62)
113 absentAACDR2Dic[8] = range(59,61)
114 absentAACDR2Dic[9] = [60]
115
116 absentAA = [len(IDlist)] * (AALength-1)
117 for k, cdr1Length in cdr1LengthDic.iteritems():
118 for c in absentAACDR1Dic[cdr1Length]:
119 absentAA[c] -= 1
120
121 for k, cdr2Length in cdr2LengthDic.iteritems():
122 for c in absentAACDR2Dic[cdr2Length]:
123 absentAA[c] -= 1
124
125
126 aa_mutations_by_id_file = outfile[:outfile.rindex("/")] + "/absent_aa_id.txt"
127 with open(aa_mutations_by_id_file, 'w') as o:
128 o.write("ID\tcdr1length\tcdr2length\t" + "\t".join([str(x) for x in range(1,AALength-1)]) + "\n")
129 for ID in IDlist:
130 absentAAbyID = [1] * (AALength-1)
131 cdr1Length = cdr1LengthDic[ID]
132 for c in absentAACDR1Dic[cdr1Length]:
133 absentAAbyID[c] -= 1
134
135 cdr2Length = cdr2LengthDic[ID]
136 for c in absentAACDR2Dic[cdr2Length]:
137 absentAAbyID[c] -= 1
138 o.write(ID + "\t" + str(cdr1Length) + "\t" + str(cdr2Length) + "\t" + "\t".join([str(x) for x in absentAAbyID]) + "\n")
139
140
141
142 aa_mutations_file = outfile[:outfile.rindex("/")] + "/aa_mutations.txt"
143 with open(aa_mutations_file, 'w') as o:
144 o.write("row.name\t" + "\t".join([str(x) for x in range(1, AALength-1)]) + "\n")
145 o.write("mutations.at.position\t" + "\t".join([str(x) for x in AA_mutation[1:]]) + "\n")
146 o.write("AA.at.position\t" + "\t".join([str(x) for x in absentAA]) + "\n")
147
148 if linecount == 0:
149 print "No data, exiting"
150 with open(outfile, 'w') as o:
151 o.write("RGYW (%)," + ("0,0,0\n" * len(genes)))
152 o.write("WRCY (%)," + ("0,0,0\n" * len(genes)))
153 o.write("WA (%)," + ("0,0,0\n" * len(genes)))
154 o.write("TW (%)," + ("0,0,0\n" * len(genes)))
155 import sys
156
157 sys.exit()
158
159 hotspotMatcher = re.compile("[actg]+,(\d+)-(\d+)\((.*)\)")
160 RGYWCount = {g: 0 for g in genes}
161 WRCYCount = {g: 0 for g in genes}
162 WACount = {g: 0 for g in genes}
163 TWCount = {g: 0 for g in genes}
164
165 IDIndex = 0
166 ataIndex = 0
167 tatIndex = 0
168 aggctatIndex = 0
169 atagcctIndex = 0
170 first = True
171 with open(infile, 'r') as i:
172 for line in i:
173 if first:
174 linesplt = line.split("\t")
175 ataIndex = linesplt.index("X.a.t.a")
176 tatIndex = linesplt.index("t.a.t.")
177 aggctatIndex = linesplt.index("X.a.g.g.c.t..a.t.")
178 atagcctIndex = linesplt.index("X.a.t..a.g.c.c.t.")
179 first = False
180 continue
181 linesplt = line.split("\t")
182 gene = linesplt[best_matchIndex]
183 ID = linesplt[IDIndex]
184 RGYW = [(int(x), int(y), z) for (x, y, z) in
185 [hotspotMatcher.match(x).groups() for x in linesplt[aggctatIndex].split("|") if x]]
186 WRCY = [(int(x), int(y), z) for (x, y, z) in
187 [hotspotMatcher.match(x).groups() for x in linesplt[atagcctIndex].split("|") if x]]
188 WA = [(int(x), int(y), z) for (x, y, z) in
189 [hotspotMatcher.match(x).groups() for x in linesplt[ataIndex].split("|") if x]]
190 TW = [(int(x), int(y), z) for (x, y, z) in
191 [hotspotMatcher.match(x).groups() for x in linesplt[tatIndex].split("|") if x]]
192 RGYWCount[ID], WRCYCount[ID], WACount[ID], TWCount[ID] = 0, 0, 0, 0
193
194 mutationList = (mutationdic[ID + "_FR1"] if include_fr1 else []) + mutationdic[ID + "_CDR1"] + mutationdic[
195 ID + "_FR2"] + mutationdic[ID + "_CDR2"] + mutationdic[ID + "_FR3"]
196 for mutation in mutationList:
197 frm, where, to, AAfrm, AAwhere, AAto, junk = mutation
198 mutation_in_RGYW = any([(start <= int(where) <= end) for (start, end, region) in RGYW])
199 mutation_in_WRCY = any([(start <= int(where) <= end) for (start, end, region) in WRCY])
200 mutation_in_WA = any([(start <= int(where) <= end) for (start, end, region) in WA])
201 mutation_in_TW = any([(start <= int(where) <= end) for (start, end, region) in TW])
202
203 in_how_many_motifs = sum([mutation_in_RGYW, mutation_in_WRCY, mutation_in_WA, mutation_in_TW])
204
205 if in_how_many_motifs > 0:
206 RGYWCount[ID] += (1.0 * int(mutation_in_RGYW)) / in_how_many_motifs
207 WRCYCount[ID] += (1.0 * int(mutation_in_WRCY)) / in_how_many_motifs
208 WACount[ID] += (1.0 * int(mutation_in_WA)) / in_how_many_motifs
209 TWCount[ID] += (1.0 * int(mutation_in_TW)) / in_how_many_motifs
210
211 directory = outfile[:outfile.rfind("/") + 1]
212 value = 0
213 valuedic = dict()
214 for gene in genes:
215 with open(directory + gene + "_value.txt", 'r') as v:
216 valuedic[gene] = int(v.readlines()[0].rstrip())
217 with open(directory + "total_value.txt", 'r') as v:
218 valuedic["total"] = int(v.readlines()[0].rstrip())
219
220 dic = {"RGYW": RGYWCount, "WRCY": WRCYCount, "WA": WACount, "TW": TWCount}
221 arr = ["RGYW", "WRCY", "WA", "TW"]
222 with open(outfile, 'w') as o:
223 for typ in arr:
224 o.write(typ + " (%)")
225 curr = dic[typ]
226 for gene in genes:
227 geneMatcher = re.compile(".*" + gene + ".*")
228 if valuedic[gene] is 0:
229 o.write(",0,0,0")
230 else:
231 x = int(round(sum([curr[x] for x in [y for y, z in genedic.iteritems() if geneMatcher.match(z)]])))
232 y = valuedic[gene]
233 z = str(round(x / float(valuedic[gene]) * 100, 1))
234 o.write("," + str(x) + "," + str(y) + "," + z)
235 # for total
236 x = int(round(sum([y for x, y in curr.iteritems()])))
237 y = valuedic["total"]
238 z = str(round(x / float(valuedic["total"]) * 100, 1))
239 o.write("," + str(x) + "," + str(y) + "," + z + "\n")
240
241
242 # for testing
243 seq_motif_file = outfile[:outfile.rindex("/")] + "/motif_per_seq.txt"
244 with open(seq_motif_file, 'w') as o:
245 o.write("ID\tRGYWC\tWRCY\tWA\tTW\n")
246 for ID in IDlist:
247 o.write(ID + "\t" + str(round(RGYWCount[ID], 2)) + "\t" + str(round(WRCYCount[ID], 2)) + "\t" + str(
248 round(WACount[ID], 2)) + "\t" + str(round(TWCount[ID], 2)) + "\n")