-
Notifications
You must be signed in to change notification settings - Fork 47
/
pipeline.py
executable file
·2731 lines (1931 loc) · 94.4 KB
/
pipeline.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/python
#pipeline.py
'''
The MIT License (MIT)
Copyright (c) 2013 Charles Lin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
#module of functions/code/structures from the myc project that has now been
#addapted for general use
from utils import *
import time
import re
#the master data table
#everything starts with this
#format is as follows
#FILE_PATH UNIQUE_ID NAME BACKGROUND ENRICHED_REGION ENRICHED_MACS COLOR
#FILE_PATH = FOLDER WHERE THE BAM FILE LIVES
#UNIQUE_ID = TONY UNIQUE ID
#GENOME = GENOME USED. MM9, HG18 ARE SUPPORTED
#NAME = IDENTIFIER OF THE DATASET NEEDS TO BE UNIQUE
#BACKGROUND = NAME OF THE BACKGROUND DATASET
#ENRICHED_REGION = NAME OF THE ERROR MODEL ENRICHED REGION OUTPUT
#ENRICHED_MACS = NAME OF THE MACS PEAKS BED FILE
#COLOR = COMMA SEPARATED RGB CODE
#==========================================================================
#===================FORMATTING FOLDERS=====================================
#==========================================================================
def formatFolder(folderName,create=False):
'''
makes sure a folder exists and if not makes it
returns a bool for folder
'''
if folderName[-1] != '/':
folderName +='/'
try:
foo = os.listdir(folderName)
return folderName
except OSError:
print('folder %s does not exist' % (folderName))
if create:
os.system('mkdir %s' % (folderName))
return folderName
else:
return False
#==========================================================================
#===================FORMATTING THE MASTER DATA TABLE=======================
#==========================================================================
def formatDataTable(dataFile):
'''
formats the dataFile and rewrites.
first 3 columns are required for every line.
if they aren't there the line is deleted
'''
print('reformatting data table')
dataTable = parseTable(dataFile,'\t')
newDataTable = [['FILE_PATH','UNIQUE_ID','GENOME','NAME','BACKGROUND','ENRICHED_REGION','ENRICHED_MACS','COLOR']]
#first check to make sure the table is formatted correctly
for line in dataTable[1:]:
if len(line) < 3:
continue
#check if it at least has the first 3 columns filled in
if len(line[0]) == 0 or len(line[1]) == 0 or len(line[2]) == 0:
print('ERROR required fields missing in line')
print(line)
#if the first three are filled in, check to make sure there are 8 columns
else:
if len(line) > 3 and len(line) < 8:
newLine = line + (8-len(line))*['']
newDataTable.append(newLine)
elif len(line) >= 8:
newLine = line[0:8]
newDataTable.append(newLine)
#lower case all of the genomes
#make the color 0,0,0 for blank lines and strip out any " marks
for i in range(1,len(newDataTable)):
newDataTable[i][2] = lower(newDataTable[i][2])
color = newDataTable[i][7]
if len(color) == 0:
newDataTable[i][7] = '0,0,0'
unParseTable(newDataTable,dataFile,'\t')
return newDataTable
#==========================================================================
#===================LOADING THE MASTER DATA TABLE==========================
#==========================================================================
def loadDataTable(dataFile):
if type(dataFile) == str:
dataTable = parseTable(dataFile,'\t')
else:
dataTable = list(dataFile)
#first check to make sure the table is formatted correctly
for line in dataTable:
#print(line)
if len(line) != 8:
print('this line did not pass')
print(line)
dataTable = formatDataTable(dataFile)
break
dataDict = {}
for line in dataTable[1:]:
dataDict[line[3]] = {}
dataDict[line[3]]['folder'] = line[0]
dataDict[line[3]]['uniqueID'] = line[1]
dataDict[line[3]]['genome']=upper(line[2])
genome = line[2]
dataDict[line[3]]['bam'] = line[0]+line[1]+'.'+genome+'.bwt.sorted.bam'
dataDict[line[3]]['sam'] = line[0]+line[1]+'.'+genome+'.bwt.sam'
dataDict[line[3]]['ylf'] = line[0]+line[1]+'.'+genome+'.bwt.ylf'
dataDict[line[3]]['enriched'] = line[5]
dataDict[line[3]]['background'] = line[4]
dataDict[line[3]]['enrichedMacs'] = line[6]
dataDict[line[3]]['color'] = line[7]
return dataDict
#==========================================================================
#===================LOADING THE MASTER DATA TABLE==========================
#==========================================================================
def summary(dataFile,outputFile=''):
'''
gives a summary of the data and its completeness
'''
dataDict = loadDataTable(dataFile)
dataList = dataDict.keys()
dataList.sort()
output= []
for name in dataList:
uniqueID = dataDict[name]['uniqueID']
cmd = 'perl /nfs/young_ata/scripts/getTONY_info.pl -i %s -f 2' % (uniqueID)
tonyQuery = os.popen(cmd)
tonyName = tonyQuery.read().rstrip()
print('dataset name\t%s\tcorresponds to tony name\t%s' % (name,tonyName))
output.append('dataset name\t%s\tcorresponds to tony name\t%s' % (name,tonyName))
#for each dataset
for name in dataList:
#check for the bam
try:
bam = open(dataDict[name]['bam'],'r')
hasBam = True
except IOError:
hasBam = False
#check for ylf
try:
ylf = open(dataDict[name]['ylf'],'r')
hasYlf = True
except IOError:
hasYlf = False
if hasBam == False:
print('No .bam file for %s' % (name))
output.append('No .bam file for %s' % (name))
if hasYlf == False:
print('No .ylf file for %s' % (name))
output.append('No .ylf file for %s' % (name))
if outputFile:
unParseTable(output,outputFile,'')
#mapping the data
#==========================================================================
#===================CALLING BOWTIE TO MAP DATA=============================
#==========================================================================
def callBowtie(dataFile,dataList = [],overwrite = False):
'''
calls bowtie for the dataset names specified. if blank, calls everything
'''
dataDict = loadDataTable(dataFile)
if len(dataList) == 0:
dataList = dataDict.keys()
for name in dataList:
#make sure the output folder exists
try:
foo = os.listdir(dataDict[name]['folder'])
except OSError:
print('no output folder %s for dataset %s. Creating directory %s now.' % (dataDict[name]['folder'],name,dataDict[name]['folder']))
os.system('mkdir %s' % (dataDict[name]['folder']))
if upper(dataDict[name]['genome']) == 'HG18' or upper(dataDict[name]['genome']) == 'MM8':
cmd = 'perl /nfs/young_ata/scripts/generateSAM_file.pl -R -G -c 4 -B -i %s -o %s' % (dataDict[name]['uniqueID'],dataDict[name]['folder'])
elif upper(dataDict[name]['genome']) == 'RN5':
cmd = 'perl /nfs/young_ata/CYL_code/generateSam_rat.pl -R -c 4 -B -i %s -o %s' % (dataDict[name]['uniqueID'],dataDict[name]['folder'])
else:
cmd = 'perl /nfs/young_ata/scripts/generateSAM_file.pl -R -c 4 -B -i %s -o %s' % (dataDict[name]['uniqueID'],dataDict[name]['folder'])
#first check if the bam exists
if overwrite:
print(cmd)
os.system(cmd)
else:
try:
foo = open(dataDict[name]['bam'],'r')
print('BAM file already exists for %s. OVERWRITE = FALSE' % (name))
except IOError:
print('no bam file found for %s, mapping now' % (name))
print(cmd)
os.system(cmd)
#==========================================================================
#===================GETTING MAPPING STATS==================================
#==========================================================================
def bowtieStats(dataFile,namesList=[]):
'''
gets stats from the bowtie out file for each bam
does not assume bowtie output format is always the same
'''
dataDict = loadDataTable(dataFile)
print('DATASET\t\tSEED LENGTH\tTOTAL READS (MILLIONS)\tALIGNED\tFAILED\tMULTI')
if len(namesList) == 0:
namesList= dataDict.keys()
for name in namesList:
readLength,readCount,alignedReads,failedReads,multiReads = False,False,False,False,False
bowtieOutFile = dataDict[name]['folder'] + dataDict[name]['uniqueID']+ '.bowtie.output'
try:
bowtieOut = open(bowtieOutFile,'r')
except IOError:
print('NO BOWTIE OUTPUT FOR %s' % (name))
continue
for line in bowtieOut:
#get the read length
if line[0] == '':
continue
if line[0:4] == 'File':
readLength = line.split('=')[1][1:-1]
if line[0] == '#' and line.count('reads') == 1:
if line.count('processed') == 1:
readCount = line.split(':')[1][1:-1]
readCount = round(float(readCount)/1000000,2)
if line.count('reported alignment') == 1:
alignedReads = line[-9:-1]
if line.count('failed') == 1:
failedReads = line[-9:-1]
if line.count('suppressed') == 1:
multiReads = line[-9:-1]
if readLength and readCount and alignedReads and failedReads and multiReads:
print('%s\t\t%s\t%s\t%s\t%s\t%s' % (name,readLength,readCount,alignedReads,failedReads,multiReads))
else:
print('%s\tNO DATA AVAILABLE' % (name))
#==========================================================================
#===================MERGE BAMS=============================================
#==========================================================================
def mergeBams(dataFile,mergedName,namesList,color='',background =''):
'''
merges a set of bams and adds an entry to the dataFile
'''
dataDict = loadDataTable(dataFile)
#make an .sh file to call the merging
bamFolder = dataDict[namesList[0]]['folder']
genome = lower(dataDict[namesList[0]]['genome'])
if color == '':
color = dataDict[namesList[0]]['color']
if background == '':
background = dataDict[namesList[0]]['background']
if bamFolder[-1] != '/':
bamFolder+='/'
mergedFullPath = bamFolder+mergedName +'.'+genome+'.bwt.sorted.bam'
mergeShFile = open(mergedFullPath+'.sh','w')
mergeShFile.write('cd %s\n' % (bamFolder))
cmd1 = 'samtools merge %s ' % mergedFullPath
for name in namesList:
cmd1+= ' %s' % (dataDict[name]['bam'])
mergeShFile.write(cmd1+'\n')
cmd2 = 'samtools sort %s %s' % (mergedFullPath,bamFolder+mergedName+'.'+genome+'.bwt.sorted')
mergeShFile.write(cmd2+'\n')
cmd3 = 'samtools index %s' % (mergedFullPath)
mergeShFile.write(cmd3+'\n')
mergeShFile.close()
runCmd = "bsub -o /dev/null 'bash %s'" % (mergedFullPath+'.sh')
os.system(runCmd)
dataTable = parseTable(dataFile,'\t')
dataTable.append([bamFolder,mergedName,genome,mergedName,background,'','',color])
unParseTable(dataTable,dataFile,'\t')
formatDataTable(dataFile)
#==========================================================================
#===================CALLING MACS ==========================================
#==========================================================================
def callMacs(dataFile,macsFolder,namesList = [],overwrite=False,pvalue='1e-9'):
'''
calls the macs error model
'''
dataDict = loadDataTable(dataFile)
if macsFolder[-1] != '/':
macsFolder+='/'
formatFolder(macsFolder,True)
#if no names are given, process all the data
if len(namesList) == 0:
namesList = dataDict.keys()
for name in namesList:
#skip if a background set
if upper(dataDict[name]['background']) == 'NONE':
continue
#check for the bam
try:
bam = open(dataDict[name]['bam'],'r')
hasBam = True
except IOError:
hasBam = False
#check for background
try:
backgroundName = dataDict[name]['background']
backbroundBam = open(dataDict[backgroundName]['bam'],'r')
hasBackground = True
except IOError:
hasBackground = False
if not hasBam:
print('no bam found for %s. macs not called' % (name))
continue
if not hasBackground:
print('no background bam %s found for dataset %s. macs not called' % (backgroundName,name))
continue
#make a new folder for every dataset
outdir = macsFolder+name
#print(outdir)
try:
foo = os.listdir(outdir)
if not overwrite:
print('MACS output already exists for %s. OVERWRITE = FALSE' % (name))
continue
except OSError:
os.system('mkdir %s' % (outdir))
os.chdir(outdir)
genome = dataDict[name]['genome']
#print('USING %s FOR THE GENOME' % genome)
bamFile = dataDict[name]['bam']
backgroundName = dataDict[name]['background']
backgroundBamFile = dataDict[backgroundName]['bam']
if upper(genome[0:2]) == 'HG':
cmd = "bsub -o /dev/null -R 'rusage[mem=2200]' 'macs14 -t %s -c %s -f BAM -g hs -n %s -p %s -w -S --space=50'" % (bamFile,backgroundBamFile,name,pvalue)
elif upper(genome[0:2]) == 'MM':
cmd = "bsub -o /dev/null -R 'rusage[mem=2200]' 'macs14 -t %s -c %s -f BAM -g mm -n %s -p %s -w -S --space=50'" % (bamFile,backgroundBamFile,name,pvalue)
elif upper(genome[0:2]) == 'RN':
cmd = "bsub -o /dev/null -R 'rusage[mem=2200]' 'macs14 -t %s -c %s -f BAM -g 2000000000 -n %s -p %s -w -S --space=50'" % (bamFile,backgroundBamFile,name,pvalue)
print(cmd)
os.system(cmd)
#==========================================================================
#===================FORMAT MACS OUTPUT=====================================
#==========================================================================
def formatMacsOutput(dataFile,macsFolder,macsEnrichedFolder,wiggleFolder,wigLink=True):
dataDict = loadDataTable(dataFile)
if macsFolder[-1] != '/':
macsFolder+='/'
if macsEnrichedFolder[-1] != '/':
macsEnrichedFolder+='/'
#make an output directory for the macsEnriched
formatFolder(macsEnrichedFolder,True)
#make an output directory for the wiggles
formatFolder(wiggleFolder,True)
namesList = dataDict.keys()
namesList.sort()
dataTable = parseTable(dataFile,'\t')
if wigLink:
genome = lower(dataDict[namesList[0]]['genome'])
cellType = lower(namesList[0].split('_')[0])
wigLinkFolder = '/lab/solexa_young/bam/wiggles/%s/%s' % (genome,cellType)
formatFolder(wigLinkFolder,True)
newDataTable = [dataTable[0]]
dataTableRows = [line[3] for line in dataTable]
for name in namesList:
outwiggleFileName = '%s%s_treat_afterfiting_all.wig.gz' % (wiggleFolder,name)
#find the row in the old dataTable
print('looking for macs output for %s' % (name))
i = dataTableRows.index(name)
#skip if a background set
if upper(dataDict[name]['background']) == 'NONE':
newLine = list(dataTable[i])
newLine[6] = 'NONE'
newDataTable.append(newLine)
continue
#check to see if the wiggle exists in the correct folder
try:
outwiggle = open('%s%s_treat_afterfiting_all.wig.gz' % (wiggleFolder,name),'r')
outwiggle.close()
except IOError:
#move the wiggle and add the itemrgb line
if dataDict[name]['color'] == '0,0,0':
print('moving wiggle for %s over without changing color' % (name))
cmd = 'mv %s%s/%s_MACS_wiggle/treat/%s_treat_afterfiting_all.wig.gz %s' % (macsFolder,name,name,name,outwiggleFileName)
os.system(cmd)
else:
try:
#print(name)
print('for dataset %s going from %s%s/%s_MACS_wiggle/treat/%s_treat_afterfiting_all.wig.gz' % (name,macsFolder,name,name,name))
wiggle = open('%s%s/%s_MACS_wiggle/treat/%s_treat_afterfiting_all.wig.gz' % (macsFolder,name,name,name),'r')
#print(name)
print('and writing to %s%s_treat_afterfiting_all.wig.gz' % (wiggleFolder,name))
outwiggle = open(outwiggleFileName,'w')
print('writing new wiggle with color line for %s' % (name))
header = wiggle.readline().rstrip()
color = dataDict[name]['color']
header = header + ' itemRgb="On" color="%s"' % (color) + '\n'
outwiggle.write(header)
for line in wiggle:
outwiggle.write(line)
outwiggle.close()
wiggle.close()
except IOError:
print('WARNING: NO MACS WIGGLE FOR %s' %(name))
if wigLink:
#time.sleep(10)
print('Creating symlink for dataset %s in %s' % (name,wigLinkFolder))
os.system('cd %s' % (wigLinkFolder))
os.chdir(wigLinkFolder)
print('cd %s' % (wigLinkFolder))
wigLinkFileName = '%s_treat_afterfitting_all.wig.gz' % (name)
print('ln -s %s %s' % (outwiggleFileName,wigLinkFileName))
os.system('ln -s %s %s' % (outwiggleFileName,wigLinkFileName))
#first check if the thing exists
try:
foo = open('%s%s_peaks.bed' % (macsEnrichedFolder,name),'r')
newLine = list(dataTable[i])
newLine[6] = name+'_peaks.bed'
newDataTable.append(newLine)
except IOError:
#move the bedFile of the peaks
try:
foo = open('%s%s/%s_peaks.bed' % (macsFolder,name,name),'r')
cmd = 'mv %s%s/%s_peaks.bed %s' % (macsFolder,name,name,macsEnrichedFolder)
newLine = list(dataTable[i])
newLine[6] = name+'_peaks.bed'
newDataTable.append(newLine)
print(cmd)
os.system(cmd)
except IOError:
print('WARNING: NO MACS OUTPUT FOR %s' %(name))
newLine = list(dataTable[i])
newLine[6] = 'NONE'
newDataTable.append(newLine)
unParseTable(newDataTable,dataFile,'\t')
#==========================================================================
#===================MAKING GFFS OF TSS REGIONS=============================
#==========================================================================
def makeGeneGFFs(annotFile,gffFolder,species='HG18'):
'''
makes a tss gff with the given window size for all genes in the annotation
tss +/-5kb
tss +/-300
body +300/+3000
can work on any genome build given the right annot file
'''
if gffFolder[-1] != '/':
gffFolder+='/'
try:
foo = os.listdir(gffFolder)
print('Directory %s already exists. Using %s to store gff' % (gffFolder,gffFolder))
except OSError:
cmd = 'mkdir %s' % (gffFolder)
print('making directory %s to store gffs' % (gffFolder))
os.system(cmd)
startDict = makeStartDict(annotFile)
geneList = startDict.keys()
tssLoci = []
for gene in geneList:
tssLocus = Locus(startDict[gene]['chr'],startDict[gene]['start'][0]-5000,startDict[gene]['start'][0]+5000,startDict[gene]['sense'],gene)
tssLoci.append(tssLocus)
tssCollection = LocusCollection(tssLoci,500)
tssGFF_5kb = locusCollectionToGFF(tssCollection)
for gene in geneList:
tssLocus = Locus(startDict[gene]['chr'],startDict[gene]['start'][0]-1000,startDict[gene]['start'][0]+1000,startDict[gene]['sense'],gene)
tssLoci.append(tssLocus)
tssCollection = LocusCollection(tssLoci,500)
tssGFF_1kb = locusCollectionToGFF(tssCollection)
tssGFF_300 = []
txnGFF = []
for line in tssGFF_5kb:
gene = line[1]
chrom = startDict[gene]['chr']
start = startDict[gene]['start'][0]
end = startDict[gene]['end'][0]
sense = startDict[gene]['sense']
name = startDict[gene]['name']
tssLine = [chrom,gene,'',start-300,start+300,'',sense,'',gene]
if sense == '+':
txnLine = [chrom,gene,'',start+300,end+3000,'',sense,'',gene]
else:
txnLine = [chrom,gene,'',end-3000,start-300,'',sense,'',gene]
tssGFF_300.append(tssLine)
txnGFF.append(txnLine)
unParseTable(tssGFF_5kb,gffFolder + '%s_TSS_ALL_-5000_+5000.gff' % (species),'\t')
unParseTable(tssGFF_5kb,gffFolder + '%s_TSS_ALL_-1000_+1000.gff' % (species),'\t')
unParseTable(tssGFF_300,gffFolder + '%s_TSS_ALL_-300_+300.gff' % (species),'\t')
unParseTable(txnGFF,gffFolder + '%s_BODY_ALL_+300_+3000.gff' % (species),'\t')
#==========================================================================
#===================MAKING GFFS OF CHROMS==================================
#==========================================================================
def makeChromGFFs(chromLengthFile,gffFolder,chromList = [],genome='HG18',binSize = 100000,singleGFF = True):
'''
makes GFFs of chromosomes, each chrom gets its own gff
'''
formatFolder(gffFolder,True)
chromLengthDict = {}
chromLengthTable = parseTable(chromLengthFile,'\t')
genomesList = uniquify([line[2] for line in chromLengthTable])
for x in genomesList:
chromLengthDict[upper(x)] = {}
for line in chromLengthTable:
chromLengthDict[upper(line[2])][line[0]] = int(line[4])
if len(chromList) ==0:
chromList = chromLengthDict[upper(genome)].keys()
chromList.sort()
masterGFF = []
for chrom in chromList:
if chromLengthDict[upper(genome)].has_key(chrom):
chromGFF = []
ticker = 1
for i in range(1,chromLengthDict[genome][chrom],int(binSize)):
chromGFF.append([chrom,'bin_%s' % (str(ticker)),'',i,i+binSize,'','.','',''])
ticker+=1
if not singleGFF:
unParseTable(chromGFF,gffFolder+'%s_%s_BIN_%s.gff' % (upper(genome),upper(chrom),str(binSize)),'\t')
if singleGFF:
masterGFF+=chromGFF
if singleGFF:
unParseTable(masterGFF,gffFolder+'%s_BIN_%s.gff' % (upper(genome),str(binSize)),'\t')
#==========================================================================
#===================MAKING GFFS OF ENHANCER REGIONS========================
#==========================================================================
def makeEnhancerGFFs(dataFile,gffName,namesList,annotFile,gffFolder,enrichedFolder,window=2000,macs=True):
'''
find all possible enhancers.
enhancers defined as h3k27ac binding sites +/-5kb outside of promoters
we define center of enhancer as the center of the bound region
'''
dataDict = loadDataTable(dataFile)
if enrichedFolder[-1] != '/':
enrichedFolder+='/'
if gffFolder[-1] != '/':
gffFolder+='/'
#nameList = ['H128_H3K27AC','H2171_H3K27AC','MM1S_H3K27AC_DMSO','MM1S_H3K27AC_JQ1','U87_H3K27AC','P493-6_T0_H3K27AC','P493-6_T1_H3K27AC','P493-6_T24_H3K27AC']
#first make the tss collection
tssGFF = makeTSSGFF(annotFile,5000,5000)
tssCollection = gffToLocusCollection(tssGFF)
#make a blank collection to load enhancers into
enhancerCollection = LocusCollection([],500)
#don't allow overlapping enhancers
species = upper(dataDict[namesList[0]]['genome'])
for name in namesList:
print('finding enhancers in %s' % (name))
if macs:
boundCollection = importBoundRegion(enrichedFolder + dataDict[name]['enrichedMacs'],name)
else:
boundCollection = importBoundRegion(enrichedFolder + dataDict[name]['enriched'],name)
for locus in boundCollection.getLoci():
#make sure an overlapping enhancer doesn't already exist
if len(tssCollection.getOverlap(locus,'both')) == 0 and len(enhancerCollection.getOverlap(locus,'both')) == 0:
center = (locus.start()+locus.end())/2
gffLocus = Locus(locus.chr(),center-window,center+window,'.',locus.ID())
enhancerCollection.append(gffLocus)
enhancerGFF = locusCollectionToGFF(enhancerCollection)
print('Found %s enhancers in %s' % (len(enhancerGFF),gffName))
unParseTable(enhancerGFF,gffFolder+'%s_ENHANCERS_%s_-%s_+%s.gff' % (species,gffName,window,window),'\t')
#==========================================================================
#===================MAKING GFFS OF ENRICHED REGIONS========================
#==========================================================================
def makeEnrichedGFFs(dataFile,namesList,gffFolder,enrichedFolder,macs=True,window=0):
'''
make gffs from enriched regions +/- a window
'''
dataDict = loadDataTable(dataFile)
if enrichedFolder[-1] != '/':
enrichedFolder+='/'
if gffFolder[-1] != '/':
gffFolder+='/'
if len(namesList) == 0:
namesList = dataDict.keys()
species = upper(dataDict[namesList[0]]['genome'])
for name in namesList:
print('making enriched region gff in %s' % (name))
if macs:
if len(dataDict[name]['enrichedMacs']) ==0 or dataDict[name]['enrichedMacs'] =='NONE':
continue
boundCollection = importBoundRegion(enrichedFolder + dataDict[name]['enrichedMacs'],name)
else:
if len(dataDict[name]['enriched']) ==0 or dataDict[name]['enriched'] =='NONE':
continue
boundCollection = importBoundRegion(enrichedFolder + dataDict[name]['enriched'],name)
boundLoci = boundCollection.getLoci()
enrichedCollection = LocusCollection([],500)
for locus in boundLoci:
searchLocus = makeSearchLocus(locus,int(window),int(window))
enrichedCollection.append(searchLocus)
enrichedGFF = locusCollectionToGFF(enrichedCollection)
print('Found %s enriched regions in %s' % (len(enrichedGFF),name))
unParseTable(enrichedGFF,gffFolder+'%s_ENRICHED_%s_-%s_+%s.gff' % (species,name,window,window),'\t')
#==========================================================================
#===================MAKING GFFS OF ENRICHED REGIONS========================
#==========================================================================
def makePromoterGFF(dataFile,annotFile,promoterFactor,enrichedFolder,gffFolder,window=0,transcribedGeneFile=''):
'''
uses a promoter associated factor to define promoter regsion. Can include a window to extend promoter regions as well as a transcribed gene list to restrict set of genes
'''
window = int(window)
#loading the dataTable
dataDict = loadDataTable(dataFile)
#finding the promoter factor in the enriched folder
formatFolder(enrichedFolder,True)
formatFolder(gffFolder,True)
#establishing the output filename
genome = dataDict[promoterFactor]['genome']
output = '%s%s_PROMOTER_%s_-%s_+%s.gff' % (gffFolder,upper(genome),promoterFactor,window,window)
#getting the promoter factor
enrichedCollection = importBoundRegion(enrichedFolder + dataDict[promoterFactor]['enrichedMacs'],promoterFactor)
#making the start dict
startDict = makeStartDict(annotFile)
#getting list of transcribed genes
if len(transcribedGeneFile) > 0:
transcribedTable = parseTable(transcribedGeneFile,'\t')
geneList = [line[1] for line in transcribedTable]
else:
geneList = startDict.keys()
#now make collection of all transcribed gene TSSs
tssLoci = []
for geneID in geneList:
tssLocus = Locus(startDict[geneID]['chr'],startDict[geneID]['start'][0],startDict[geneID]['start'][0]+1,'.',geneID)
tssLoci.append(tssLocus)
tssCollection = LocusCollection(tssLoci,50)
#a promoter is a single promoter associated enriched region
#site that overlaps at most 2 unique genes
promoterGFF = []
promoterLoci = enrichedCollection.getLoci()
for locus in promoterLoci:
overlappingTSSLoci = tssCollection.getOverlap(locus,'both')
if len(overlappingTSSLoci) == 0:
continue
else:
geneNames = [startDict[x.ID()]['name'] for x in overlappingTSSLoci]
geneNames = uniquify(geneNames)
if len(geneNames) <= 2:
refseqString = join([x.ID() for x in overlappingTSSLoci],',')
chrom = locus.chr()
start = locus.start()-window
end = locus.end()+window
strand = locus.sense()
promoterGFF.append([chrom,locus.ID(),'',start,end,'',strand,'',refseqString])
unParseTable(promoterGFF,output,'\t')
#==========================================================================
#===================MAP ENRICHED REGIONS TO GFF============================
#==========================================================================
def mapEnrichedToGFF(dataFile,setName,gffList,cellTypeList,enrichedFolder,mappedFolder,macs=True,namesList=[]):
'''
maps enriched regions from a set of cell types to a set of gffs
tries to make a new folder for each gff
'''
dataDict = loadDataTable(dataFile)
formatFolder(enrichedFolder,True)
formatFolder(mappedFolder,True)
for gffFile in gffList:
gffName = gffFile.split('/')[-1].split('.')[0]
print('making enriched regions to %s' % (gffName))
#make the gff into a collection
try:
foo = os.listdir(mappedFolder)
except OSError:
print('making directory %s to hold mapped enriched files' % (mappedFolder))
os.system('mkdir %s' % (mappedFolder))
outdir = mappedFolder+gffName+'/'
try:
foo = os.listdir(mappedFolder+gffName)
except OSError:
os.system('mkdir %s' % (outdir))
#first filter the name list
cellTypeNameList =[]
if len(namesList) == 0:
namesList = dataDict.keys()
for name in namesList:
#check to make sure in the right celltype
#also make sure to not process WCEs
if dataDict[name]['background'] == 'NONE':
continue
cellName = name.split('_')[0]
if macs == True:
if cellTypeList.count(cellName) == 1 and dataDict[name]['enrichedMacs'] != 'NONE':
cellTypeNameList.append(name)
else:
if cellTypeList.count(cellName) == 1 and dataDict[name]['enriched'] != 'NONE':
cellTypeNameList.append(name)
cellTypeNameList.sort()
mappedGFF = [['GFF_LINE','ID'] + cellTypeNameList]
#now we go through the gff and fill in stuff
gffTable = parseTable(gffFile,'\t')
gffLoci = []
#making the header line
for line in gffTable:
gffLocus = Locus(line[0],line[3],line[4],line[6],line[8])
gffLine = gffLocus.__str__()
gffID = line[1]
gffLoci.append(gffLocus)
mappedGFF.append([gffLine,gffID])
for name in cellTypeNameList:
print('dataset %s' % (name))
if macs:
enrichedCollection = importBoundRegion(enrichedFolder + dataDict[name]['enrichedMacs'],name)
else:
enrichedCollection = importBoundRegion(enrichedFolder + dataDict[name]['enriched'],name)
for i in range(len(gffLoci)):
if len(enrichedCollection.getOverlap(gffLoci[i],'both')) > 0:
mappedGFF[i+1].append(1)
else:
mappedGFF[i+1].append(0)
unParseTable(mappedGFF,outdir+gffName+'_'+setName+'.txt','\t')
#==========================================================================
#===================MAPPING BAMS TO GFFS===================================
#==========================================================================
def mapBams(dataFile,cellTypeList,gffList,mappedFolder,nBin = 200,overWrite =False,nameList = []):
'''
for each gff maps all of the data and writes to a specific folder named after the gff
can map either by cell type or by a specific name list
'''
dataDict = loadDataTable(dataFile)
if mappedFolder[-1] != '/':
mappedFolder+='/'
for gffFile in gffList:
#check to make sure gff exists
try:
foo = open(gffFile,'r')
except IOError:
print('ERROR: GFF FILE %s DOES NOT EXIST' % (gffFile))
gffName = gffFile.split('/')[-1].split('.')[0]
#see if the parent directory exists, if not make it
try:
foo = os.listdir(mappedFolder)
except OSError:
print('%s directory not found for mapped bams. making it' % (mappedFolder))