-
Notifications
You must be signed in to change notification settings - Fork 0
/
fast_iCLIP_oldCLIPper.py
executable file
·2319 lines (2098 loc) · 88.2 KB
/
fast_iCLIP_oldCLIPper.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 python
import os
import cmath
import math
import sys
import numpy as np
import glob
import subprocess
import re
from matplotlib_venn import venn2
import pandas as pd
from collections import defaultdict
from operator import itemgetter
import matplotlib as mpl
import matplotlib.pyplot as plt
from optparse import OptionParser
def getFastq(infilepath,sampleName):
# Useage: Get the path to a pair of zipped files (either replicates or paired-end reads).
# Input: Path to raw data files ans sample name.
# Output: The path to each read.
read1=infilepath+sampleName+'_R1.fastq'
read2=infilepath+sampleName+'_R2.fastq'
return(read1,read2)
def moveFiles(reads,outfilepath):
# Useage: Copy a list of files of a given destination and updates their path.
# Input: List of files and a new destination directory.
# Output: Updated list of file paths.
try:
for read in reads:
proc = subprocess.Popen(['cp',read,outfilepath], shell=False, stderr=subprocess.PIPE)
proc.communicate()
return changePath(reads,outfilepath)
except:
print "Error with moving files."
def changePath(inpaths,outpath):
# Useage: Change the path of a file.
# Input: List of path for files and new path for all.
# Output: List of new paths.
pathNames=[]
try:
for inpath in inpaths:
head, tail = os.path.split(inpath)
newfilepath=outpath+tail
pathNames = pathNames+[newfilepath]
return pathNames
except:
print "Problem changing file handle."
def changeHandle(reads,newHandle):
# Useage: Change the handle of a file.
# Input: File of type <name>.<handle>
# Output: List of <name>.<new handle>
readNames=[]
try:
for read in reads:
head, tail = os.path.split(read)
newfilepath=head+'/'+tail.split('.')[0]+newHandle
readNames = readNames+[newfilepath]
return readNames
except:
print "Problem changing file handle."
def changePath(inpaths,outpath):
# Useage: Change the path of a file.
# Input: List of path for files and new path for all.
# Output: List of new paths.
pathNames=[]
try:
for inpath in inpaths:
head, tail = os.path.split(inpath)
newfilepath=outpath+tail
pathNames = pathNames+[newfilepath]
return pathNames
except:
print "Problem changing file handle."
def countFiles(unzippedreads):
# Useage: Counts the number of lines in a specified file.
# Input: List of fastq files.
# Output: Prints the line count to standard out.
try:
for read in unzippedreads:
print read
process=subprocess.Popen(['wc','-l',read], shell=False, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print process.communicate()
except:
print "Problem with counting file."
def modifyName(filepath,newTag):
# Useage: Modifies the filepath name.
# Input: File path of format <path>/<name>.fastq and a string to add to the name.
# Output: Returns the modified path of type <old path>_<new modifier>.fastq
try:
head, tail = os.path.split(filepath)
oldname = tail.split('.')[0]
newName = head+"/"+oldname+"_"+newTag
return newName
except:
print "Problem with modifying file name."
def trimReads5p(unzippedreads,n):
# Useage: Trims a specified number of bases from the 5' end of each read.
# Input: List of fastq files.
# Output: List of 5p trimmed files.
trimparam='-f'+str(n)
trimmedReads=[]
print "Performing raw data filtering.."
logOpen.write("Performing 5p trimming...\n")
try:
for inread in unzippedreads:
outread = modifyName(inread,"5ptrimmed.fastq")
# -Q33 indicates Illumina quality score encoding
process=subprocess.Popen(['fastx_trimmer', trimparam, '-Q33', '-i', inread,'-o',outread], shell=False,stderr=subprocess.PIPE)
# Communicate the process so that the function waits to finish before exiting.
process.communicate()
trimmedReads=trimmedReads+[outread]
return trimmedReads
except:
logOpen.write("Problem with 5p trimming.\n")
print "Problem with 5p trimming."
def trimReads3p(unzippedreads,adapter3p):
# Useage: Trims a specified adapter sequence from the 3p end of the reads.
# Input: List of (5' trimmed) fastq files.
# Output: List of 3p trimmed files.
trimparam='-a'+adapter3p
trimmedReads=[]
logOpen.write("Performing 3p trimming...\n")
try:
for inread in unzippedreads:
outread = modifyName(inread,"3ptrimmed.fastq")
# Parameters:
# -n: keep sequences with unknown (N) nucleotides
# -D: DEBUG output
# -l: Discard sequences shorter than N nucleotides
# -i $FASTQ.fastq -o
process=subprocess.Popen(['fastx_clipper', trimparam, '-n', '-l33', '-Q33', '-i', inread,'-o',outread], shell=False,stderr=subprocess.PIPE)
process.communicate()
trimmedReads=trimmedReads+[outread]
return trimmedReads
except:
logOpen.write("Problem with 3p trimming.\n")
print "Problem with 3p trimming."
def qualityFilter(unzippedreads,q,p):
# Useage: Filters reads based upon quality score.
# Input: List of fastq file names as well as the quality paramters p and q.
# Output: List of modified fastq file names.
qualityparam='-q'+str(q)
percentrageparam='-p'+str(p)
filteredReads=[]
logOpen.write("Performing quality filtering...\n")
try:
for inread in unzippedreads:
outread = modifyName(inread,"filter.fastq")
# Parameters:
# q: Minimum quality score to keep.
# p: Minimum percent of bases that must have [-q] quality.
process=subprocess.Popen(['fastq_quality_filter', qualityparam, percentrageparam,'-Q33', '-i', inread,'-o',outread], shell=False,stderr=subprocess.PIPE)
process.communicate()
filteredReads=filteredReads+[outread]
return filteredReads
except:
logOpen.write("Problem with quality filter.\n")
print "Problem with quality filter."
def dupRemoval(unzippedreads):
# Useage: Removes duplicate reads.
# Input: List of fastq file names.
# Output: List of reads in FASTA format.
filteredReads=[]
logOpen.write("Performing duplicate removal...\n")
print "Performing duplicate removal..."
try:
for inread in unzippedreads:
outread = modifyName(inread,"nodupe.fasta")
process=subprocess.Popen(['fastx_collapser','-Q33', '-i', inread,'-o',outread], shell=False,stderr=subprocess.PIPE)
process.communicate()
filteredReads=filteredReads+[outread]
return filteredReads
except:
logOpen.write("Problem with duplicate removal.\n")
print "Problem with duplicate removal."
def fastaTofastq(fastaIN):
# Usage: Convert fasta to fastq
# Input: List of fasta files
# Output: List of fastq files
program = os.getcwd() + '/bin/fasta_to_fastq.pl'
fastqFiles=[]
print "Performing fasta conversion..."
try:
for fasta in fastaIN:
fastqOut = fasta.replace('.fasta', '.fastq')
outfh = open(fastqOut, 'w')
proc = subprocess.Popen(['perl',program,fasta],stdout=outfh)
proc.communicate()
fastqFiles=fastqFiles+[fastqOut]
return fastqFiles
except:
print "Error with fastq file conversion."
def runBowtie(fastqFiles):
# Useage: Short read mapping to reference (hg19).
# Input: Fastq files of replicates (not paired end).
# Output: Path to samfile for each read.
program = 'bowtie2'
mappedReads=[]
unMappedReads=[]
print "Performing Bowtie..."
logOpen.write("Performing Bowtie...\n")
# Parameters
# -m : Suppress all alignments for a particular read or pair if more than <int> reportable alignments exist for it: -m 1
# -v : Alignments may have no more than `V` mismatches: -v2
try:
for infastq in fastqFiles:
print "Input file:"
print infastq
# Process the genome index
if genomeDict[genomeIndex] == 1:
index = os.getcwd() + '/docs/hg19/hg19'
outfile = modifyName(infastq,"mapped.sam")
unmapped = modifyName(infastq,"notMappedToHg19.fastq")
elif genomeDict[genomeIndex] == 2:
index = os.getcwd() + '/docs/jfh1/jfh1'
elif genomeDict[genomeIndex] == 3:
index = os.getcwd() + '/docs/h77/h77'
elif genomeDict[genomeIndex] == 4:
index = os.getcwd() + '/docs/mm9/mm9'
elif genomeDict[genomeIndex] == 5:
index = os.getcwd() + '/docs/repeat/rep'
outfile = modifyName(infastq,"mappedToRepeatRNA.sam")
unmapped = modifyName(infastq,"notMappedToRepeat.fastq")
print 'Genome index:'
print index
print "Output file (mapped):"
print outfile
print "Output file (unmapped)"
print unmapped
proc = subprocess.Popen([program,'-x', index,'-U',infastq,'--un',unmapped,'-S',outfile,'2>>%s'%logFile],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
proc.communicate()
mappedReads = mappedReads + [outfile]
unMappedReads = unMappedReads + [unmapped]
return (mappedReads,unMappedReads)
except:
logOpen.write("Error with Bowtie.\n")
print "Error with Bowtie"
def runSamtools(samfiles):
# Useage: Samfile processing.
# Input: Sam files from Bowtie mapping.
# Output: Duplicate removed, sorted bedFiles.
program = 'samtools'
program2 = 'bamToBed'
outBedFiles=[]
logOpen.write("Performing Samtools...\n")
try:
for samfile in samfiles:
if genomeIndex == 'rep':
# Convert to bamfile
bamfile = samfile.replace('.sam', '.bam')
proc = subprocess.Popen( [program, 'view', '-bS', '-o', bamfile, samfile])
proc.communicate()
# Sort the bamfile and note that samtools sort adds the .bam handle
bamfile_sort = bamfile.replace('.bam', '_sorted')
proc2 = subprocess.Popen( [program, 'sort', bamfile, bamfile_sort])
proc2.communicate()
# Convert to bedFile
bedFile = bamfile_sort.replace('_sorted', '.bed')
outfh = open(bedFile, 'w')
proc3 = subprocess.Popen( [program2,'-i', bamfile_sort+'.bam'],stdout=outfh)
proc3.communicate()
else:
# Convert to bamfile
bamfile = samfile.replace('.sam', '.bam')
proc = subprocess.Popen( [program, 'view', '-bS', '-o', bamfile, samfile])
proc.communicate()
# Sort the bamfile and note that samtools sort adds the .bam handle
bamfile_sort = bamfile.replace('.bam', '_sorted')
proc2 = subprocess.Popen( [program, 'sort', bamfile, bamfile_sort])
proc2.communicate()
# Remove duplicates
bamfile_nodupes = bamfile_sort.replace('_sorted', '_nodupes.bam')
proc3 = subprocess.Popen( [program, 'rmdup','-s', bamfile_sort+'.bam', bamfile_nodupes])
proc3.communicate()
# Convert to bedFile
bedFile = bamfile_nodupes.replace('_nodupes.bam', '_nodupes.bed')
outfh = open(bedFile, 'w')
proc4 = subprocess.Popen( [program2,'-i', bamfile_nodupes],stdout=outfh)
proc4.communicate()
outBedFiles=outBedFiles+[bedFile]
return outBedFiles
except:
logOpen.write("Error with Samtools.\n")
print "Error with Samtools"
def seperateStrands(mappedReads):
# Useage: Seperate positive and negative strands.
# Input: Paths to two bed files from Samtools.
# Output: Paths to bed files isolated by strand.
logOpen.write("Performing isolation of reads by strand...\n")
try:
# Create list for storing file names
negativeStrand=[]
positiveStrand=[]
# For each file in the input list
for mapFile in mappedReads:
# Open the file
with open(mapFile, 'r') as infile:
# Create new file handles
neg_strand=modifyName(mapFile,'neg.bed')
pos_strand=modifyName(mapFile,'pos.bed')
# Open new files
neg = open(neg_strand, 'w')
pos = open(pos_strand, 'w')
negativeStrand=negativeStrand+[neg_strand]
positiveStrand=positiveStrand+[pos_strand]
# Read one line at the time to memory, and write to outputs.
for line in infile:
# Sort read based upon strand, which is field six (index=5)
if str(line.strip().split('\t')[5]) == '-':
neg.write(line)
elif str(line.strip().split('\t')[5]) == '+':
pos.write(line)
return (negativeStrand,positiveStrand)
except:
logOpen.write("Error with seperating strands.\n")
print "Error with seperating strands."
def modifyNegativeStrand(negativeStrandReads):
# Useage: For negative stranded reads, ensure 5' position (RT stop) is listed first.
# Input: Bed file paths to all negative stranded.
# Output: Paths to modified bed files.
logOpen.write("Modifying the negative strand reads.\n")
negativeStrandEdit=[]
try:
# For each file in the input list
for negativeRead in negativeStrandReads:
# Outpit file name
neg_strand_edited = modifyName(negativeRead,'edit.bed')
negativeStrandEdit=negativeStrandEdit+[neg_strand_edited]
# Open new files
neg_edit = open(neg_strand_edited, 'w')
with open(negativeRead, 'r') as infile:
for line in infile:
chrom,start,end,name,quality,strand=line.strip().split('\t')
# For negative stranded reads, invert so that 5' position is listed first (3' position is an arbitrary 30 bases beyond)
neg_edit.write('\t' .join((chrom,end,str(int(end)+30),name,quality,strand,'\n')))
return negativeStrandEdit
except:
logOpen.write("Error with correcting the negative strand.\n")
print "Error with correcting the negative strand."
def isolate5prime(strandedReads):
# Useage: Isolate only the Chr, 5' position (RT stop), and strand.
# Input: Bed file paths to strand seperated reads.
# Output: Paths to 5' isolated reads.
logOpen.write("Isolating RT stops.\n")
try:
# For each file in the input list
RTstops=[]
for reads in strandedReads:
# Outpit file name
RTstop = modifyName(reads,'RTstop.bed')
# Open new files
f = open(RTstop, 'w')
with open(reads, 'r') as infile:
RTstops=RTstops+[RTstop]
for line in infile:
chrom,start,end,name,quality,strand=line.strip().split('\t')
f.write('\t' .join((chrom,start,strand,'\n')))
return RTstops
except:
logOpen.write("Error with isolating RT stops.\n")
print "Error with isolating RT stop."
def mergeRT(RTstops,outfilename,threshold):
# Useage: Merge RT stops between replicates.
# Input: Paths to RT stop files (stranded reads) and output filename.
# Output: Nothing (outfile name is specified in input)
logOpen.write("Merging RT stops.\n")
try:
# Create object for storing dictionaries
store=[0,0]
# Flag for storing each dictionary
i=0
# Iterare through each file in input
for RT in RTstops:
# Create a dictionary with each value initialized to zero
d = defaultdict(int)
# Open the file
with open(RT, 'r') as infile:
for line in infile:
if line in d:
d[line] += 1
else:
# Make each RT stop a unique key in the dictionary
d[line] += 1
# Store the dictionary
store[i]=d
i += 1
rt_rep1=[k for k in store[0].iteritems()]
rt_rep2=[k for k in store[1].iteritems()]
# Open output files
f = open(outfilename, 'w')
# Iderate through each RT stop in dictionary 1
for key in store[0]:
# Check if same RT stop is in dictionary 2
name=store[1].get(key,None)
# If so, then the read is preserved in both files
if name:
# *** Get total number of RT stops ***
totalRT = store[0][key] + store[1][key]
# Record old if the count if it exceeds the threshold
if totalRT > threshold:
chrom,start,strand=key.strip().split('\t')
# Make sure the start of the read is greater than 15 bases from end of the chrom
if int(start)>15:
# Create a new read centered +/- 15 bases around the RT stop coordinate
read='\t' .join((chrom,str(int(start)-15),str(int(start)+15),'CLIPread','255',strand,'\n'))
else:
read='\t' .join((chrom,str(int(start)),str(int(start)+15),'CLIPread','255',strand,'\n'))
# Write the read to the output, and repeat for the total number of instances the RT stop appears
f.write(read*(store[0][key]+store[1][key]))
except:
logOpen.write("Error with merging RT stops\n")
print "Error with merging RT stops."
def fileCat(destinationFile,fileList):
# Useage: Concatenate two files.
# Input: Output file path, as well as a list input files.
# Output: Nothing (outfile name is specified in input).
logOpen.write("Concatening files.\n")
try:
f = open(destinationFile, "w")
for tempfile in fileList:
# Read each file into the destrination file
readfile = open(tempfile, "r")
f.write(readfile.read())
readfile.close()
f.close()
except:
logOpen.write("Error with file concatenation.\n")
print "Error with file concatenation."
def runCLIPPER(RTclusterfile):
# Useage: Process the mergedRT file and pass through CLIPper FDR script.
# Input: Merged RT file.
# Output: CLIPper input (.bed) file and output file.
program = 'bedToBam'
genomeFile = os.getcwd()+'/docs/human.hg19.genome'
program2 = 'samtools'
program3 = 'bamToBed'
program4 = 'clipper'
print "Running CLIPper..."
logOpen.write("Running CLIPper...\n")
try:
# Create and open bamfile
bamfile = RTclusterfile.replace('.bed', '.bam')
outfh = open(bamfile, 'w')
proc = subprocess.Popen([program, '-i', RTclusterfile,'-g',genomeFile],stdout=outfh)
proc.communicate()
bamfile_sort = bamfile.replace('.bam', '.srt')
proc2 = subprocess.Popen([program2, 'sort', bamfile, bamfile_sort])
proc2.communicate()
bamfile_sorted=bamfile_sort+'.bam'
mapStats = bamfile_sorted.replace('.srt.bam', '.mapStats.txt')
outfh = open(mapStats, 'w')
proc3 = subprocess.Popen([program2, 'flagstat', bamfile_sorted],stdout=outfh)
proc3.communicate()
proc4 = subprocess.Popen([program2, 'index', bamfile_sorted])
proc4.communicate()
CLIPPERin = bamfile_sorted.replace('.srt.bam', '_CLIPPERin.bed')
outfh = open(CLIPPERin, 'w')
proc5 = subprocess.Popen([program3, '-i', bamfile_sorted],stdout=outfh)
proc5.communicate()
CLIPPERout = CLIPPERin.replace('_CLIPPERin.bed', '_CLIP_clusters')
proc6 = subprocess.Popen([program4, '--bam', bamfile_sorted,'-shg19','--outfile=%s'%CLIPPERout],)
proc6.communicate()
outfh.close()
return (CLIPPERin,CLIPPERout)
except:
logOpen.write("Error with running CLIPper.\n")
print "Error with running CLIPper."
def modCLIPPERout(CLIPPERin,CLIPPERout):
# Usage: Process the CLIPper output and isolate lowFDR reads based upon CLIPper windows.
# Input: .bed file passed into CLIPper and the CLIPper windows file.
# Output: Low FDR reads recovered using the CLIPer windows file, genes per cluster, gene list of CLIPper clusters, and CLIPper windows as .bed.
program = 'intersectBed'
logOpen.write("Processing CLIPper output...\n")
try:
# Output format from CLIPper will be: <same_name>_CLIP_clusters
CLIPperOutBed=CLIPPERout+'.bed'
CLIPpeReadsPerCluster=CLIPPERout+'.readsPerCluster'
CLIPpeGeneList=CLIPPERout+'.geneNames'
# Open new files
f = open(CLIPperOutBed, 'w')
g = open(CLIPpeReadsPerCluster, 'w')
h = open(CLIPpeGeneList, 'w')
with open(CLIPPERout, 'r') as infile:
# For each CLIPper window.
for line in infile:
try:
# Version of CLIPper used here includes a header that cannot be parsed. Handle this.
chrom,start,end,name,stats,strand,start_2,end_2 = line.strip().split('\t')
# Old CLIPPER: Ensembl genes are parsed with <name>_<cluster>_<count>
readPerCluster=name.strip().split('_')[2]
geneName=name.strip().split('_')[0]
# Re-write the CLIPper windows file
f.write('\t' .join((chrom,start,end,name,stats,strand,'\n')))
g.write((readPerCluster+'\n'))
h.write((geneName+'\n'))
except:
logOpen.write("Problem with CLIPper ID. Continue reading windows file...\n")
f.close()
g.close()
h.close()
# File name for low FDR reads
CLIPPERlowFDR = CLIPperOutBed.replace('.bed', '_lowFDRreads.bed')
# Intersect input reads with the CLIPper windows
outfh = open(CLIPPERlowFDR, 'w')
# Note that -u and -wb are mutually exclusive, but enforce strandedness
proc = subprocess.Popen([program,'-a', CLIPPERin, '-b', CLIPperOutBed,'-wb','-s'],stdout=outfh)
proc.communicate()
outfh.close()
return (CLIPPERlowFDR,CLIPpeReadsPerCluster,CLIPpeGeneList,CLIPperOutBed)
except:
logOpen.write("Problem obtaining lowFDR reads.\n")
print "Problem obtaining lowFDR reads."
def compareLists(list1,list2,outname):
# Usage: Compare gene lists and output matches to the file.
# Input: Two gene lists.
# Output: Path file containing the matching genes.
logOpen.write("Comparing gene lists...\n")
try:
# Set comparison, resulting in shared genes
f = open(list1, 'r')
g = open(list2, 'r')
content1 = set(f.readlines())
content2 = set(g.readlines())
commonGenes = content1 & content2
# Write shared genes to an output file
geneCategory=outname.split('.')[1]
outputName=outfilepath+'clipGenes_'+geneCategory
outfh = open(outputName, 'w')
for gene in commonGenes:
outfh.write(gene)
outfh.close()
return outputName
except:
logOpen.write("Problem comparing two sets of genes.\n")
print "Problem comparing two sets of genes."
def getLowFDRGeneTypes(CLIPpeGeneList):
# Usage: Get all genes listed under each type, compare to CLIPer targets.
# Input: .bed file passed into CLIPper and the CLIPper windows file.
# Output: Path to file containing all CLIPper genes of each type.
logOpen.write("Grabbing genes of each type...\n")
# try:
readListByGeneType=[]
# Iterate through all gene types
for geneType in os.listdir(os.getcwd() + '/docs/genes_types'):
# Paths to gene lists and output directory
genepath=os.getcwd() + '/docs/genes_types/' + geneType
# Compare list of lowFDR CLIP gene names and gene names by gene type
lowFDRreadlist=compareLists(CLIPpeGeneList,genepath,geneType)
# Update the list of paths to the resulting files
readListByGeneType=readListByGeneType+[lowFDRreadlist]
return readListByGeneType
def grep(pattern,filein):
# Usage: Open a file and search all lines for a pattern.
# Input: Pattern to search (gene name) and file name.
# Output: List of lines in a file that have the pattern.
r = []
filein_open = open(filein, 'r')
for line in filein_open:
if re.search(pattern,line):
r.append(line)
filein_open.close()
return r
def getLowFDRReadTypes(CLIPPERlowFDR,pathToGeneLists):
# Usage: Given a list of genes, return all reads for the associated genes.
# Input: Gene list and the path to lowFDR read file.
# Output: List of reads assocaited with the given genes.
print "Grabbing low FDR read by gene type..."
logOpen.write("Grabbing low FDR reads... \n")
lowFDRgenelist=[]
try:
for path in pathToGeneLists:
# File path to which low FDR reads of each type will be written
outfile=path+'_LowFDRreads.bed'
# Run file grep
print "Grep all reads for %s"%path
proc = subprocess.Popen('grep -F -f %s %s > %s'%(path,CLIPPERlowFDR,outfile),shell=True) # Run grep
return_code = proc.wait() # Wait for process to finish
lowFDRgenelist=lowFDRgenelist+[outfile]
return lowFDRgenelist
except:
logOpen.write("Problem isolating low FDR reads by type.\n")
print "Problem isolating low FDR reads by type."
def lineCountForLog(infileList,outFileName):
# Usage: Obtain line count for all files in alist.
# Input: File list and output file path.
# Output: Path to count for all files in the input list.
try:
outfh = open(outFileName, 'w')
for infile in infileList:
with open(infile) as fin:
lines = sum(1 for line in fin)
outfh.write(str(infile)+'\t'+str(lines)+'\n')
except:
"Print error with line count"
def lineCount(filename):
# Usage: Get and return line count for a file.
# Input: File
# Outline: Lines
print "Counting lines for ..."
print filename
i=0
with open(filename) as f:
for i,l in enumerate(f):
pass
print "Lines counted:"
print i
return i+1
def cleanBedFile(inBed):
# Usage: Sort and recover only first 6 fields from a bed file.
# Input: BedFile.
# Output: Sorted bedFile with correct number of fields.
program='sortBed'
try:
# Make sure bedfile only has 5 fields
CLIPperOutBed=inBed.replace('.bed','_cleaned.bed')
sortedBed=CLIPperOutBed.replace('_cleaned.bed','_cleaned_sorted.bed')
# Open new files
f = open(CLIPperOutBed, 'w')
with open(inBed, 'r') as infile:
for line in infile:
elementList = line.strip().split('\t')
# Re-write the CLIPper windows file
f.write('\t' .join((elementList[0],elementList[1],elementList[2],elementList[3],elementList[4],elementList[5],'\n')))
f.close()
# Sort the resulting bedFile
outfh = open(sortedBed, 'w')
proc = subprocess.Popen([program, '-i', CLIPperOutBed],stdout=outfh)
proc.communicate()
outfh.close()
return sortedBed
except:
print "Error cleaning file."
def makeBedGraph(lowFDRreads):
# Usage: From a bedFile, generate a bedGraph and bigWig.
# Input: BedFile.
# Output: BedGraph file.
program = 'genomeCoverageBed'
program2 = os.getcwd() + '/bin/bedGraphToBigWig'
# Note include this reference to account for the fact that non-traditional chroms (e.g., chrUn_gl000220) can appear in the data.
# Without this, bedGraph creation will throw an error.
sizesFile = os.getcwd()+'/docs/human.hg19.genome'
sizesFile2 = os.getcwd()+'/docs/hg19.sizes'
try:
cleanBed = cleanBedFile(lowFDRreads)
outname = cleanBed.replace('.bed','.bedgraph')
outname2 = cleanBed.replace('.bed','.bw')
outfh = open(outname, 'w')
proc = subprocess.Popen([program, '-bg','-split','-i',cleanBed,'-g',sizesFile],stdout=outfh)
proc.communicate()
outfh2 = open(outname2, 'w')
proc2 = subprocess.Popen([program2,outname,sizesFile,outname2],stdout=subprocess.PIPE)
proc2.communicate()
return outname
except:
print "Problem making bedGraph."
def makeClusterCenter(windowsFile):
# Usage: Generate a file of cluster centers.
# Input: Raw CLIPper output file.
# Output: File with coordinates for the center of each CLIPper cluster.
try:
cleanBed = cleanBedFile(windowsFile)
centers=cleanBed.replace('.bed','.clusterCenter')
# Open new files
f = open(centers, 'w')
with open(cleanBed, 'r') as infile:
for line in infile:
# Each line from the CLIPper cluster file
elementList = line.strip().split('\t')
# Lower coordinate in order to correct for differences in strand
minCoordinate=min(int(elementList[1]), int(elementList[2]))
diff=abs(int((int(elementList[1])-int(elementList[2]))/2))
# Write the center of each window
f.write(elementList[0] + '\t' + str(minCoordinate+diff) + '\t' + str(minCoordinate+diff+1) + '\n')
f.close()
return centers
except:
print "Problem making the cluster center file."
def getClusterIntensity(bedGraph,centerCoordinates):
# Usage: Generate a matrix of read itensity values around CLIPper cluster center.
# Input: BedGraph and cluster center file.
# Output: Generates a matrix, which is passed into R.
program = os.getcwd() + '/bin/grep_chip-seq_intensity.pl'
program2 = 'wait'
logOpen.write("Generating cluster intensity... \n")
try:
proc = subprocess.Popen(['perl',program, centerCoordinates, bedGraph],)
proc.communicate()
print "Waiting for Cluster Intensity file completion..."
proc2 = subprocess.Popen(program2,shell=True)
proc2.communicate()
except:
logOpen.write("Problem with generating cluster intensity.\n")
print "Problem with get reads around cluster centers."
def makeTab(bedGraph):
program = os.getcwd() + '/bin/bedGraph2tab.pl'
program2 = 'wait'
genesFile = os.getcwd() + '/docs/hg19_ensembl_genes.txt'
sizesFile = os.getcwd() + '/docs/hg19.sizes'
try:
outfile=bedGraph.replace('.bedgraph','.tab')
print "Waiting for Tabfile completion..."
proc = subprocess.Popen(['perl',program,genesFile,sizesFile,bedGraph,outfile],)
proc.communicate()
proc2 = subprocess.Popen(program2,shell=True)
proc2.communicate()
return outfile
except:
logOpen.write("Problem making tab.\n")
print "Problem with making the tab file."
def makeAvgGraph(bedGraph):
# Usage: Generate a matrix of read itensity values across gene body.
# Input: BedGraph.
# Output: Generates two matricies, which are passed into R.
program= os.getcwd() + '/bin/averageGraph_scaled_tab.pl'
program2 = 'wait'
utrFile = os.getcwd() + '/docs/hg19_ensembl_UTR_annotation.txt'
print "Make average graph..."
logOpen.write("Generating average graph... \n")
try:
tabFile=makeTab(bedGraph)
outhandle=tabFile.replace('.tab','_UTRs')
proc = subprocess.Popen(['perl',program,utrFile,tabFile,tabFile,outhandle],)
proc.communicate()
# Perl send this to a background process, so wait for completion before going ahead.
print "Waiting for AverageGraph completion..."
proc2 = subprocess.Popen(program2,shell=True)
proc2.communicate()
except:
logOpen.write("Problem with making average graph.\n")
print "Problem with making average graph."
def extractClusters(geneList,allClusters):
# Usage: Extract a set of CLIPper clusters based on gene name
# Input: Gene list
# Output: Clusters with those genes
try:
# Create the outfile
extractedClusters = geneList+'clusters'
outfh = open(extractedClusters, 'w')
# Iterate through each gene name
namesToQuery = np.genfromtxt(geneList,usecols=(0,),delimiter='\t',dtype='string')
for name in namesToQuery:
# Grep it to the output
store=grep(name.strip(),allClusters)
# If NOT empty, then write to output
if store:
outfh.write(''.join(store))
outfh.close()
return extractedClusters
except:
print "Problem extracting clusters for gene list."
def runBlacklistRegions(mappedReads):
# Usage: Remove blacklisted regions from bedfile following mapping.
# Input: .bed file after mapping (duplicates removed by samtools).
# Output: Bedfile with blacklisted regions removed.
program = 'intersectBed'
blacklistregions = os.getcwd() + '/docs/wgEncodeDukeMapabilityRegionsExcludable.bed'
blackListed=[]
try:
for bedIn in mappedReads:
# File name for low FDR reads
noBlacklist = bedIn.replace('.bed', '_noBlacklist.bed')
# Intersect input reads with the blacklist region, and return those that do not intersect
outfh = open(noBlacklist, 'w')
proc = subprocess.Popen([program, '-a', bedIn, '-b', blacklistregions, '-v'],stdout=outfh)
proc.communicate()
outfh.close()
blackListed=blackListed+[noBlacklist]
return (blackListed)
except:
print "Problem with blacklist."
def runRepeatMask(mappedReads):
# Usage: Remove repeat regions from bedfile following mapping.
# Input: .bed file after mapping (duplicates removed by samtools) and blastlist regions removed.
# Output: Bedfile with repeat regions removed.
program = 'intersectBed'
repeatregions = os.getcwd() + '/docs/repeat_masker.bed'
masked=[]
try:
for bedIn in mappedReads:
# File name for low FDR reads
noRepeat = bedIn.replace('.bed', '_noRepeat.bed')
# Intersect input reads with the repeat region, and return those that do not intersect
outfh = open(noRepeat, 'w')
proc = subprocess.Popen([program, '-a', bedIn, '-b', repeatregions, '-v'],stdout=outfh)
proc.communicate()
outfh.close()
masked=masked+[noRepeat]
return (masked)
except:
print "Problem with repeat masking."
def extractExons(bedIn):
# Usage: Extract all exonic reads from a bedfile
# Input: .bed file
# Output: Exonic bedfile
program = 'intersectBed'
exonsBed = os.getcwd() + '/docs/allExons.bed'
try:
# File name for low FDR reads
exonicReads = bedIn.replace('.bed', '_exons.bed')
# Intersect input reads with the blacklist region, and return those that do not intersect
outfh = open(exonicReads, 'w')
proc = subprocess.Popen([program, '-a', bedIn, '-b', exonsBed],stdout=outfh)
proc.communicate()
outfh.close()
return (exonicReads)
except:
print "Problem with extraction of exonic reads."
def extractIntrons(bedIn):
# Usage: Extract all intronic reads from a bedfile
# Input: .bed file
# Output: Intronic bedfile and all non-intronic reads
program = 'intersectBed'
intronsBed = os.getcwd() + '/docs/allIntrons.bed'
try:
# File name for low FDR reads
intronicReads = bedIn.replace('.bed', '_introns.bed')
nonIntronicReads = bedIn.replace('.bed', '_Notintrons.bed')
# Intersect input reads with the intronic bedFile and return those that intersect
outfh = open(intronicReads, 'w')
# proc = subprocess.Popen([program, '-a', bedIn, '-b', intronsBed, '-wa'],stdout=outfh)
proc = subprocess.Popen([program, '-a', bedIn, '-b', intronsBed,'-u'],stdout=outfh)
proc.communicate()
outfh.close()
# Return all reads that do not intersect
outfh = open(nonIntronicReads, 'w')
# proc = subprocess.Popen([program,'-a', bedIn,'-b', intronsBed,'-wa','-v'],stdout=outfh)
proc = subprocess.Popen([program,'-a', bedIn,'-b', intronsBed,'-v'],stdout=outfh)
proc.communicate()
outfh.close()
# Return file handles
return (intronicReads,nonIntronicReads)
except:
print "Problem with extraction of intronic reads."
def extractUTRs(bedIn):
# Usage: Extract all UTR specific reads from the input file.
# Input: .bed file
# Output: Mutually exclusive partitions of the input file.
program = 'intersectBed'
fivePUTRBed = os.getcwd() + '/docs/5pUTRs_Ensbl_sort_clean_uniq.bed'
threePUTRBed = os.getcwd() + '/docs/3pUTRs_Ensbl_sort_clean_uniq.bed'
cdsBed = os.getcwd() + '/docs/Exons_Ensbl_sort_clean_uniq.bed'
try:
# Extract 5p reads and NOT 5p reads
fivePreads = bedIn.replace('.bed', '_5p.bed')
notFivePreads = bedIn.replace('.bed', '_NOT5p.bed')
outfh = open(fivePreads, 'w')
proc = subprocess.Popen([program, '-a', bedIn, '-b', fivePUTRBed,'-u','-s'],stdout=outfh)
proc.communicate()
outfh.close()
outfh = open(notFivePreads, 'w')
proc = subprocess.Popen([program, '-a', bedIn, '-b', fivePUTRBed,'-v','-s'],stdout=outfh)
proc.communicate()
outfh.close()
# Extract 3p UTR reads and NOT 3pUTR
threePreads = bedIn.replace('.bed', '_3p.bed')
notThreePreads = bedIn.replace('.bed', '_NOT3p.bed')
outfh = open(threePreads, 'w')
proc = subprocess.Popen([program, '-a', notFivePreads, '-b', threePUTRBed,'-u','-s'],stdout=outfh)
proc.communicate()
outfh.close()
outfh = open(notThreePreads, 'w')
proc = subprocess.Popen([program, '-a', notFivePreads, '-b', threePUTRBed,'-v','-s'],stdout=outfh)
proc.communicate()
# Extract CDS reads and NOT CDS reads
CDSreads = bedIn.replace('.bed', '_cds.bed')
notCDSreads = bedIn.replace('.bed', '_NOTcds.bed')
outfh = open(CDSreads, 'w')
proc = subprocess.Popen([program, '-a', notThreePreads, '-b', cdsBed,'-u','-s'],stdout=outfh)
proc.communicate()
outfh.close()
outfh = open(notCDSreads, 'w')
proc = subprocess.Popen([program, '-a', notThreePreads, '-b', cdsBed,'-v','-s'],stdout=outfh)
proc.communicate()
outfh.close()
outfh.close()
return (fivePreads,notFivePreads,CDSreads,notCDSreads,threePreads,notThreePreads)
except:
print "Problem with extraction of UTR reads."
def sortCLIPClusters(CLIPPERclusters):
# Usage: From a bedfile of CLIPper clusters, sort them based upon read count
# Input: BedFile
# Output: Sorted bedFile
try:
# Name and open the output file
sortedClusters = CLIPPERclusters.replace('.bed','_sortedClusters.bed')
# Open file for reading and writing (if file does not exist, it will create one.)
outfh = open(sortedClusters, 'w+')
# Process the output file
with open(CLIPPERclusters, 'r') as infile: