This repository has been archived by the owner on Oct 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeliner.py
executable file
·2159 lines (1709 loc) · 78.1 KB
/
pipeliner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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 python3
import sys,os,math,time
import json,re
import contextlib
import webbrowser
import time,threading
# from subprocess import Popen, PIPE, STDOUT,check_output
from subprocess import *
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askdirectory
from tkinter.messagebox import showerror
from tkinter.ttk import *
from pathlib import Path
try:
# Python2
from Tkinter import *
import Tkinter
import tkMessageBox
import tkFileDialog
except ImportError:
# Python3
from tkinter import *
import tkinter
import tkinter.messagebox
import tkinter.filedialog
#################
#Globals
#################
UnitsBak=[]
RGbak={}
cfile="pipeliner.json"
def load_config(cfile=cfile):
global Cfg
Q=open(cfile,"r")
Cfg=eval(Q.read())
Q.close()
load_config()
def set_colors(*args):
global baseColor
global entryFgColor
global entryBgColor
global textDarkColor
global textLightColor
global widgetFgColor
global widgetBgColor
global projectFgColor
global projectBgColor
global statusFgColor
global statusBgColor
global dryrunFgColor
global dryrunBgColor
global logFgColor
global logBgColor
global errorsFgColor
global errorsBgColor
global menuFgColor
global menuBgColor
global commentFgColor
global commentBgColor
baseColor=Cfg['colors']['base'][0]
entryFgColor=Cfg['colors']['entry'][0]
entryBgColor=Cfg['colors']['entry'][1]
textDarkColor=Cfg['colors']['text'][0]
textLightColor=Cfg['colors']['text'][1]
widgetFgColor=Cfg['colors']['widget'][0]
widgetBgColor=Cfg['colors']['widget'][1]
projectFgColor=Cfg['colors']['project'][0]
projectBgColor=Cfg['colors']['project'][1]
statusFgColor=Cfg['colors']['status'][0]
statusBgColor=Cfg['colors']['status'][1]
dryrunFgColor=Cfg['colors']['dryrun'][0]
dryrunBgColor=Cfg['colors']['dryrun'][1]
logFgColor=Cfg['colors']['log'][0]
logBgColor=Cfg['colors']['log'][1]
errorsFgColor=Cfg['colors']['errors'][0]
errorsBgColor=Cfg['colors']['errors'][1]
menuFgColor=Cfg['colors']['menu'][0]
menuBgColor=Cfg['colors']['menu'][1]
commentFgColor=Cfg['colors']['comments'][0]
commentBgColor=Cfg['colors']['comments'][1]
#baseColor="red4"
#widgetBgColor="goldenrod"
set_colors()
customRules=[]
pipeline=["initialqc","exomeseq-somatic","exomeseq-germline"]
auto_check=0
whereiam=os.popen("cd ../ && pwd").read().strip()
uhome=os.popen("echo $HOME").read().strip()
runmode=1
defaultwork=whereiam+"/Results"
#tkinter.messagebox.showinfo("path",whereiam)
rules=os.popen("cd Rules && ls *.rl|grep -v all-").read().replace(".rl","").split("\n")
b=rules.pop()
#rules=['samtools.sort','picard.headers','picard-markdups']
PL="initialqc"
smver=os.popen("snakemake --version").read().strip()
#PJ=open("project.json","r")
#projectjson=PJ.read()
#PJ.close()
errorreport=""
batchsize="20"
parameters=[]
smparams=[]
newlines = ['\n', '\r\n', '\r']
####################
#Functions
###################
def pipelineget():
if pfamily.get()=="exomeseq":
pipeline_current=Pipeline.get()
if pfamily.get()=="rnaseq":
pipeline_current=rPipeline.get()
if pfamily.get()=="chipseq":
pipeline_current=cPipeline.get()
if pfamily.get()=="mirseq":
pipeline_current=mPipeline.get()
if pfamily.get()=="genomeseq":
pipeline_current=gPipeline.get()
return(pipeline_current)
def checklist(*args):
p=pipelineget()
pairs=workpath.get()+"/pairs"
if p=="exomeseq-somatic":
if os.popen("if [ -s '{0}' ]; then echo 'ok';fi".format(pairs)).read()!="":
return(0)
else:
tkinter.messagebox.showinfo("ExomeSeq Somatic Error","Required ExomeSeq Somatic '{0}' file is either empty or missing.".format(pairs))
return(1)
def writeheader(*args):
if ftype.get()=="rg.tab":
comments.delete(1.0,END)
comments.insert(INSERT,"rgid\trgsm\trglb\trgpl\trgpu\trgcn\n")
if ftype.get()=="pairs":
comments.delete(1.0,END)
comments.insert(INSERT,"Sample1\tSample2\n")
if ftype.get()=="groups.tab":
comments.delete(1.0,END)
comments.insert(INSERT,"Sample.Name\tSample.Group\tSample.Label\n")
if ftype.get()=="contrasts.tab":
comments.delete(1.0,END)
# t=list(PD['project']['units'].keys())
# t.sort()
# comments.insert(INSERT," ".join(t))
comments.insert(INSERT,"group1\tvs.group2\n")
# comments.insert(INSERT,"Sample.Name\tSample.Group\tSample.Label\tContrasts\n")
return
def writepaste():
try:
fname=workpath.get()+"/"+ftype.get()
F=open(fname,"w")
F.write(comments.get('1.0',END))
F.close()
tkinter.messagebox.showinfo("Success","Wrote file "+fname)
except:
tkinter.messagebox.showinfo("Error","Did not write file "+fname+"\nIs working directory set?")
makejson("none")
return
def readpaste():
try:
fname=workpath.get()+"/"+ftype.get()
F=open(fname,"r")
comments.delete("1.0", END)
comments.insert(INSERT, F.read())
F.close()
tkinter.messagebox.showinfo("Success","Read file "+fname)
except:
tkinter.messagebox.showinfo("Error","Did not read file "+fname+"\nIs working directory set?")
makejson("none")
return
def load_configuration():
fname = askopenfilename(filetypes=(("json files", "*.json"),
("All files", "*.*") ))
if fname:
try:
load_config(cfile=fname)
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read config file\n'%s'" % fname)
return
set_colors()
top.configure(bg=baseColor)
# i=top.winfo_children()
# showerror("", i)
_list = top.winfo_children()
for item in _list :
if item.winfo_children() :
_list.extend(item.winfo_children())
for i in filter(lambda w:isinstance(w,LabelFrame), _list):
i.config(fg=textLightColor,bg=baseColor)
for i in filter(lambda w:isinstance(w,Frame), _list):
i.config(fg=textLightColor,bg=baseColor)
for i in filter(lambda w:isinstance(w,Menu), _list):
i.config(fg=menuFgColor,bg=menuBgColor)
for i in filter(lambda w:isinstance(w,Radiobutton), _list):
i.config(fg=widgetFgColor,bg=widgetBgColor)
for i in filter(lambda w:isinstance(w,OptionMenu), _list):
i.config(fg=widgetFgColor,bg=widgetBgColor)
# i.config["menu"](fg=widgetFgColor,bg=widgetBgColor)
for i in filter(lambda w:isinstance(w,Label), _list):
i.config(fg=textLightColor,bg=textDarkColor)
for i in filter(lambda w:isinstance(w,Checkbutton), _list):
i.config(fg=textLightColor,bg=textDarkColor)
return
def load_project():
global customRules
fname = askopenfilename(filetypes=(("json files", "*.json"),
("All files", "*.*") ))
if fname:
try:
# print("here is %s" % fname)
F=open(fname,"r")
PD=F.read()
PD=eval(PD)
J=json.dumps(PD, sort_keys = True, indent = 4, ensure_ascii=TRUE)
jsonconf.delete("1.0", END)
jsonconf.insert(INSERT, J)
customRules=PD['project']['custom']
workpath.set(PD['project']['workpath'])
pfamily.set(PD['project']['pfamily'])
datapath.set(PD['project']['datapath'])
targetspath.set(PD['project']['targetspath'])
annotation.set(PD['project']['annotation'])
binset.set(PD['project']['binset'])
efiletype.set(PD['project']['efiletype'])
filetype.set(PD['project']['filetype'])
Pipeline.set(PD['project']['pipeline'])
epoc.set(PD['project']['poc'])
eanalyst.set(PD['project']['analyst'])
euser.set(PD['project']['username'])
eflowcell.set(PD['project']['flowcellid'])
eplatform.set(PD['project']['platform'])
epi.set(PD['project']['pi'])
eprojectid.set(PD['project']['id'])
eorganism.set(PD['project']['organism'])
technique.set(PD['project']['technique'])
rPipeline.set(PD['project']['pipeline'])
# rReadlen.set(PD['project']['SJDBOVERHANG'])
# rStrand.set(PD['project']['STRANDED']) ## to check
# rDeg.set(PD['project']['DEG'])
rMincount.set(PD['project']['MINCOUNTGENES'])
rMinsamples.set(PD['project']['MINSAMPLES'])
rReadlens={50:'Read Length is 50',75:'Read Length is 75',100:'Read Length is 100',125:'Read Length is 125',150:'Read Length is 150',250:'Read Length is 250'}
rReadlen.set(rReadlens[int(PD['project']['SJDBOVERHANG'])])
rStrands={0:"0, Reads are Unstranded",1:"1, Reads are from Sense Strand",2:"2, Reads are from Anti-Sense Strand"}
rStrand.set(rStrands[int(PD['project']['STRANDED'])])
rDegs={'no':'no, Do not Report Differentially Expressed Genes','yes':'yes, Report Differentially Expressed Genes'}
rDeg.set(rDegs[PD['project']['DEG']])
# tkinter.messagebox.showinfo(fname,customRules)
F.close()
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
makejson("none")
#MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
return
def set_working_directory():
fname = tkinter.filedialog.askdirectory(initialdir=whereiam,title="Select Working Directory")
workpath.set(fname)
def set_data_directory():
fname = tkinter.filedialog.askdirectory(initialdir=whereiam,title="Select Data Directory")
datapath.set(fname)
def save_project():
try:
fname = asksaveasfilename(filetypes=(("json files", "*.json"),("All files","*.*")),initialdir=workpath.get())
except:
tkinter.messagebox.showinfo("Error","Project not Saved\n Is the working directory set?")
return
if fname:
P=eval(jsonconf.get("1.0",END))
# tkinter.messagebox.showinfo("Json",str(P))
try:
with open(fname, 'w') as F:
json.dump(P, F, sort_keys = True, indent = 4, ensure_ascii=False)
F.close()
tkinter.messagebox.showinfo("Project Write","Project written to %s."% fname)
except Exception as e:
tkinter.messagebox.showerror("Error","Name=%s Error= %s"%(fname,e))
return
def progress():
o=os.popen("cd {0} && snakemake --dryrun --rerun-incomplete > {0}/Reports/checkpoint".format(workpath.get()))
o.close()
F=open("{0}/Reports/checkpoint".format(workpath.get()),"r").read()
rules2={}
rules=re.findall(r'rule .+:',F)
for i in rules:
i=re.sub("rule ","",i)
i=re.sub(":","",i)
rules2[i]=0
F=open("{0}/Reports/{1}.dot".format(workpath.get(),pipelineget()),"r").read()
for i in rules2.keys():
F=re.sub(r'('+i+')(\".+?)\".+?\"',r'\1_pending\2"0.0 0.0 0.0"',F)
# F=re.sub(i,"",F)
G=open("{0}/Reports/{1}-{2}.dot".format(workpath.get(),pipelineget(),"progress"),"w")
G.write(F)
G.close()
o=os.popen("cd {0}/Reports && dot -Tpng -o {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.dot;convert {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.gif".format(workpath.get(),pipelineget()))
# tkinter.messagebox.showerror("o",o)
PL=pipelineget()
gf=Toplevel()
gf.title("CCBR Pipeliner: {0} Progress Graph".format(PL))
cgf = Canvas(gf,bg="white")
# gff=Frame(cgf,width=300,height=300)
xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
xscrollbar.pack(side = BOTTOM, fill=X )
xscrollbar.config(command=cgf.xview)
yscrollbar = Scrollbar(gf,orient=VERTICAL)
yscrollbar.pack(side = RIGHT, fill=Y )
yscrollbar.config(command=cgf.yview)
cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
cgf.config(width=600,height=600)
cgf.pack(expand=1,fill=BOTH,side=RIGHT)
cgf.config(scrollregion=(0,0,1000,5000))
try:
time.sleep(5)
img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(workpath.get(),PL))
except:
time.sleep(5)
img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(workpath.get(),PL))
cgf.create_image(0,0,image=img, anchor="nw")
cgf.image=img
def unbuffered(proc, stream='stdout'):
stream = getattr(proc, stream)
with contextlib.closing(stream):
while True:
out = []
last = stream.read(1)
# Don't loop forever
if last == '' and proc.poll() is not None:
break
while last not in newlines:
# Don't loop forever
if last == '' and proc.poll() is not None:
break
out.append(last)
last = stream.read(1)
out = ''.join(out)
yield out
def makejson(*args):
# print(args[0])
caller=args[0]
global PD
global UnitsBak
global RGbak
D=dict()
try:
F=open(workpath.get()+"/samples","r")
f=F.read().split("\n")
F.close()
for line in f:
L=line.split()
a=L.pop(0)
D[a]=L
samples=D
except:
samples={"na":"na"}
D=dict()
try:
F=open(workpath.get()+"/pairs","r")
f=F.read().split()
F.close()
for i in range(0,len(f),2):
# a=f[i].split(".")[0]
# b=f[i+1].split(".")[0]
a=f[i]
b=f[i+1]
D[a+"+"+b]=[a,b]
pairs=D
except:
pairs={"na":"na"}
D=dict()
try:
F=open(workpath.get()+"/contrasts.tab","r")
# f=F.read().split('\n')
# F.close()
# D["rsamps"]=f[0].split()
# D["rgroups"]=f[1].split()
# D["rcontrasts"]=f[2].split()
# D["rlabels"]=f[3].split()
f=F.readlines()
F.close()
## sampl=[]
## grp=[]
cont=[]
## lbl=[]
for x in f:
if len(x.split()) == 2:
cont.append(x.split()[0])
cont.append(x.split()[1])
D["rcontrasts"]=cont
# contrasts["rcontrasts"]=cont
contrasts=D
except:
contrasts={"rcontrasts":"na"}
## contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
##------
D=dict()
try:
F=open(workpath.get()+"/groups.tab","r")
f=F.readlines()
F.close()
sampl=[]
grp=[]
# cont=[]
lbl=[]
for x in f:
# if len(x.split()) == 4 or len(x.split()) == 3:
if len(x.split()) == 3:
sampl.append(x.split()[0])
grp.append(x.split()[1])
lbl.append(x.split()[2])
D["rsamps"]=sampl
D["rgroups"]=grp
D["rlabels"]=lbl
# D["rcontrasts"]="na"
# contrasts=D
groups=D
except:
# contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
groups={"rsamps":"na","rgroups":"na","rlabels":"na"}
##------
D=dict()
FT=filetype.get()
# p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
p = Popen("find "+workpath.get()+" -maxdepth 1 -type l -printf '%f\n' ", shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
a = p.stdout.read().decode(encoding='UTF-8').split("\n")
RG=dict()
b=a.pop()
# tkinter.messagebox.showerror("",a)
# if freezeunits.get()=="no":
for i in a:
key=re.sub(".realign","",i.split("/")[-1])
key=re.sub(".bai","",key)
key=re.sub(".bam","",key)
key=re.sub(".sam","",key)
key=re.sub(".recal","",key)
key=re.sub(".dedup","",key)
key=re.sub(".sorted","",key)
key=re.sub(".fin","",key)
key=re.sub("\.R[12]","",key)
key=re.sub("_R[12]","",key)
key=re.sub(".fastq","",key)
key=re.sub(".gz","",key)
# key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])
# key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
# key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
D[key]=key
RG[key]={'rgsm':key,'rglb':'na','rgpu':'na','rgpl':'ILLUMINA','rgcn':'na'}
units=D
UnitsBak=D
try:
F=open(workpath.get()+"/rg.tab","r")
f=F.read().splitlines()
F.close()
for theLine in f:
if not re.match("^ID",theLine):
(rgid,rgsm,rglb,rgpl,rgpu,rgcn)=theLine.split("\t")
RG[rgid]={'rgsm':rgsm,'rglb':rglb,'rgpu':rgpu,'rgpl':rgpl,'rgcn':rgcn}
except:
pass
RGbak=RG
# else:
# units=UnitsBak
# RG=RGbak
#
PD=dict()
smparams=[]
for i in range(len(parameters)):
if cp[i].var.get()=="1":
smparams.append(parameters[i])
AD=eval(open(whereiam+"/Pipeliner/"+annotation.get()+".json","r").read())
SD=AD['references']['rnaseq']['STARDIR']
# tkinter.messagebox.showinfo("initLock","SD={0}".format(SD))
PD={'project':{'pfamily':pfamily.get(),'units':units,'samples':samples,'pairs':pairs,'id':eprojectid.get(),'pi':epi.get(),'organism':eorganism.get(),'analyst':eanalyst.get(),'poc':epoc.get(),'pipeline':pipelineget(),'version':"1.0",'annotation':annotation.get(),'datapath':datapath.get(),'targetspath':targetspath.get(),'filetype':filetype.get(), 'binset':binset.get(),'username':euser.get(),'flowcellid':eflowcell.get(),'platform':eplatform.get(),'custom':customRules,'efiletype':efiletype.get(),'workpath':workpath.get(),'batchsize':batchsize,"smparams":smparams,"rgid":RG,"cluster":"cluster_medium.json","description":description.get('1.0',END),"technique":technique.get(),"groups":groups,"contrasts":contrasts,"TRIM":"yes","SJDBOVERHANG":rReadlen.get().split(" ")[3],"STRANDED":rStrand.get().split(",")[0],"DEG":rDeg.get().split(",")[0].lower(),"STARSTRANDCOL":"{0}".format(int(rStrand.get().split(",")[0])+2),"MINSAMPLES":rMinsamples.get(),"MINCOUNTGENES":rMincount.get(),"MINCOUNTJUNCTIONS":rMincount.get(),"MINCOUNTGENEJUNCTIONS":rMincount.get(),"STARDIR": SD+rReadlen.get().split(" ")[3],"PICARDSTRAND":["NONE", "FIRST_READ_TRANSCRIPTION_STRAND","SECOND_READ_TRANSCRIPTION_STRAND"][int(rStrand.get().split(",")[0])]}}
J=json.dumps(PD, sort_keys = True, indent = 4, ensure_ascii=TRUE)
jsonconf.delete("1.0", END)
jsonconf.insert(INSERT, J)
saveproject(jsonconf.get("1.0",END))
# topic=caller
# if re.match(re.compile(".*"+topic+".*"),"refsets,binsets,workpath,datapath,exomeseq,rnaseq,genomeseq,mirseq,custom,chipseq"):
# manpage=os.popen("man -M {0}/Pipeliner/Manpages/ {0}/Pipeliner/Manpages/{1}.1|groff -t -e -man -Tascii|col -bx".format(whereiam,topic)).read()
# mandisplay.delete("1.0", END)
# mandisplay.insert(INSERT, manpage)
# if re.match(re.compile(".*"+topic+".*"),"rnaseq,rtrim,rreadlength,rstrand,rdeg,rcol,rthresh,rmincount"):
# manpage=os.popen("man -M {0}/Pipeliner/Manpages/ {0}/Pipeliner/Manpages/{1}.1|groff -t -e -man -Tascii|col -bx".format(whereiam,topic)).read()
# rmandisplay.delete("1.0", END)
# rmandisplay.insert(INSERT, manpage)
def initialize():
global initLock
if initLock.get()=="unlocked":
pass
else:
if not os.path.isdir(workpath.get()):
# p=os.popen("if [ ! -d {0} ]; then mkdir {0};fi".format(workpath.get()))
#p=os.popen("rm -rf {0}/expression;rm -rf {0}/fastqs;rm -rf {0}/igv;rm -rf {0}/logs;rm -rf {0}/mirdeep2;rm -rf {0}/mirspring;rm -rf {0}/qc;rm -rf {0}/variants;rm -rf {0}/bams;rm -rf {0}/bams-bwa;rm -rf {0}/config;rm -rf {0}/differential*;rm -rf {0}/dir_mapper*;rm -rf {0}/*stats rm -rf {0}/QC;rm -rf {0}/Reports;rm -rf {0}/*dedup_stats; rm {0}/*; rm -rf {0}/.*; mkdir {0}/QC;touch {0}/pairs;touch {0}/samples;cp -rf ".format(workpath.get())+whereiam+"/Pipeliner/Results-template/* {0}".format(workpath.get()))
p=os.popen("mkdir {0};chmod 3770 {0};mkdir {0}/QC;chmod 3770 {0}/QC; touch {0}/pairs;touch {0}/samples;cp -rf ".format(workpath.get())+whereiam+"/Pipeliner/Results-template/* {0}".format(workpath.get()))
return 0
else:
return 1
def initialize_results():
global initLock
# tkinter.messagebox.showinfo("initLock","initLock={0}".format(initLock))
if initLock.get()=="unlocked":
tkinter.messagebox.showinfo("Locked","Initialize button is locked. Uncheck to unlock.")
pass
else:
if initialize()==0:
# result=tkinter.messagebox.showinfo("Initializing Directory","Directory Initialized")
tkinter.messagebox.showinfo("Initializing Directory","Directory Initialized")
else:
tkinter.messagebox.showinfo("Aborted Initializing Directory","Directory Already exists")
# result=tkinter.messagebox.askquestion("Initialize Directory Warning", "Initialize working directory %s? ALL FILES IN THIS DIRECTORY WILL BE DELETED!"%workpath.get(), icon='warning')
# if result=='yes':
# p=os.popen("ls {0}".format(workpath.get())).read()
# result=tkinter.messagebox.askquestion("Initialize Directory Warning", "THESE FILES WILL BE DELETED! Continue? \n {0}".format(p), icon='warning')
# if result=='yes':
# initialize()
# tkinter.messagebox.showinfo("Initializing Directory","Directory Initialized")
# else:
# tkinter.messagebox.showinfo("Aborted Initialing Directory","Directory Not Initialized")
# else:
# tkinter.messagebox.showinfo("Aborted Initializing Directory","Directory Not Initialized")
def symlink(data):
data=data+"/"
data=re.sub("/+$","/",data)
FT=filetype.get()
try:
#cmd="for f in `ls "+data+"*.fastq`;do ln -s $f;done"
# cmd="for f in `ls "+data+"*."+FT+"`;do ln -s $f ../;done"
labelfile=Path(datapath.get()+"/labels.txt")
if labelfile.is_file():
cmd="perl symfiles.pl {0} {1} {2}".format(datapath.get(),datapath.get()+"/labels.txt",workpath.get())
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
Out = p.stdout.read()
else:
cmd="for f in `ls {0}*[\._]{1}`;do ln -s $f {2};done".format(data,FT,workpath.get())
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
Out = p.stdout.read()
except Exception as e:
tkinter.messagebox.showinfo("Error",str(e))
if str(Out).find("No such file")==-1:
tkinter.messagebox.showinfo(FT,"Symlinks Created")
else:
tkinter.messagebox.showinfo("Error","Symlinks Not Created")
if re.sub("bam","",FT):
FT2=re.sub("bam","",FT)
try:
cmd="for f in `ls "+data+"*."+FT2+"bai`;do ln -s $f %s;done"%workpath.get()
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
Out = p.stdout.read()
except Exception as e:
tkinter.messagebox.showinfo("Error",str(e))
if str(Out).find("No such file")==-1:
tkinter.messagebox.showinfo(FT2+"bai","Symlinks Created")
#else:
#tkinter.messagebox.showinfo(FT2+"bai","Index Symlinks Not Created")
p = os.popen("for f in `ls {0}/*fastq*`;do mv $f `echo $f|sed s/_fastq/.fastq/g`;done".format(workpath.get()))
p = os.popen("for f in `ls {0}/*fastq*`;do mv $f `echo $f|sed s/_R1.fastq/.R1.fastq/g`;done".format(workpath.get()))
p = os.popen("for f in `ls {0}/*fastq*`;do mv $f `echo $f|sed s/_R2.fastq/.R2.fastq/g`;done".format(workpath.get()))
makejson("none")
def show(x,y,fg,bg,height,width):
sm=Toplevel()
sm.title(y)
smyscrollbar = Scrollbar(sm, orient=VERTICAL)
smyscrollbar.pack( side = RIGHT, fill=Y )
smxscrollbar = Scrollbar(sm, orient=HORIZONTAL)
smxscrollbar.pack( side = BOTTOM, fill=X )
smout = Text(sm,width=width,height=height,bg=bg,fg=fg,yscrollcommand = smyscrollbar.set, xscrollcommand = smxscrollbar.set)
# smout = Text(sm,width=100,height=100,bg="gray30",fg="yellow",yscrollcommand = smyscrollbar.set, xscrollcommand = smxscrollbar.set)
smout.insert(INSERT, x)
smout.pack(expand=1,fill=BOTH,side=RIGHT)
smyscrollbar.config(command=smout.yview)
smxscrollbar.config(command=smout.xview)
def makeunitswarm():
S=""
F=open("project.json","r")
config=eval(F.read())
for u in config['project']['units']:
S=S+"module load python/3.5.0; samples=\""+ u + "\"; snakemake -s Snakefile\n"
tkinter.messagebox.showinfo("Swarm",S)
F=open("../"+PL+".swarm","w")
F.write(S)
F.close()
def makepairswarm():
S=""
F=open("project.json","r")
config=eval(F.read())
for u in config['project']['pairs'].values():
S=S+"module load python/3.5.0; samples=\""+ ' '.join(u) + "\"; snakemake -s Snakefile\n"
tkinter.messagebox.showinfo("Swarm",S)
F=open("../"+PL+".swarm","w")
F.write(S)
F.close()
def getrootnames():
D=dict()
a=os.popen("ls ../*.fastq").read().split("\n")
b=a.pop()
for i in a:
D[i.split(".")[0]]=i.split(".")[0]
show(D,"Root Fastq Names to Units","black","white",50,50)
def twocol2pairs():
D=dict()
F=open("../pairs","r")
f=F.read().split()
F.close()
for i in range(0,len(f),2):
a=f[i].split(".")[0]
b=f[i+1].split(".")[0]
D[a+"+"+b]=[a,b]
show(D,"Pairs","black","white",50,50)
def tab2samples():
D=dict()
F=open("../samples","r")
f=F.read().split("\n")
F.close()
try:
for line in f:
L=line.split()
a=L.pop(0)
D[a]=L
except:
pass
show(D,"Samples","black","white",50,50)
def about():
info="""
CCBR Pipeliner
Version 1.0
August 28, 2015
"""
tkinter.messagebox.showinfo("CCBR Pipeliner\nVersion 1.0",info)
def hidew(self):
""""""
self.top.withdraw()
def showw(self):
""""""
self.top.update()
self.top.deiconify()
def jsonform():
return
def saveproject(proj):
P=eval(proj)
try:
# with open('project.json', 'w') as F:
with open(uhome+'/project.json', 'w') as F:
json.dump(P, F, sort_keys = True, indent = 4, ensure_ascii=False)
F.close()
# tkinter.messagebox.showinfo("Project Json Write","Project Json file written.")
except:
tkinter.messagebox.showerror("Error","Project Json file not written.")
def viewreport():
PL=pipelineget()
try:
webbrowser.open(workpath.get()+'/Reports/'+PL+'.html')
except Exception as e:
tkinter.messagebox.showinfo("View Report",str(e))
def getworkflow():
PL=pipelineget()
gf=Toplevel()
#MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
gf.title("CCBR Pipeliner: "+ PL + " Workflow Graph")
cgf = Canvas(gf,bg="white")
# gff=Frame(cgf,width=300,height=300)
xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
xscrollbar.pack(side = BOTTOM, fill=X )
xscrollbar.config(command=cgf.xview)
yscrollbar = Scrollbar(gf,orient=VERTICAL)
yscrollbar.pack(side = RIGHT, fill=Y )
yscrollbar.config(command=cgf.yview)
cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
cgf.config(width=600,height=600)
cgf.pack(expand=1,fill=BOTH,side=RIGHT)
cgf.config(scrollregion=(0,0,5000,20000))
img = PhotoImage(file=workpath.get()+"/Reports/"+PL+".gif")
cgf.create_image(0,0,image=img, anchor="nw")
cgf.image=img
def cmd(smcommand):
global img
pl=pipelineget()
PL=uhome
# makejson("none")
if checklist()==1:
return
saveproject(jsonconf.get("1.0",END))
#MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
MkaS=os.popen("./makeasnake.py "+PL+" 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
Out=os.popen("cd "+workpath.get()+" && snakemake " + smcommand +" 2>&1").read()
show(Out,"CCBR Pipeliner: "+ pl + " "+smcommand,dryrunFgColor,dryrunBgColor,200,100)
def swarm():
return
def qsub():
return
def custompipe():
global cb
custom=Toplevel(bg=baseColor)
custom.title("Construct Custom Pipeline")
cb=[0 for x in range(len(rules))]
y=0
for i in range(len(rules)):
if i%8==0:
y=y+1
x=0
v=StringVar(value="0")
cb[i] = Checkbutton(custom, text=rules[i],variable=v,bg=baseColor,fg=textLightColor,offvalue="0",onvalue="1")
cb[i].var=v
cb[i].var.trace("w",setrules)
cb[i].grid(row=x,column=y,sticky=W)
x=x+1
custom.update()
custom.deiconify()
def setrules(*args):
global customRules
customRules=[]
for i in range(len(rules)):
if cb[i].var.get()=="1":
# tkinter.messagebox.showinfo(str(i),cb[i].var.get())
customRules.append(rules[i])
makejson("none")
def updateParams(*args):
global batchsize
batchsize=BS.get()
makejson("none")
def setparameters():
global batchsize
global parameters
global cp
#batch size for GVCFs
custom=Toplevel(bg=baseColor)
custom.title("Additional Parameters")
ppar = LabelFrame(custom,text="Additional Pipeline Parameters")
ppar.grid(row=0,column=0,sticky=W,padx=10,pady=10)
ppar.configure(bg=baseColor,fg=textLightColor)
L=Label(ppar,text="Batch size for Combine GVCFs",anchor="ne",bg=widgetBgColor,fg=widgetFgColor)
E = Entry(ppar, bd =2, width=15,bg=entryBgColor,fg=entryFgColor,textvariable=BS)
L.grid(row=1,column=0,sticky=W)
E.grid(row=2,column=0,sticky=W)
BS.trace('w', updateParams)
par = LabelFrame(custom,text="Additional Snakemake Parameters")
par.grid(row=3,column=0,sticky=W,padx=10,pady=10)
par.configure(bg=baseColor,fg=textLightColor)
parameters=["--debug","--notemp","--reason","--forceall","--keep-going"]
plabels=["Run in debug mode","Ignore temp directives in rules","Show reasons for rules","Force execution of all rules","Keep going if non-essential rule fails"]
cp=[0 for x in range(len(parameters))]
y=3
for i in range(len(parameters)):
if i%1==0:
y=y+1
x=0
v=StringVar(value="0")
cp[i] = Checkbutton(par, text=plabels[i],variable=v,bg=baseColor,fg=textLightColor,offvalue="0",onvalue="1")
cp[i].var=v
cp[i].var.trace("w",makejson)
cp[i].grid(row=y,column=x,sticky=W)
x=x+1
custom.update()
custom.deiconify()
def seelog():
sm=Toplevel()
sm.title("Snakemake Log")
smyscrollbar = Scrollbar(sm, orient=VERTICAL)
smyscrollbar.pack( side = RIGHT, fill=Y )
smxscrollbar = Scrollbar(sm, orient=HORIZONTAL)
smxscrollbar.pack( side = BOTTOM, fill=X )
smout = Text(sm,width=80,font=("nimbus mono","10"),height=30,bg=logBgColor, fg=logFgColor,yscrollcommand = smyscrollbar.set, xscrollcommand = smxscrollbar.set)
smout.pack(expand=1,fill=BOTH,side=RIGHT)
smyscrollbar.config(command=smout.yview)
smxscrollbar.config(command=smout.xview)
smout.tag_config('rule',background="orange",foreground="black")
smout.tag_config('input:',background="cyan",foreground="black")
smout.tag_config('output:',background="yellow",foreground="black")
smout.tag_config('Error',background="red",foreground="black")
smout.tag_config('java',background="purple",foreground="black")
smout.tag_config('threads:',background="white",foreground="black")
smout.tag_config('%) done',background="blue",foreground="white")
#smout.insert(INSERT, f)
# sm.pack()
# force drawing of the window
#smout.update_idletasks()
#smout.insert(INSERT,"Starting Snakemake Run "+PL+"\n")
def refreshlog():
F=open(workpath.get()+"/Reports/snakemake.log","r")
f=F.read()
F.close()
smout.delete("1.0", END)
smout.insert(INSERT, f)
for R in ["rule","input:","output:","Error","threads:","%) done"]:
start="1.0"
while 1:
pos=smout.search(R,start,stopindex=END)
if not pos:
break
pos2=re.sub("\.\d+","",pos)+".end"
pos3=re.sub("\.\d+","",pos)+".0"
smout.tag_add(R,pos3,pos2)
start=pos+"+1c"
smout.update_idletasks()
smout.see(END)
refreshlog()
button = Button(sm, text="Update", fg=widgetFgColor,bg=widgetBgColor,command=refreshlog)
button.pack( side = BOTTOM,padx=5)
button.pack( side = TOP,padx=5)
def run():
global snakemakeRun
#PL=pipelineget()
PL=uhome
MkaS=os.popen("./makeasnake.py "+PL+" 2>&1 | tee -a makeasnake.log").read()
tkinter.messagebox.showinfo("Run by Simple Script","Starting Snakemake Run "+PL+"\n")
snakemakeRun=Popen("../run.sh")
seelog()
def runqsub():
global snakemakeRun
global runmode
runmode=1
# PL=pipelineget()
PL=uhome
MkaS=os.popen("./makeasnake.py "+PL+" 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
tkinter.messagebox.showinfo("Qsub","Starting Qsub Snakemake Run "+PL+"\n")
#snakemakeRun=Popen("../qsub.sh")
snakemakeRun=Popen(workpath.get()+"/submit.sh")
#seelog()
def runslurm():
global snakemakeRun
global runmode
runmode=2
pl=pipelineget()
PL=uhome
if checklist()==1:
return
MkaS=os.popen("./makeasnake.py "+PL+" 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
tkinter.messagebox.showinfo("Slurm","Starting Slurm Snakemake Run "+pl+"\n")
#snakemakeRun=Popen("../qsub.sh")
snakemakeRun=Popen(workpath.get()+"/submit_slurm.sh")
#seelog()
def snakemakeoptions():
sm=Toplevel()
sm.title("Snakemake Options")
flags=['--forceall','--touch','--rerun-incomplete']
c = Checkbutton(sm, text="Forceall", variable=FcAl,fg=textLightColor)
c.pack()
c = Checkbutton(sm, text="Rerun Incomplete", fg=textLightColor, variable=ReIn)
c.pack()