-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHapFlow.py
More file actions
1762 lines (1684 loc) · 94 KB
/
HapFlow.py
File metadata and controls
1762 lines (1684 loc) · 94 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# HapFlow - visualising haplotypes in sequencing data
# Copyright (C) 2013-2015 Mitchell Sullivan
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Mitchell Sullivan
# mjsull@gmail.com
# Falculty of Science, Health, Education and Engineering
# University of the Sunshine Coast
__author__ = 'mjsull'
import random
import os
import platform
import webbrowser
import sys
import argparse
# get sequence of read aligned to var_pos to var_pos + var-len in the reference
def get_seq_read(read, var_pos, var_len):
a = None
b = None
var_pos -= 1
for i, j in read.get_aligned_pairs():
if j == var_pos and a is None:
a = i
if j == var_pos + var_len:
b = i
break
if not a is None and not b is None:
return read.query_sequence[a:b]
else:
return None
# dummy queue when running in command-line mode strings pushed here will be printed to the console instead of the GUI
class clqueue:
def put(self, theval):
sys.stdout.write(theval + '\n')
# variation class - holds information about variants from the vcf file
class variation:
def __init__(self, chrom, pos, ref, alt, qual):
self.chrom = chrom
self.pos = int(pos)
self.ref = ref
self.alt = alt
self.qual = qual
# Main app
class App:
def __init__(self, master):
if master is None:
if args.ref_max == 'end':
ref_max = float('inf')
else:
try:
ref_max = float(args.max_ref)
except ValueError:
sys.stderr.write('Max. reference must be "end", or an integer.')
return
try:
import pysam
except ImportError:
sys.stderr.write('pysam not found, please install.')
return
if args.reference is None:
testbam = pysam.Samfile(args.bam_file, 'rb')
references = testbam.references
testbam.close()
for i, j in enumerate(references):
self.getflow(args.bam_file, args.vcf_file, args.output_prefix + '.' + str(i) + '.flw', args.max_distance, j, args.ref_min, ref_max, args.min_quality, args.max_coverage)
return
else:
self.getflow(args.bam_file, args.vcf_file, args.output_prefix + '.flw', args.max_distance, args.reference, args.ref_min, ref_max, args.min_quality, args.max_coverage)
self.otu = IntVar(value=0)
self.flowlist = None
self.otufilename = StringVar(value='')
self.writeotu_options = StringVar(value='Assign reads to multiple OTUs')
self.menubar = Menu(master)
self.filemenu = Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Create flow file", command=self.create_flow)
self.filemenu.add_command(label="Load flow file", command=self.get_flow_name)
self.filemenu.add_separator()
self.filemenu.add_command(label="Change max. variants", command=self.change_max_variants)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=self.quit)
self.menubar.add_cascade(label="File", menu=self.filemenu)
self.toolmenu = Menu(self.menubar, tearoff=0)
self.otumenu = Menu(self.toolmenu, tearoff=0)
self.toolmenu.add_command(label="Goto base", command=self.goto_base)
self.toolmenu.add_command(label="Create image", command=self.create_image)
self.otumenu.add_radiobutton(label="OTU 1", selectcolor='black', variable=self.otu, value=0)
self.otumenu.add_radiobutton(label="OTU 2", selectcolor='black', variable=self.otu, value=1)
self.otumenu.add_radiobutton(label="OTU 3", selectcolor='black', variable=self.otu, value=2)
self.otumenu.add_radiobutton(label="OTU 4", selectcolor='black', variable=self.otu, value=3)
self.otumenu.add_radiobutton(label="OTU 5", selectcolor='black', variable=self.otu, value=4)
self.otumenu.add_radiobutton(label="OTU 6", selectcolor='black', variable=self.otu, value=5)
self.otumenu.add_radiobutton(label="OTU 7", selectcolor='black', variable=self.otu, value=6)
self.otumenu.add_radiobutton(label="OTU 8", selectcolor='black', variable=self.otu, value=7)
self.otumenu.add_radiobutton(label="OTU 9", selectcolor='black', variable=self.otu, value=8)
self.otumenu.add_radiobutton(label="OTU 10", selectcolor='black', variable=self.otu, value=9)
self.toolmenu.add_cascade(label="Mark OTU", menu=self.otumenu)
self.toolmenu.add_command(label="Write OTUs", command=self.write_otus)
self.menubar.add_cascade(label="Tools", menu=self.toolmenu)
self.viewmenu = Menu(self.menubar, tearoff=0)
self.viewmenu.add_command(label="Hide gapped", command=self.hide_gapped)
self.viewmenu.add_command(label="Show gapped", command=self.show_gapped)
self.viewmenu.add_command(label="Stretch X", command=self.stretch_x)
self.viewmenu.add_command(label="Shrink X", command=self.shrink_x)
self.viewmenu.add_command(label="Stretch Y", command=self.stretch_y)
self.viewmenu.add_command(label="Shrink Y", command=self.shrink_y)
self.menubar.add_cascade(label="View", menu=self.viewmenu)
self.helpmenu = Menu(self.menubar, tearoff=0)
self.helpmenu.add_command(label="About", command=self.about)
self.helpmenu.add_command(label="Help", command=self.help)
self.helpmenu.add_command(label="Support", command=self.support)
self.helpmenu.add_command(label="Citing", command=self.cite)
self.menubar.add_cascade(label="Help", menu=self.helpmenu)
master.config(menu=self.menubar)
self.currxscroll = 1000
self.curryscroll = 5000
self.fontsize = 10 # When zooming in/out font does scale, we create a custom font and then change the font size when we zoom
self.fontsize2 = 20
self.customFont = tkFont.Font(family="Courier", size=self.fontsize)
self.customFont2 = tkFont.Font(family="Courier", size=self.fontsize2, weight='bold')
self.mainframe = Frame(master)
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)
self.mainframe.grid(row=0, column=0, sticky=NSEW)
xscrollbar = Scrollbar(self.mainframe, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)
yscrollbar = Scrollbar(self.mainframe)
yscrollbar.grid(row=0, column=1, sticky=N+S)
self.canvas = Canvas(self.mainframe, bd=0, bg='#FFFAF0', scrollregion=(0, 0, self.currxscroll, self.curryscroll),
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
self.mainframe.grid_rowconfigure(0, weight=1)
self.mainframe.grid_columnconfigure(0, weight=1)
self.canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscrollbar.config(command=self.xscroll)
yscrollbar.config(command=self.canvas.yview)
self.bamfile = StringVar(value='')
self.vcffile = StringVar(value='')
self.flowfile = StringVar(value='')
self.therefvar = StringVar(value='')
self.refmin = IntVar(value=0)
self.refmax = StringVar(value='end')
self.minvarqual = DoubleVar(value=10.0)
self.maxvarcov = DoubleVar(value=4.0)
self.maxdist = IntVar(value=1000)
self.reflength = None
self.ypossnp = 60
self.yposref = 20
self.ypos1 = 160
self.ypos2 = 225
self.ypos3 = 290
self.ypos4 = 355
self.min_flow = 2
self.block_width = 80
self.xmod = 20
self.ymod = 2
self.gap_size = 8
self.block_height = 60
self.maxvar = 2
self.currflows = set()
self.gapped_state = NORMAL
self.queue = queue.Queue()
self.rcmenu = Menu(root, tearoff=0)
self.rcmenu.add_command(label="Details", command=self.details)
self.rcmenu.add_command(label="Write flow readnames", command=self.write_flow_names)
self.rcmenu.add_command(label="Write flow to BAM", command=self.write_flow_bam)
self.rcmenu.add_command(label="Write group readnames", command=self.write_group_names)
self.rcmenu.add_command(label="Write group to BAM", command=self.write_group_bam)
if platform.system() in ['Windows', 'Linux']:
self.canvas.tag_bind('map', '<Button-3>', self.rightClick)
else:
self.canvas.tag_bind('map', '<Button-2>', self.rightClick)
self.canvas.tag_bind('map', '<Button-1>', self.select_flow)
self.canvas.bind('<Double-Button-1>', self.select_otu)
self.canvas.bind('<Button-1>', self.remove_rc)
root.bind('w', self.stretch_y)
root.bind('s', self.shrink_y)
root.bind('a', self.shrink_x)
root.bind('d', self.stretch_x)
self.canvas.bind('<Configure>', self.update_frame)
self.selected = [None, None, None]
self.lastxmod = None
self.lastymod = None
self.otus = [[None, [], []] for i in range(10)]
if not args.load_flow is None:
self.flowfile.set(args.load_flow)
self.load_flow()
# posts menu when right click on flow - records position of click
def rightClick(self, event):
self.rctag = self.canvas.gettags(CURRENT)
self.rcmenu.unpost()
self.rcmenu.post(event.x_root, event.y_root)
self.rcpos = (event.x_root, event.y_root)
# color flow black to highlight entire flow
def select_flow(self, event):
pos, num, amap, zecurrent = self.canvas.gettags(CURRENT)
thecol = self.canvas.itemcget(CURRENT, 'fill')
if not self.selected[0] is None:
for i in self.canvas.find_withtag(self.selected[0]):
if self.canvas.gettags(i)[1] == self.selected[1]:
self.canvas.itemconfig(i, fill=self.selected[2])
if pos == self.selected[0] and num == self.selected[1]:
self.selected = [None, None, None]
else:
for i in self.canvas.find_withtag(pos):
if self.canvas.gettags(i)[1] == num:
self.canvas.itemconfig(i, fill='#000000')
self.selected = [pos, num, thecol]
self.rcmenu.unpost()
# change the maximum number of variants shown per site
def change_max_variants(self):
x = tkSimpleDialog.askinteger('Change max. variants.', 'Please choose maximum variants per site to show.')
self.maxvar = x
# write defined OTUs to separate BAM files
def write_otus(self):
try:
self.write_otu.destroy()
except:
pass
self.write_otu = Toplevel()
self.write_otu.grab_set()
self.write_otu.wm_attributes("-topmost", 1)
self.otuframe = Frame(self.write_otu)
self.write_otu.geometry('+20+30')
self.write_otu.title('Write OTUs to SAM')
self.samfilenamelabel = Label(self.otuframe, text='Original BAM file:', anchor=E)
self.samfilenamelabel.grid(column=0, row=0, sticky=E)
self.samfilenameentry = Entry(self.otuframe, textvariable=self.bamfile)
self.samfilenameentry.grid(column=1, row=0, sticky=EW)
self.samfilebutton = Button(self.otuframe, text='...', command=self.load_bam)
self.samfilebutton.grid(column=2, row=0)
self.otufilenamelabel = Label(self.otuframe, text='Prefix for output BAM files:', anchor=E)
self.otufilenamelabel.grid(column=0, row=1, sticky=E)
self.otufilenameentry = Entry(self.otuframe, textvariable=self.otufilename)
self.otufilenameentry.grid(column=1, row=1, sticky=EW)
self.otufilebutton = Button(self.otuframe, text='...', command=self.load_otubam)
self.otufilebutton.grid(column=2, row=1)
self.otuopt = OptionMenu(self.otuframe, self.writeotu_options, 'Assign reads to multiple OTUs', 'Ignore reads with multiple OTUs')
self.otuopt.grid(column=0, row=2, columnspan=2)
self.okotu = Button(self.otuframe, text='Ok', command=self.ok_otu)
self.okotu.grid(column=1, row=3, sticky=E)
self.otuframe.grid(padx=10, pady=10)
# choose original BAM file to find alignments
def load_bam(self):
filename = tkFileDialog.askopenfilename(title='Please select alignment file (BAM) from which flow was generated.')
self.bamfile.set(filename)
# select prefix for output BAM files (write OTUs)
def load_otubam(self):
filename = tkFileDialog.asksaveasfilename(title='Prefix for output BAM files.')
self.otufilename.set(filename)
# Seperates alignments into seperate BAM files
def ok_otu(self):
if self.bamfile.get() == '':
tkMessageBox.showerror('BAM file not found.', 'Please select valid BAM file.')
return
if self.otufilename.get() == '':
tkMessageBox.showerror('Prefix not found.', 'Please select valid prefix.')
return
self.write_otu.destroy()
varnum = 0
lastvar = ''
outflows = [[] for i in range(10)]
outpos = [[] for i in range(10)]
with open(self.flowfile.get()) as f:
for line in f:
if line.startswith('F '):
outflow = line.split()[1]
pos = outflow.split(',')[0]
flow = filter(lambda x: not x in ['+s', '+', '-s', '-', 'e'], outflow.split(',')[1:-2])
if pos != lastvar:
varnum += 1
lastvar = pos
getotus = None
for theotu, i in enumerate(self.otus):
if not i[0] is None and varnum >= i[0] and varnum + len(flow) <= i[0] + len(i[1]):
compflow = map(str, i[1][varnum - i[0]:])
gotit = True
for j, k in enumerate(flow):
if k == '_' or k == compflow[j] or (k == 'x' and compflow[j] == str(self.maxvar)) or (k != 'x' and int(k) >= self.maxvar and compflow[j] == str(self.maxvar)):
pass
else:
gotit = False
break
if gotit and self.writeotu_options.get() == 'Assign reads to multiple OTUs':
outflows[theotu].append(outflow)
outpos[theotu].append(varnum - 1)
elif gotit:
if getotus is None:
getotus = theotu
else:
getotus = None
break
if self.writeotu_options.get() != 'Assign reads to multiple OTUs' and not getotus is None:
outflows[getotus].append(outflow)
outpos[getotus].append(varnum - 1)
for i, j in enumerate(outflows):
if len(j) > 0:
if os.path.exists(self.otufilename.get() + '.' + str(i+1) + '.bam'):
answer = tkMessageBox.askyesno('File already exists', 'Overwrite ' + self.otufilename.get() + '.' + str(i+1) + '.bam')
if not answer:
return
self.get_names(j, outpos[i], True, self.otufilename.get() + '.' + str(i+1) + '.bam')
# keeps track of define OTUs and adds OTU numbers when double clicking the canvas
def select_otu(self, event):
if self.flowlist is None:
return
absx, absy = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
xnum = int((absx+self.xmod*2) / self.xmod/4)
xcoord = (xnum) * self.xmod * 4 - self.xmod * 2
for i, j in enumerate(self.stacker):
if absy <= self.ypos1 + j*self.ymod:
ynum = i-1
break
if absy >= self.ypos1 + self.stacker[-1]*self.ymod:
ynum = len(self.stacker) - 1
if ynum != -1:
stacknum = (xnum - 1) * (self.maxvar + 1) + ynum
ycoord = self.ypos1 + self.stacker[ynum] * self.ymod + int(self.otustack[(xnum - 1) * (self.maxvar + 1) + ynum]) * self.fontsize2
if self.otus[self.otu.get()][1] == []:
self.otus[self.otu.get()][2].append(self.canvas.create_text(xcoord, ycoord, anchor=NW, text=str(self.otu.get()+1), font=self.customFont2, tags='otus'))
self.otus[self.otu.get()][0] = xnum
self.otus[self.otu.get()][1].append(ynum)
self.otustack = self.otustack[:stacknum] + str(int(self.otustack[stacknum]) + 1) + self.otustack[stacknum+1:]
elif xnum == self.otus[self.otu.get()][0] - 1:
self.otus[self.otu.get()][2].insert(0, self.canvas.create_text(xcoord, ycoord, anchor=NW, text=str(self.otu.get()+1), font=self.customFont2, tags='otus'))
self.otus[self.otu.get()][0] = xnum
self.otus[self.otu.get()][1].insert(0, ynum)
self.otustack = self.otustack[:stacknum] + str(int(self.otustack[stacknum]) + 1) + self.otustack[stacknum+1:]
elif xnum == self.otus[self.otu.get()][0] + len(self.otus[self.otu.get()][1]):
self.otus[self.otu.get()][2].append(self.canvas.create_text(xcoord, ycoord, anchor=NW, text=str(self.otu.get()+1), font=self.customFont2, tags='otus'))
self.otus[self.otu.get()][1].append(ynum)
self.otustack = self.otustack[:stacknum] + str(int(self.otustack[stacknum]) + 1) + self.otustack[stacknum+1:]
elif xnum == self.otus[self.otu.get()][0]:
self.canvas.delete(self.otus[self.otu.get()][2][0])
self.otus[self.otu.get()][2].pop(0)
self.otus[self.otu.get()][1].pop(0)
self.otus[self.otu.get()][0] += 1
self.otustack = self.otustack[:stacknum] + str(int(self.otustack[stacknum]) - 1) + self.otustack[stacknum+1:]
elif xnum == self.otus[self.otu.get()][0] + len(self.otus[self.otu.get()][1]) - 1:
self.canvas.delete(self.otus[self.otu.get()][2][-1])
self.otus[self.otu.get()][2].pop()
self.otus[self.otu.get()][1].pop()
self.otustack = self.otustack[:stacknum] + str(int(self.otustack[stacknum]) - 1) + self.otustack[stacknum+1:]
# remove the right-click menu
def remove_rc(self, event):
self.rcmenu.unpost()
# find flow in the flow file
def find_flow(self, pos, num):
flowfile = open(self.flowfile.get())
count = 0
for line in flowfile:
if line.startswith('F'):
if line[2:].startswith(pos + ','):
count += 1
if count == num:
flowfile.close()
return line.split()[1]
# get the names of the reads associated with a flow or flows
def get_names(self, flows, positions, BAM=True, outfile=None):
try:
import pysam
except ImportError:
tkMessageBox.showerror('Pysam not installed.', 'This functionality is only available if pysam is isntalled.')
return
if self.bamfile.get() == '':
filename = tkFileDialog.askopenfilename(title='Please select alignment file (BAM) from which flow was generated.')
self.bamfile.set(filename)
try:
sam = pysam.Samfile(self.bamfile.get(), 'rb')
except IOError:
tkMessageBox.showerror('File not found', 'Please select a valid BAM file.')
self.bamfile.set('')
return
except ValueError:
tkMessageBox.showerror('File not BAM file', 'Please make sure the file is a valid, indexed BAM file.')
self.bamfile.set('')
return
minsnp = float('inf')
maxsnp = 0
for i in range(len(flows)):
minisnp = int(positions[i])
maxisnp = int(positions[i]) + len(filter(lambda x: not x in ['+s', '+', '-s', '-', 'e'], flows[i].split(',')[1:-2])) -1
if minisnp < minsnp:
minsnp = minisnp
if maxisnp > maxsnp:
maxsnp = maxisnp
snplist = []
getit = True
minsnp = max([0, minsnp-1])
i = minsnp
while getit:
position = self.poslist[i][0]
if position >= self.poslist[maxsnp][0] + self.maxdist.get():
getit = False
alt = ''
for j in self.poslist[i][1:]:
if j.startswith('*'):
ref = j[1:]
else:
alt += ',' + j
alt = alt[1:]
aninstance = variation(self.chrom, position, ref, alt, 0)
snplist.append(aninstance)
i += 1
reads = {}
for snp in snplist: # for each variant in the vcf file
vardict = {}
varorder = []
varcount = {}
currerr = 0
varlength = len(snp.ref)
for i in [snp.ref] + snp.alt.split(','):
varcount[i] = 0
for theread in sam.fetch(snp.chrom, snp.pos, snp.pos + 1):
rvar = get_seq_read(theread, snp.pos, varlength)
if rvar in varcount:
varcount[rvar] += 1
else:
currerr += 1
for i in varcount:
varorder.append((varcount[i], i))
varorder.sort(reverse=True)
count = 0
for i in varorder:
vardict[i[1]] = str(count)
count += 1
gottenreads = set() # prevent dovetailed paired-end reads recording two variants at a single position
for theread in sam.fetch(snp.chrom, snp.pos, snp.pos+1):
readname = theread.query_name
if not readname in gottenreads: # ignore the start of the second pair in dovetailed reads, there might be a better solution to this but would take a long time to implement and wouldn't provide much additional clarity.
rvar = get_seq_read(theread, snp.pos, varlength)
if readname in reads and not rvar is None:
if reads[readname][1] != theread.is_read1:
if theread.is_reverse and theread.reference_start + 1 == snp.pos:
reads[readname].append('-s')
elif theread.is_reverse:
reads[readname].append('-')
elif theread.reference_start + 1 == snp.pos:
reads[readname].append('+s')
else:
reads[readname].append('+')
reads[readname][1] = theread.is_read1
elif not rvar is None:
reads[readname] = [snp.pos, theread.is_read1]
if theread.is_reverse and theread.reference_start + 1 == snp.pos:
reads[readname].append('-s')
elif theread.is_reverse:
reads[readname].append('-')
elif theread.reference_start + 1 == snp.pos:
reads[readname].append('+s')
else:
reads[readname].append('+')
if rvar in vardict:
reads[readname].append(vardict[rvar])
elif not rvar is None:
reads[readname].append('x')
gottenreads.add(readname)
if not rvar is None and theread.reference_end + 1 == snp.pos:
reads[readname].append('e')
for i in reads:
if not i in gottenreads:
reads[i].append('_')
outset = set()
for i in reads:
for j in flows:
if int(j.split(',')[0]) == reads[i][0] and ','.join(reads[i][2:]).strip(',_') == ','.join(j.split(',')[1:-2]):
outset.add(i)
if BAM:
if outfile is None:
outfile = tkFileDialog.asksaveasfilename(title='Choose path to write alignments to (BAM).')
if outfile[-4:] != '.bam':
outfile += '.bam'
try:
newsam = pysam.Samfile(outfile, 'wb', template=sam)
except IOError:
tkMessageBox.showerror('File not valid', 'Please select a valid output file.')
return
for read in sam.fetch():
if read.qname in outset:
newsam.write(read)
newsam.close()
else:
if outfile is None:
outfile = tkFileDialog.asksaveasfilename(title='Choose path to write read names to.')
try:
out = open(outfile, 'w')
except IOError:
tkMessageBox.showerror('File not valid', 'Please select a valid output file.')
return
for i in outset:
out.write(i + '\n')
out.close()
sam.close()
# create window with details of the flow
def details(self):
pos, num, amap, securrent = self.rctag
pos = str(self.poslist[int(pos[1:])][0])
num = int(num[1:])
flow = self.find_flow(pos, num)
try:
self.detail_window.destroy()
except:
pass
self.detail_window = Toplevel()
splitline = flow.split(',')
self.detail_frame = Frame(self.detail_window)
self.hl1 = Label(self.detail_frame, text='Position:', anchor=E)
self.hl1.grid(column=0, row=1)
self.he1 = Entry(self.detail_frame, textvariable=StringVar(value=splitline[0]), state='readonly')
self.he1.grid(column=1, row=1)
self.hl2 = Label(self.detail_frame, text='Flow:', anchor=E)
self.hl2.grid(column=0, row=2)
self.he2 = Entry(self.detail_frame, textvariable=StringVar(value=', '.join(splitline[1:-2])), state='readonly')
self.he2.grid(column=1, row=2)
self.hl3 = Label(self.detail_frame, text='Count:', anchor=E)
self.hl3.grid(column=0, row=3)
self.he3 = Entry(self.detail_frame, textvariable=StringVar(value=splitline[-2]), state='readonly')
self.he3.grid(column=1, row=3)
self.hl4 = Label(self.detail_frame, text='Group:', anchor=E)
self.hl4.grid(column=0, row=4)
self.he4 = Entry(self.detail_frame, textvariable=StringVar(value=splitline[-1]), state='readonly')
self.he4.grid(column=1, row=4)
self.detail_frame.grid(padx=5, pady=5)
# write read names of flow
def write_flow_names(self):
pos, num, amap, securrent = self.rctag
posnum = int(pos[1:])
pos = str(self.poslist[int(pos[1:])][0])
num = int(num[1:])
flow = self.find_flow(pos, num)
self.get_names([flow], [posnum], False)
# write bam alignment of flow
def write_flow_bam(self):
pos, num, amap, securrent = self.rctag
posnum = int(pos[1:])
pos = str(self.poslist[int(pos[1:])][0])
num = int(num[1:])
flow = self.find_flow(pos, num)
self.get_names([flow], [posnum])
# get all flows associated with group
def get_group(self, group):
flowfile = open(self.flowfile.get())
count = 0
flows, posnums = [], []
for line in flowfile:
if line.startswith('F'):
if line.rstrip()[-len(group)-1:] == ',' + group:
flows.append(line.split()[1])
posnums.append(count)
count += 1
return flows, posnums
# write bam file of all flows in group
def write_group_bam(self):
pos, num, amap, securrent = self.rctag
pos = str(self.poslist[int(pos[1:])][0])
num = int(num[1:])
flow = self.find_flow(pos, num)
group = flow.split(',')[-1]
flows, posnums = self.get_group(group)
self.get_names(flows, posnums)
# write read names of all flows in group
def write_group_names(self):
pos, num, amap, securrent = self.rctag
pos = str(self.poslist[int(pos[1:])][0])
num = int(num[1:])
flow = self.find_flow(pos, num)
group = flow.split(',')[-1]
flows, posnums = self.get_group(group)
self.get_names(flows, posnums, False)
# convert hue/saturation/lightness to red green blue
def hsl_to_rgb(self, h, s, l):
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h *1.0 / 60 % 2 - 1))
m = l - c/2
if h < 60:
r, g, b = c + m, x + m, 0 + m
elif h < 120:
r, g, b = x + m, c+ m, 0 + m
elif h < 180:
r, g, b = 0 + m, c + m, x + m
elif h < 240:
r, g, b, = 0 + m, x + m, c + m
elif h < 300:
r, g, b, = x + m, 0 + m, c + m
else:
r, g, b, = c + m, 0 + m, x + m
r = int(r * 255)
g = int(g * 255)
b = int(b * 255)
return '#%02x%02x%02x' % (r, g, b)
# update the frame - remove flows not near the frame of focus add flows coming near the frame of focus
def update_frame(self, temp=None):
if self.flowlist is None:
return
tilt = 0.5
x1 = self.canvas.canvasx(0)
x2 = self.canvas.canvasx(self.canvas.winfo_width())
self.canvas.delete('top')
indexa = int(x1 / self.xmod/4)
indexb = int(x2 / self.xmod/4)
if indexb >= len(self.flowlist):
indexb = len(self.flowlist) - 1
positions = []
suppositions = []
if self.xmod == self.lastxmod and self.ymod == self.lastymod:
toremove = set()
for i in self.currflows:
if i < indexa -10 or i > indexb + 10:
self.canvas.delete('p' + str(i))
toremove.add(i)
for i in toremove:
self.currflows.remove(i)
else:
self.currflows = set()
self.canvas.delete('top')
self.canvas.delete('map')
self.canvas.delete('gapped')
self.lastxmod = self.xmod
self.lastymod = self.ymod
for i in self.stacker:
self.canvas.create_line(x1+5, self.ypos1 + i * self.ymod - 3, x2-5, self.ypos1 + i * self.ymod - 3, tags='top', fill='gray')
for i in range(max([indexa, 0]), indexb):
if not i in self.currflows:
count = 0
self.currflows.add(i)
for j in self.flowlist[i]:
count += 1
if j[0] == 0: # if single forward
self.canvas.create_line([j[1][0] * self.xmod, j[2][0] * self.ymod + self.ypos1, j[1][1] * self.xmod, j[2][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1]), 2):
self.canvas.create_line([(j[1][k-1]) * self.xmod, j[2][k-1] * self.ymod + self.ypos1, (j[1][k-1] + tilt) * self.xmod, j[2][k-1] * self.ymod + self.ypos1,
(j[1][k] - tilt) * self.xmod, j[2][k] * self.ymod + self.ypos1, (j[1][k]) * self.xmod, j[2][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][k] * self.xmod, j[2][k] * self.ymod + self.ypos1, j[1][k+1] * self.xmod, j[2][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
elif j[0] == 1: # if single reverse
self.canvas.create_line([j[1][0] * self.xmod, j[2][0] * self.ymod + self.ypos1, j[1][1] * self.xmod, j[2][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1]), 2):
self.canvas.create_line([(j[1][k-1]) * self.xmod, j[2][k-1] * self.ymod + self.ypos1, (j[1][k-1] + tilt) * self.xmod, j[2][k-1] * self.ymod + self.ypos1,
(j[1][k] - tilt) * self.xmod, j[2][k] * self.ymod + self.ypos1, (j[1][k]) * self.xmod, j[2][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][k] * self.xmod, j[2][k] * self.ymod + self.ypos1, j[1][k+1] * self.xmod, j[2][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
elif j[0] == 2: # if pair F F
self.canvas.create_line([j[1][0][0] * self.xmod, j[2][0][0] * self.ymod + self.ypos1, j[1][0][1] * self.xmod, j[2][0][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][0]), 2):
self.canvas.create_line([(j[1][0][k-1]) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1, (j[1][0][k-1] + tilt) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1,
(j[1][0][k] - tilt) * self.xmod, j[2][0][k] * self.ymod + self.ypos1, (j[1][0][k]) * self.xmod, j[2][0][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][0][k] * self.xmod, j[2][0][k] * self.ymod + self.ypos1, j[1][0][k+1] * self.xmod, j[2][0][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][1] * self.xmod, j[2][1][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][1]), 2):
self.canvas.create_line([(j[1][1][k-1]) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1, (j[1][1][k-1] + tilt) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1,
(j[1][1][k] - tilt) * self.xmod, j[2][1][k] * self.ymod + self.ypos1, (j[1][1][k]) * self.xmod, j[2][1][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][k] * self.xmod, j[2][1][k] * self.ymod + self.ypos1, j[1][1][k+1] * self.xmod, j[2][1][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
if j[5]:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + 1) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - 1) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=int(j[3]/4), fill='#000000', dash=(5,2), tags=('p' + str(i), 'gapped'), state=self.gapped_state)
else:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + tilt) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - tilt) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=int(j[3]/4), fill=j[4], dash=(5,2), tags=('p' + str(i), 'f' + str(count), 'map'))
elif j[0] == 3: # if pair F R
self.canvas.create_line([j[1][0][0] * self.xmod, j[2][0][0] * self.ymod + self.ypos1, j[1][0][1] * self.xmod, j[2][0][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][0]), 2):
self.canvas.create_line([(j[1][0][k-1]) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1, (j[1][0][k-1] + tilt) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1,
(j[1][0][k] - tilt) * self.xmod, j[2][0][k] * self.ymod + self.ypos1, (j[1][0][k]) * self.xmod, j[2][0][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][0][k] * self.xmod, j[2][0][k] * self.ymod + self.ypos1, j[1][0][k+1] * self.xmod, j[2][0][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][1] * self.xmod, j[2][1][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][1]), 2):
self.canvas.create_line([(j[1][1][k-1]) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1, (j[1][1][k-1] + tilt) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1,
(j[1][1][k] - tilt) * self.xmod, j[2][1][k] * self.ymod + self.ypos1, (j[1][1][k]) * self.xmod, j[2][1][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][k] * self.xmod, j[2][1][k] * self.ymod + self.ypos1, j[1][1][k+1] * self.xmod, j[2][1][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
if j[5]:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + 1) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - 1) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill='#000000', dash=(5,2), tags=('p' + str(i), 'gapped'), state=self.gapped_state)
else:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + tilt) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - tilt) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], dash=(5,2), tags=('p' + str(i), 'f' + str(count), 'map'))
elif j[0] == 4: # if pair R F
self.canvas.create_line([j[1][0][0] * self.xmod, j[2][0][0] * self.ymod + self.ypos1, j[1][0][1] * self.xmod, j[2][0][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][0]), 2):
self.canvas.create_line([(j[1][0][k-1]) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1, (j[1][0][k-1] + tilt) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1,
(j[1][0][k] - tilt) * self.xmod, j[2][0][k] * self.ymod + self.ypos1, (j[1][0][k]) * self.xmod, j[2][0][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][0][k] * self.xmod, j[2][0][k] * self.ymod + self.ypos1, j[1][0][k+1] * self.xmod, j[2][0][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][1] * self.xmod, j[2][1][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][1]), 2):
self.canvas.create_line([(j[1][1][k-1]) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1, (j[1][1][k-1] + tilt) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1,
(j[1][1][k] - tilt) * self.xmod, j[2][1][k] * self.ymod + self.ypos1, (j[1][1][k]) * self.xmod, j[2][1][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=str(i))
self.canvas.create_line([j[1][1][k] * self.xmod, j[2][1][k] * self.ymod + self.ypos1, j[1][1][k+1] * self.xmod, j[2][1][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=LAST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
if j[5]:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + 1) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - 1) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill='#000000', dash=(5,2), tags=('p' + str(i), 'gapped'), state=self.gapped_state)
else:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + tilt) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - tilt) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), dash=(5,2), tags=('p' + str(i), 'f' + str(count), 'map'))
elif j[0] == 5: # if pair R R
self.canvas.create_line([j[1][0][0] * self.xmod, j[2][0][0] * self.ymod + self.ypos1, j[1][0][1] * self.xmod, j[2][0][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][0]), 2):
self.canvas.create_line([(j[1][0][k-1]) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1, (j[1][0][k-1] + tilt) * self.xmod, j[2][0][k-1] * self.ymod + self.ypos1,
(j[1][0][k] - tilt) * self.xmod, j[2][0][k] * self.ymod + self.ypos1, (j[1][0][k]) * self.xmod, j[2][0][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][0][k] * self.xmod, j[2][0][k] * self.ymod + self.ypos1, j[1][0][k+1] * self.xmod, j[2][0][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][1] * self.xmod, j[2][1][1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
for k in range(2, len(j[1][1]), 2):
self.canvas.create_line([(j[1][1][k-1]) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1, (j[1][1][k-1] + tilt) * self.xmod, j[2][1][k-1] * self.ymod + self.ypos1,
(j[1][1][k] - tilt) * self.xmod, j[2][1][k] * self.ymod + self.ypos1, (j[1][1][k]) * self.xmod, j[2][1][k] * self.ymod + self.ypos1],
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], tags=('p' + str(i), 'f' + str(count), 'map'))
self.canvas.create_line([j[1][1][k] * self.xmod, j[2][1][k] * self.ymod + self.ypos1, j[1][1][k+1] * self.xmod, j[2][1][k+1] * self.ymod + self.ypos1],
width=j[3] * self.ymod, fill=j[4], arrow=FIRST, arrowshape=(5, 5, 0), tags=('p' + str(i), 'f' + str(count), 'map'))
if j[5]:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + 1) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - 1) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill='#000000', dash=(5,2), tags=('p' + str(i), 'gapped'), state=self.gapped_state)
else:
self.canvas.create_line((j[1][0][-1] * self.xmod, j[2][0][-1] * self.ymod + self.ypos1, (j[1][0][-1] + tilt) * self.xmod, j[2][0][-1] * self.ymod + self.ypos1,
(j[1][1][0] - tilt) * self.xmod, j[2][1][0] * self.ymod + self.ypos1, j[1][1][0] * self.xmod, j[2][1][0] * self.ymod + self.ypos1),
smooth=True, width=min([10, j[3] * self.ymod / 8]), fill=j[4], dash=(5,2), tags=('p' + str(i), 'f' + str(count), 'map'))
xpos = (i + 1) * self.xmod * 4
if i >= indexa:
suppositions.append(xpos)
positions.append(self.poslist[i][0])
thetext = str(self.poslist[i][0]) + '\n' + '\n'.join(self.poslist[i][1:])
self.canvas.create_text(xpos + 4, self.ymod * self.flowend + self.ypos1 + 5, anchor=NW, text=thetext, font=self.customFont, tags='top')
self.canvas.create_rectangle(x1+10, self.ypossnp + 20, x2 - 10, self.ypossnp, tags='top', fill='#E1974C')
self.canvas.tag_raise('gapped')
self.canvas.tag_raise('otus')
if len(positions) > 1:
for i in range(len(positions)):
xpos = x1+15 + int((positions[i] - positions[0]) * 1.0 / (positions[-1] - positions[0]) * (x2 - x1 - 30))
self.canvas.create_line(suppositions[i], self.ypos1 + self.ymod * self.flowend, suppositions[i], self.ypos1 - 5, xpos, self.ypossnp + 20, xpos, self.ypossnp, tags='top', width=2)
self.canvas.create_rectangle(x1 + 10, self.yposref + 20, x2 - 10, self.yposref, tags='top', fill='#7293CB')
starto = x1 + 10 + int(positions[0] * 1.0 / self.reflength * (x2 - x1 - 20))
endo = x1 + 10 + int(positions[-1] * 1.0 / self.reflength * (x2 - x1 - 20))
self.canvas.create_rectangle(starto, self.yposref + 20, endo, self.yposref, tags='top', fill='#E1974C')
self.canvas.create_text(x1 + 10, self.ypossnp - 2, anchor=SW, text='SNP block start..stop: ' + str(positions[0]) + '..' + str(positions[-1]), font=self.customFont, tags='top')
# open a window that can initiate creating a flow file
def create_flow(self):
try:
import pysam
except ImportError:
tkMessageBox.showerror('Pysam not found',
'Creating a flow file requires Pysam, please install.')
return
self.create_flow_top = Toplevel()
self.create_flow_top.grab_set()
self.create_flow_top.wm_attributes("-topmost", 1)
self.create_flow_top.geometry('+20+30')
self.create_flow_top.title('Create Flow')
self.create_flow_frame = Frame(self.create_flow_top)
self.bamfilelabel = Label(self.create_flow_frame, text='BAM file:')
self.bamfilelabel.grid(row=0, column=0, sticky=E)
self.bamfileentry = Entry(self.create_flow_frame, textvariable=self.bamfile, justify=RIGHT, width=30)
self.bamfileentry.grid(row=0, column=1)
self.bamfileentrybutton = Button(self.create_flow_frame, text='...', command=self.loadbam)
self.bamfileentrybutton.grid(row=0, column=2)
self.vcffilelabel = Label(self.create_flow_frame, text='VCF file:')
self.vcffilelabel.grid(row=1, column=0, sticky=E)
self.vcffileentry = Entry(self.create_flow_frame, textvariable=self.vcffile, justify=RIGHT, width=30)
self.vcffileentry.grid(row=1, column=1)
self.vcffileentrybutton = Button(self.create_flow_frame, text='...', command=self.loadvcf)
self.vcffileentrybutton.grid(row=1, column=2)
self.flowfilelabel = Label(self.create_flow_frame, text='Output file:')
self.flowfilelabel.grid(row=2, column=0, sticky=E)
self.flowfileentry = Entry(self.create_flow_frame, textvariable=self.flowfile, justify=RIGHT, width=30)
self.flowfileentry.grid(row=2, column=1)
self.flowfileentrybutton = Button(self.create_flow_frame, text='...', command=self.loadflow)
self.flowfileentrybutton.grid(row=2, column=2)
self.refselectlabel = Label(self.create_flow_frame, text='Select reference:')
self.refselectlabel.grid(row=3, column=0, sticky=E)
self.refselectentry = Entry(self.create_flow_frame, textvariable=self.therefvar, justify=RIGHT, width=30)
self.refselectentry.grid(row=3, column=1)
self.refselectbutton = Button(self.create_flow_frame, text='...', command=self.choose_ref)
self.advanced_label = Label(self.create_flow_frame, text='Advanced options', font='Courier 10 bold', width=30)
self.advanced_label.grid(row=4, column=0, sticky=E)
self.refminlabel = Label(self.create_flow_frame, text='Filter variants before:')
self.refminlabel.grid(row=5, column=0, sticky=E)
self.refminentry = Entry(self.create_flow_frame, textvariable=self.refmin, width=30)
self.refminentry.grid(row=5, column=1)
self.minbplabel = Label(self.create_flow_frame, text='bp')
self.minbplabel.grid(row=5, column=2)
self.refmaxlabel = Label(self.create_flow_frame, text='Filter variants after:')
self.refmaxlabel.grid(row=6, column=0, sticky=E)
self.refmaxentry = Entry(self.create_flow_frame, textvariable=self.refmax, width=30)
self.refmaxentry.grid(row=6, column=1)
self.maxbplabel = Label(self.create_flow_frame, text='bp')
self.maxbplabel.grid(row=6, column=2)
self.maxdistlabel = Label(self.create_flow_frame, text='Max. distance (bp):')
self.maxdistlabel.grid(row=7, column=0, sticky=E)
self.maxdistentry = Entry(self.create_flow_frame, textvariable=self.maxdist, width=30)
self.maxdistentry.grid(row=7, column=1)
self.minvarquallabel = Label(self.create_flow_frame, text='Min. variant quality:')
self.minvarquallabel.grid(row=8, column=0, sticky=E)
self.minvarqualentry = Entry(self.create_flow_frame, textvariable=self.minvarqual, width=30)
self.minvarqualentry.grid(row=8, column=1)
self.maxvarcovlabel = Label(self.create_flow_frame, text='Filter high coverage variants:')
self.maxvarcovlabel.grid(row=9, column=0, sticky=E)
self.maxvarcoventry = Entry(self.create_flow_frame, textvariable=self.maxvarcov, width=30)
self.maxvarcoventry.grid(row=9, column=1)
self.okflow = Button(self.create_flow_frame, text='Ok', command=self.ok_flow)
self.okflow.grid(row=10, column=2, sticky=E)
self.create_flow_frame.grid(padx=10, pady=10)
# ask for bam file name
def loadbam(self):
import pysam
filename = tkFileDialog.askopenfilename(parent=self.create_flow_top)
if filename == '':
return
self.bamfile.set(filename)
testsam = pysam.Samfile(self.bamfile.get(), 'rb')
if len(testsam.references) == 0:
tkMessageBox.showerror('No reference in BAM file', 'Can this even happen?')
return
elif len(testsam.references) == 1:
self.therefvar.set(testsam.references[0])
testsam.close()
else:
self.choose_ref()
def choose_ref(self):
import pysam
try:
testsam = pysam.Samfile(self.bamfile.get(), 'rb')
except IOError:
tkMessageBox.showerror('File not found.', 'Please select a BAM file before choosing the reference.')
self.choice_top = Toplevel()
self.choice_top.grab_set()
self.choice_top.wm_attributes("-topmost", 1)
self.choice_top.geometry('+20+30')
self.choice_top.title('Choose reference')
self.choice_frame = Frame(self.choice_top)
self.choice_label = Label(self.choice_frame, text='Please choose reference\n from which to create flow:')
self.choice_label.grid(row=0, column=0)
self.choice_scroll = Scrollbar(self.choice_frame, orient=VERTICAL)
self.choice_entry = Listbox(self.choice_frame, yscrollcommand=self.choice_scroll.set)
self.choice_scroll.config(command=self.choice_entry.yview)
self.choice_scroll.grid(row=1, column=1, sticky=NS)
self.choice_entry.grid(row=1, column=0, sticky=EW)
for i in testsam.references:
self.choice_entry.insert(END, i)
testsam.close()
self.okchoice = Button(self.choice_frame, text='Ok', command=self.ok_choice)
self.okchoice.grid(row=2, column=0, columnspan=2, sticky=E)
self.choice_frame.grid(padx=10, pady=10)
# ok button for choosing reference from references available in BAM
def ok_choice(self):
self.therefvar.set(self.choice_entry.get(ACTIVE))
self.choice_top.destroy()
# ask for vcf file name
def loadvcf(self):
filename = tkFileDialog.askopenfilename(parent=self.create_flow_top)
if filename == '':
return
self.vcffile.set(filename)
# ask for flow file name
def loadflow(self):
filename = tkFileDialog.asksaveasfilename(parent=self.create_flow_top)
if filename == '':
return
else:
self.flowfile.set(filename)
# initiate the flow file creation process
def ok_flow(self):
if not os.path.exists(self.bamfile.get()) or not os.path.exists(self.vcffile.get()):
tkMessageBox.showerror('File missing', 'Please include a contig and read file.', parent=self.create_flow_top)
return
try:
if self.thethread.is_alive():
tkMessageBox.showerror('Already running process',
'Please wait until current tasks have finished before running another process.')
return
except AttributeError:
pass
self.create_flow_top.destroy()
self.run_flow()
# open a window with updates about the progress of creating the flow file
def run_flow(self):
self.run_flow_top = Toplevel()
self.run_flow_top.grab_set()
self.run_flow_top.wm_attributes("-topmost", 1)
self.run_flow_top.geometry('+20+30')
self.run_flow_top.title('Running flow creation tool')
self.run_flow_frame = Frame(self.run_flow_top)
self.consoletext = StringVar(value='Creating Flow File.')
self.consolelabel = Label(self.run_flow_frame, bg='#FFFF99', relief=SUNKEN, textvariable=self.consoletext, width=35, height=10)
self.consolelabel.grid(row=0, column=0)
self.consolebutton = Button(self.run_flow_frame, text='Ok', command=self.ok_console, state=DISABLED)
self.consolebutton.grid(row=1, column=0, sticky=E)
self.run_flow_frame.grid(padx=10, pady=10)
self.thethread = threading.Thread(target=self.getflow)
self.thethread.start()
self.update_flow()
# remove the console
def ok_console(self):
self.run_flow_top.destroy()
# get messages from thread and print to console
def update_flow(self):
self.dot_console()
while self.queue.qsize():
try:
text = self.queue.get(0)
self.update_console(text)
if text == 'Flow file successfully created.':
self.consolebutton.config(state=NORMAL)
else:
root.after(1000, self.update_flow)
return
except Queue.Empty:
pass
if not self.thethread.is_alive():
self.update_console('Flow file creation failed,\n please check console output.')
self.consolebutton.config(state=NORMAL)
return
elif not self.queue.qsize():
root.after(1000, self.update_flow)
return