/
make_contig_cov_file.py
544 lines (390 loc) · 13.5 KB
/
make_contig_cov_file.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
#!/usr/bin/python
#PYTHON SCRIPT
#written by: Richard Wolfe
#
#to run type: python convert_velvet_to_ida_output.py -i <inputfile> -o <outputfile>
# or: ./convert_velvet_to_ida_output.py -i <inputfile> -o <outputfile>
#
# if error: /usr/bin/python^M: bad interpreter: No such file or directory
# -there is a windows endl after shebang
# -open in vi
# once in vi type:
# :set ff=unix<return>
# :x<return>
#
# -s scaffold file
# -o output file
# -b bowtie sam file (Optional if not supplied then reads and cov will be 0)
#
#
#
#
# make a contig coverage file
# reads length gc cov
# scaffold_0 295348 478516 60.72 61.7217
# scaffold_1 255602 369697 60.48 69.1382
# scaffold_8 182939 338702 61.2 54.0118
# scaffold_4 205429 300854 61.33 68.282
# scaffold_2 156721 291172 60.16 53.8242
# scaffold_5 182272 280216 60.76 65.047
#
import sys #for exit command and maxint
import argparse #to get command line args
#needed to install argparse module because using python 2.6
#and argparse comes with python 2.7
# sudo easy_install argparse
def make_cov_table():
ids = []
genome_len = []
filtrate = []
F02 = []
F08 = []
pellet = []
import glob #for * in file name
dir_files = glob.glob('contig_cov_*') #put all files in this directory in a list
if len(dir_files) == 0:
print ("Error ... No contig_cov_ files in this directory")
sys.exit(1)
for item in dir_files:
print item
#extract id and sample from file name
#id = item.replace("contig_cov_","")
id = item.replace(".txt", "")
id = id.replace("contig_cov_Pellet_", "")
id = id.replace("contig_cov_F02_", "")
id = id.replace("contig_cov_F08_", "")
id = id.replace("contig_cov_filtrate_", "")
print id
if id not in ids:
ids.append(id)
filtrate.append(0.0)
F02.append(0.0)
F08.append(0.0)
pellet.append(0.0)
genome_len.append(0)
f = open(item, "rU")
line = f.readline()
#reads = 0
bp_mapped = 0
bp_scaffolds = 0
while line:
avg_read_len = 0.0
if float(line.split()[1]) != 0:
avg_read_len = (float(line.split()[4]) * float(line.split()[2])) / float(line.split()[1])
bp_mapped = bp_mapped + int(avg_read_len * float(line.split()[1]))
bp_scaffolds = bp_scaffolds + int(line.split()[2])
line = f.readline()
print "bp_mapped = ",bp_mapped
print "bp_scaffolds = ",bp_scaffolds
#percent_mapped = 0.0
avg_cov = float(bp_mapped) / float(bp_scaffolds)
print "avg_cov = ", avg_cov
index = ids.index(id)
genome_len[index] = bp_scaffolds
if item.startswith("contig_cov_Pellet_"):
#sample = "Pellet"
#percent_mapped = reads / pellet_reads
pellet[index] = avg_cov
elif item.startswith("contig_cov_F02_"):
#sample = "F02"
#percent_mapped = reads / F02_reads
F02[index] = avg_cov
elif item.startswith("contig_cov_F08_"):
#sample = "F08"
#percent_mapped = reads / F08_reads
F08[index] = avg_cov
elif item.startswith("contig_cov_filtrate_"):
#sample = "Filtrate"
#percent_mapped = reads / filtrate_reads
filtrate[index] = avg_cov
else:
print "Error... No sample name"
sys.exit(1)
#read the file and get number of reads that mapped
#sys.exit()
#print the table
out_file = open(args.make_cov_table,"w")
out_file.write("File\tGenome_length\tFiltrate\tF02\tF08\tPellet\n")
i = 0
while i < len(ids):
out_file.write(ids[i] + "\t" + str(genome_len[i]) + "\t" + str(filtrate[i]) + "\t" + str(F02[i]) + "\t" + str(F08[i]) + "\t" + str(pellet[i]) + "\n")
i += 1
print ""
print "Number of contig_cov_ files in directory = ",len(dir_files)
print ""
print "Script finished..."
sys.exit(0)
def make_table():
#go through all contig_cov files in the dir and make a table
#
# ex filename: contig_cov_F08_BACT33.fa.txt
#
# Filtrate F02 F08 Pellet
# Bact33.fa value value ...
# ...
# value = reads mapped/filtrate reads
filtrate_reads = 89488910.0
F02_reads = 295029380.0
F08_reads = 73814516.0
pellet_reads = 82116428.0
ids = []
filtrate = []
F02 = []
F08 = []
pellet = []
import glob #for * in file name
dir_files = glob.glob('contig_cov_*') #put all files in this directory in a list
if len(dir_files) == 0:
print ("Error ... No contig_cov_ files in this directory")
sys.exit(1)
for item in dir_files:
print item
#extract id and sample from file name
#id = item.replace("contig_cov_","")
id = item.replace(".txt", "")
id = id.replace("contig_cov_Pellet_", "")
id = id.replace("contig_cov_F02_", "")
id = id.replace("contig_cov_F08_", "")
id = id.replace("contig_cov_filtrate_", "")
print id
sample = ""
if id not in ids:
ids.append(id)
filtrate.append(0.0)
F02.append(0.0)
F08.append(0.0)
pellet.append(0.0)
f = open(item, "rU")
line = f.readline()
reads = 0
while line:
reads = reads + int(line.split()[1])
line = f.readline()
print "reads = ",reads
percent_mapped = 0.0
index = ids.index(id)
if item.startswith("contig_cov_Pellet_"):
#sample = "Pellet"
#percent_mapped = reads / pellet_reads
pellet[index] = reads / pellet_reads
elif item.startswith("contig_cov_F02_"):
#sample = "F02"
#percent_mapped = reads / F02_reads
F02[index] = reads / F02_reads
elif item.startswith("contig_cov_F08_"):
#sample = "F08"
#percent_mapped = reads / F08_reads
F08[index] = reads / F08_reads
elif item.startswith("contig_cov_filtrate_"):
#sample = "Filtrate"
#percent_mapped = reads / filtrate_reads
filtrate[index] = reads / filtrate_reads
else:
print "Error... No sample name"
sys.exit(1)
#print sample
print "percent = ",percent_mapped
#read the file and get number of reads that mapped
#sys.exit()
#print the table
out_file = open(args.make_table,"w")
out_file.write("File\tFiltrate\tF02\tF08\tPellet\n")
i = 0
while i < len(ids):
out_file.write(ids[i] + "\t" + str(filtrate[i]) + "\t" + str(F02[i]) + "\t" + str(F08[i]) + "\t" + str(pellet[i]) + "\n")
i += 1
print ""
print "Number of contig_cov_ files in directory = ",len(dir_files)
print ""
print "Script finished..."
sys.exit(0)
#create an argument parser object
#description will be printed when help is used
parser = argparse.ArgumentParser(description='A script to ')
#add the available arguments -h and --help are aqdded by default
#if the input file does not exist then program will exit
#if output file does not exit it will be created
# args.input is the input file Note: cant write to this file because read only
# args.output is the output file
# args.m is the minimum seq length
parser.add_argument('-s', '--scaffold_file', type=argparse.FileType('rU'), help='scaffold file name') #,required=True)
parser.add_argument('-o', '--output', type=argparse.FileType('w'), help='Output file name') #, required=True)
parser.add_argument('-b', '--sam_file', type=argparse.FileType('rU'), help='bowtie sam file name')
parser.add_argument('--make_table', help='file name to make of a table from all contig_cov files in current directory')
parser.add_argument('--make_cov_table', help='file name to make of a table from all contig_cov files in current directory')
#get the args
args = parser.parse_args()
if args.make_cov_table:
make_cov_table()
if args.scaffold_file == None or args.output == None or args.sam_file == None: #if 1 of these args not supplied
if args.make_table == None:
print "You must supply -s and -o and -b or just --make_table"
sys.exit(1)
if args.make_table:
if args.scaffold_file or args.output or args.sam_file:
print "Error .. you can only use --make_table with no other arguments"
sys.exit(1)
else:
make_table()
#Test print the args
#print args
#arg test
#if args.sam_file != "NONE":
# if not os.path.isfile(args.sam_file):
# print ("-b is not a file or NONE")
# sys.exit(0)
input_lines = 0
input_sequences = 0
output_lines = 0
output_sequences = 0
sam_lines = 0
sam_header_lines = 0
sam_data_lines = 0
reads_not_mapped = 0
reads_mapped = 0
scaffold = 0
ids = [] #a list of tupples
reads = []
reads_bp_count = []
#lengths = []
#gc_content = []
#coverage = []
#read first line should be header line starts with ">"
line = args.scaffold_file.readline()
print "Reading scaffold file"
#if the file is not empty keep reading one at a time
while line:
sequence = ""
header = ""
input_lines += 1
line = line.rstrip() #remove whitespace at end includung endl
header = line
input_sequences += 1
#read sequence
line = args.scaffold_file.readline()
line = line.rstrip() #remove whitespace at end includung endl
while line:
#if line starts with > it is the header line for next sequence
if line.startswith('>'): #">" in line:
break #break out of this while loop
else: #this is the seq
input_lines += 1
line = line.rstrip() #remove whitespace at end includung endl
sequence = sequence + line
#read another line
line = args.scaffold_file.readline()
#the seq is found
#get id from header
header = header.replace(">","") #replace the >
header = header.split()[0] #get first word
reads.append(0)
reads_bp_count.append(0)
#calculate gc content
cg = 0.0
for char in sequence:
if char == "C" or char == "c" or char == "G" or char == "g":
cg += 1.0
cg = cg / len(sequence) * 100.0 #will be %
cg = '%.3f'%(cg) #only 3 places after decimal and rounds
tup = (header,cg,len(sequence))
ids.append(tup)
#close the file
args.scaffold_file.close()
print "Sorting scaffold file ... number of scaffolds = ",len(ids)
#sort the tuples on id Ex:scaffold_1 ....
#new_list = sorted(ids, key=lambda item: item[0]) #sort on first item in tuple - returns a new list
ids.sort(key=lambda item: item[0]) #sort on first item in tuple - sort in place
#test print the tuples
#i = 0
#for item in ids:
# if i < 200:
# print item
# i += 1
#sys.exit()
mapped_sam = [] #list of tuples
#if sam file then go through and get reads and coverage
if args.sam_file:
print "Starting to read SAM file"
line = args.sam_file.readline()
while line:
line = line.rstrip() #remove endline
sam_lines += 1
#print progress
if sam_lines % 1000000 == 0:
print "Reading SAM file line ",sam_lines
#break #test on 1st million lines
if line.startswith("@"): #this is a header line
sam_header_lines += 1
line = args.sam_file.readline()
continue
#process the data line
sam_data_lines += 1
cols = line.split()
id = cols[2]
if int(cols[1]) & 4: #flag bit 4 is on
reads_not_mapped += 1
else:
reads_mapped += 1
#read_length = len(cols[9])
#index = ids.index(id)
#index = ids_dict[id]
#reads[index] += 1
#reads_bp_count[index] = reads_bp_count[index] + read_length
tup = (id, len(cols[9]))
mapped_sam.append(tup)
line = args.sam_file.readline()
print "Sorting sam file ... number of reads that mapped = ",len(mapped_sam)
#sort the tuples on id Ex:scaffold_1 ....
#new_mapped = sorted(mapped_sam, key=lambda item: item[0]) #sort on first item in tuple - returns new list
mapped_sam.sort(key=lambda item: item[0]) #sort on first item in tuple - sort in place
#test print 1st 200 tuples
#i = 0
#for item in mapped_sam:
# print item
# if i > 200:
# break
# i += 1
#because both are sorted we can go through each list 1 time
print "Getting number of reads and number of basepairs that mapped"
ids_index = 0
for item in mapped_sam:
#if item[0] != "scaffold_0":
# break
while item[0] != ids[ids_index][0]: #update the index
ids_index += 1
read_len = item[1]
reads_bp_count[ids_index] = reads_bp_count[ids_index] + read_len
reads[ids_index] += 1
#############################################################
#print results to output file
# make a contig coverage file
# reads length gc cov
# scaffold_0 186656 77408 46.47 241.133
# scaffold_1 141225 63744 50 221.55
# scaffold_2 120809 54525 55.11 221.566
# scaffold_13 109246 48685 48.23 224.394
# scaffold_3 91634 46485 49.93 197.126
# scaffold_4 94311 44893 48.15 210.08
# scaffold_59 102236 42712 48.54 239.361
print "Printing results to output file"
i = 0
while i < len(ids):
args.output.write(ids[i][0] + "\t" + str(reads[i]) + "\t" + str(ids[i][2]) + "\t" + str(ids[i][1]) + "\t")
cov = reads_bp_count[i] * 1.0 / ids[i][2] # * 1.0 to make a double
args.output.write(str(cov) + "\n")
output_sequences += 1
i += 1
args.output.close()
print ""
print "Lines read from scaffold file = ", input_lines
print "Sequences in scaffold file = ", input_sequences
print "Sequences written to output file = ", output_sequences
print ""
print "Lines in sam file = ",sam_lines
print "Header lines in sam file = ", sam_header_lines
print "Data lines = read lines in sam file = ", sam_data_lines
print ""
print "Reads that did not map = ",reads_not_mapped
print "Reads that mapped = ", reads_mapped
print ""
print "Script finished..."