-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathChorusNoRef.py
More file actions
746 lines (413 loc) · 19.4 KB
/
ChorusNoRef.py
File metadata and controls
746 lines (413 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
import sys
import argparse
from Choruslib import bwa, bcftools, probecompare, bamdepth, jellyfish, subprocesspath, revcom
import os
from pybedtools import BedTool
from multiprocessing import Pool
import pandas as pd
def main():
args = check_options(get_options())
# jellyfish par
jfsize = '100M'
# ?build bwa index
bwaindexfile = os.path.basename(args.genome)
tmpfolder = args.tmp
bwatestindex = os.path.join(tmpfolder, bwaindexfile+'.sa')
bwaindex = os.path.join(tmpfolder, bwaindexfile)
bwabuild = True
if os.path.isfile(bwatestindex):
bwabuild = False
if bwabuild:
# build bwa index
bwa.bwaindex(args.bwa, args.genome, tmpfolder)
print("bwa index build finished ...")
else:
print("Use", bwatestindex)
sampleinfor = dict()
names = args.names.split(',')
reads1 = args.reads1.split(',')
reads2 = args.reads2.split(',')
cnsfile = os.path.join(args.saved,'_'.join(names)+'_cns_probe.csv')
print(cnsfile)
cnsio = open(cnsfile, 'w')
for i in range(len(names)):
name = names[i]
read1 = reads1[i]
read2 = reads2[i]
bamfile = os.path.join(tmpfolder,name+'.bam')
bcffile = os.path.join(tmpfolder,name+'.bcf')
jffile = os.path.join(tmpfolder,name+'.jf')
cnsprobe = os.path.join(args.saved, name + '_probe.txt')
# new add indel
indelNprobe = os.path.join(args.saved, name + '_indel_probe.txt')
mindepth = os.path.join(tmpfolder, name + '_mindepth.bed')
if name in sampleinfor:
print("error same name:", name)
else:
sampleinfor[name] = dict()
sampleinfor[name]['read1'] = read1
sampleinfor[name]['read2'] = read2
sampleinfor[name]['bamfile'] = bamfile
sampleinfor[name]['bcffile'] = bcffile
sampleinfor[name]['jffile'] = jffile
# sampleinfor[name]['kmerscore'] = kmerscore
#
# sampleinfor[name]['kmerscoreio'] = open(kmerscore, 'w')
sampleinfor[name]['cnsprobe'] = cnsprobe
sampleinfor[name]['cnsprobeio'] = open(cnsprobe, 'w')
# new add indel
sampleinfor[name]['indelNprobelist'] = list()
sampleinfor[name]['indelNprobeio'] = open(indelNprobe, 'w')
sampleinfor[name]['mindepth'] = mindepth
# run bwa mem
bwa.bwamem_paired(bwabin=args.bwa,
samtoolsbin =args.samtools,
reffile=bwaindex,
outfile=bamfile,
inputfile1=read1,
inputfile2=read2,
samplename=name,
threadnumber = args.threads
)
print("bwa mem", name, 'finished')
# get min depth bed file
bamdepth.bamdepthtobed(bamfile=bamfile, outbed=mindepth, mindepth=args.mindepth, minlength=200)
print(mindepth, 'done')
# generate bcf file from bam file
bcftools.bamtobcf(bcfbin=args.bcftools,
reffile=bwaindex,
bamfile=bamfile,
outbcf=bcffile)
print(bcffile, "done")
# generate jf file
jellyfish.makegenerator(filenames=[read1, read2], type='gz', generators='generators')
jellyfish.jfgeneratorscount(jfpath=args.jellyfish, mer=args.length, output=jffile,
generators='generators', threads=args.threads, size='100M')
print(jffile, "done")
probe = BedTool(args.probe).sort()
for name in sampleinfor:
nowprobe = BedTool(sampleinfor[name]['mindepth']).sort()
probe = probe.intersect(nowprobe, wa=True, u=True)
# cnsprobe
for name in sampleinfor:
bcfpool = Pool(args.threads)
bcfrunerlist = list()
consensusprobelist = list()
for i in probe:
probestr = str(i).rstrip()
bcfconsensusruner = bcftools.BcfConsensusRuner(probestr=probestr, bcftoolspath=args.bcftools,
bcffile=sampleinfor[name]['bcffile'],
sample=name
)
bcfrunerlist.append(bcfconsensusruner)
# consensusprobe = bcftools.probestrtoconsensus(bcfconsensusruner)
#
# print(probestr, consensusprobe, sep='\t')
reslist = list()
for res in bcfpool.imap_unordered(bcftools.probestrtoconsensus, bcfrunerlist):
# print(res['probestr'], name, res['consensusprobe'], sep='\t', file=sampleinfor[name]['cnsprobeio'])
if len(res['consensusprobe']) != args.length:
sampleinfor[name]['indelNprobelist'].append(res)
elif 'N' in res['consensusprobe']:
continue
else:
consensusprobelist.append(res['consensusprobe'])
# consensusprobelist.append(res)
reslist.append(res)
bcfpool.close()
consensusprobekmerscore = jellyfish.jfquerylist(jfkmerfile=sampleinfor[name]['jffile'],
jfpath=args.jellyfish,
seqlist=consensusprobelist)
kmerscoredict = dict()
kmerscorelist = list()
for score in consensusprobekmerscore:
# print(score, file=sampleinfor[name]['kmerscoreio'])
(subseq, kmerscore) = score.split(',')
if 'N' not in subseq:
kmerscoredict[subseq] = int(kmerscore)
kmerscorelist.append(int(kmerscore))
maxkmer = pd.Series(kmerscorelist).quantile(0.9)
minkmer = args.minkmer
for consensusprobe in reslist:
probestr = consensusprobe['probestr']
consensusprobeseq = consensusprobe['consensusprobe']
if consensusprobeseq in kmerscoredict:
if kmerscoredict[consensusprobeseq] <= maxkmer:
if kmerscoredict[consensusprobeseq] >= minkmer:
print(probestr, consensusprobeseq, kmerscoredict[consensusprobeseq], sep='\t',
file=sampleinfor[name]['cnsprobeio'])
for name in sampleinfor:
sampleinfor[name]['cnsprobeio'].close()
# sampleinfor[name]['kmerscoreio'].close()
# print(sampleinfor)
for res in sampleinfor[name]['indelNprobelist']:
print(res['probestr'], name, res['consensusprobe'], sep='\t', file=sampleinfor[name]['indelNprobeio'])
sampleinfor[name]['indelNprobeio'].close()
probdict = dict()
for name in sampleinfor:
with open(sampleinfor[name]['cnsprobe']) as inio:
for infor in inio:
infor = infor.rstrip()
inforlist = infor.split('\t')
orgprb = inforlist[3]
if orgprb in probdict:
probdict[orgprb][name] = infor
else:
probdict[orgprb] = dict()
probdict[orgprb][name] = infor
print('chrom', 'start', 'end', 'refseq', ','.join(sampleinfor), 'consensusprobe', 'consensusscore', 'consensussite',
'consensusdiff', sep=',', file=cnsio)
for orgprb in probdict:
sharecount = len(probdict[orgprb])
values_view = probdict[orgprb].values()
value_iterator = iter(values_view)
first_value = next(value_iterator).split('\t')
outinfo = first_value[0:3]
if len(sampleinfor) == sharecount:
# print(sampleinfor, sharecount)
# print(orgprb, len(probdict[orgprb]))
probelist = list()
namelist = list()
namelist.append('refseq')
probelist.append(orgprb)
for name in sampleinfor:
infor = probdict[orgprb][name].split('\t')
speciesprobe = infor[-2]
namelist.append(name)
if len(speciesprobe) == len(orgprb):
probelist.append(speciesprobe)
if len(namelist) == len(probelist):
# print(namelist, probelist)
res = probecompare.getconsensusprobe(probelist)
outinfo.extend(probelist)
print(','.join(outinfo), res['consensusprobe'], res['consensusscore'], res['consensussite'],
res['consensusdiff'], sep=',', file=cnsio)
cnsio.close()
print("finished")
def check_options(parser):
args = parser.parse_args()
if args.bwa:
if not os.path.exists(args.bwa):
print("Can not locate bwa, please input full path of bwa\n")
parser.print_help()
sys.exit(1)
bwaversion = bwa.bwaversion(args.bwa)
if bwaversion == 'None':
print("Can not locate bwa, please input full path of bwa\n")
parser.print_help()
sys.exit(1)
else:
bwapath = subprocesspath.which('bwa')
if bwapath:
bwaversion = bwa.bwaversion(bwapath[0])
if bwaversion == 'None':
print("Can not locate bwa, please input full path of bwa\n")
parser.print_help()
sys.exit(1)
else:
args.bwa = bwapath[0]
else:
print("Can not locate bwa, please input full path of bwa\n")
parser.print_help()
sys.exit(1)
# End check bwa
# Start check jellyfish
if args.jellyfish:
if not os.path.exists(args.jellyfish):
print("Can not locate jellyfish, please input full path of jellyfish\n")
parser.print_help()
sys.exit(1)
jellyfishversion = jellyfish.jfversion(args.jellyfish)
if jellyfishversion == 'None':
print("Can not locate jellyfish, please input full path of jellyfish\n")
parser.print_help()
sys.exit(1)
else:
jellyfishpath = subprocesspath.which('jellyfish')
if jellyfishpath:
jellyfishversion = jellyfish.jfversion(jellyfishpath[0])
if jellyfishversion == 'None':
print("Can not locate jellyfish, please input full path of jellyfish\n")
parser.print_help()
sys.exit(1)
else:
args.jellyfish = jellyfishpath[0]
else:
print("Can not locate jellyfish, please input full path of jellyfish\n")
parser.print_help()
sys.exit(1)
# End check jellyfish
if args.samtools:
if not os.path.exists(args.samtools):
print("Can not locate samtools, please input full path of samtools\n")
parser.print_help()
sys.exit(1)
samtoolsversion = bwa.samtoolsversion(args.samtools)
if samtoolsversion == 'None':
print("Can not locate samtools, please input full path of samtools\n")
parser.print_help()
sys.exit(1)
else:
samtoolspath = subprocesspath.which('samtools')
if samtoolspath:
samtoolsversion = bwa.samtoolsversion(samtoolspath[0])
if samtoolsversion == 'None':
print("Can not locate samtools, please input full path of samtools\n")
parser.print_help()
sys.exit(1)
else:
args.samtools = samtoolspath[0]
else:
print("Can not locate samtools, please input full path of samtools\n")
parser.print_help()
sys.exit(1)
if args.bcftools:
if not os.path.exists(args.bcftools):
print("Can not locate bcftools, please input full path of bcftools\n")
parser.print_help()
sys.exit(1)
bcftoolsversion = bcftools.bcftoolsversion(args.bcftools)
if bcftoolsversion == 'None':
print("Can not locate bcftools, please input full path of bcftools\n")
parser.print_help()
sys.exit(1)
else:
bcftoolspath = subprocesspath.which('bcftools')
if bcftoolspath:
bcftoolsversion = bcftools.bcftoolsversion(bcftoolspath[0])
if bcftoolsversion == 'None':
print("Can not locate bcftools, please input full path of bcftools\n")
parser.print_help()
sys.exit(1)
else:
args.bcftools = bcftoolspath[0]
else:
print("Can not locate bcftools, please input full path of bcftools\n")
parser.print_help()
sys.exit(1)
if not os.path.exists(args.genome):
print("Can not locate genome file, please input genome file.\n")
parser.print_help()
sys.exit(1)
if not os.path.exists(args.probe):
print("Can not locate probe file, please input probe file which generate by Chorus2.\n")
parser.print_help()
sys.exit(1)
names = args.names.split(',')
reads1 = args.reads1.split(',')
reads2 = args.reads2.split(',')
if len(names) != len(reads1):
print("There are %s species (%s) but %s reads1 files (%s)" % (len(names), names, len(reads1), reads1))
if len(names) != len(reads2):
print("There are %s species (%s) but %s reads2 files (%s)" % (len(names), names, len(reads2), reads2))
for read1 in reads1:
# print(read1)
if not os.path.exists(read1):
print("Can not locate %s file.\n", read1)
parser.print_help()
sys.exit(1)
for read2 in reads2:
if not os.path.exists(read2):
print("Can not locate %s file.\n", read2)
parser.print_help()
sys.exit(1)
if os.path.exists(args.saved):
args.saved = os.path.realpath(args.saved)
print("The output folder ",args.saved, " already exists.")
print('''
Press Y to use it for output files. Everything in this folder will be removed.
Press N and set -s/--saved to a different folder:
''')
while True:
char = getch()
if char.lower() in ("y", "n"):
print(char)
if char.lower() == 'n':
sys.exit(1)
break
else:
args.saved = os.path.realpath(args.saved)
os.mkdir(args.saved)
if args.tmp:
tmpfolder = os.path.abspath(args.tmp)
else:
tmpfolder = os.path.abspath(os.path.join(args.saved, './tmp'))
print("tmp",args.tmp, tmpfolder)
args.tmp = tmpfolder
if os.path.exists(tmpfolder):
tmpfolder = os.path.realpath(tmpfolder)
print("The output folder ",tmpfolder, " already exists.")
print('''
Press Y to use it for output files. Everything in this folder will be removed.
Press N and set --tmp to a different folder:
''')
while True:
char = getch()
if char.lower() in ("y", "n"):
print(char)
if char.lower() == 'n':
sys.exit(1)
break
else:
args.tmp = tmpfolder
os.mkdir(tmpfolder)
print("#"*40)
print("bwa version:", args.bwa, bwaversion)
print("jellyfish version:", args.jellyfish, jellyfishversion)
print("samtools version:", args.samtools, samtoolsversion)
print("bcftools version:", args.bcftools, bcftoolsversion)
print("genome file:", args.genome)
print("probe file:", args.probe)
print("out put folder:", args.saved)
for i in range(len(names)):
print(names[i], reads1[i], reads2[i])
return args
def getch():
"""
For yes/no choice
"""
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def get_options():
parser = argparse.ArgumentParser(description="Oligo FISH probe design for no reference genome.", prog='ChorusNoRef',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="Example:\n"
)
parser.add_argument("--version", action='version', version='%(prog)s 2.1' )
parser.add_argument('-j', '--jellyfish', dest='jellyfish', help='The path where Jellyfish software installed')
parser.add_argument('-b', '--bwa', dest='bwa', help='The path where BWA software installed')
parser.add_argument('-c', '--bcftools', dest='bcftools', help='The path where bcftools software installed')
parser.add_argument('-m', '--samtools', dest='samtools', help='The path where samtools software installed')
parser.add_argument('-g', '--genome', dest='genome',
help='Fasta format genome file, should include all sequences from genome', required=True)
parser.add_argument('-s', '--save', dest='saved', help='The output folder for saving results', default='noRefprobes')
parser.add_argument('--tmp', dest='tmp', help='The temporary fold for processing')
parser.add_argument('-p', '--probe', dest='probe',
help='Original probe design by Chorus2 and filtered by ChorusNGSfilter',
required=True)
parser.add_argument('-r1','--reads1',dest='reads1', required=True,
help='read1 of species, example: For one Species only: species_R1.fq; for more than one species: species1_R1.fq,species2_R1.fq ')
parser.add_argument('-r2', '--reads2', dest='reads2', required=True,
help='read1 of species, example: For one Species only: species_R2.fq; for more than one species: species1_R2.fq,species2_R2.fq ')
parser.add_argument('-n', '--names', dest='names', required=True,
help='species name(s), the order must same as r1, r2 ')
parser.add_argument('-t', '--threads', dest='threads', help='Number of threads or CPUs to use. (Default: 1)',
default=1, type=int)
parser.add_argument('--minkmer', default=3, type=int, dest='minkmer', help="Probe min count for illumina reads")
parser.add_argument('-l', '--length', dest='length', help='The probe length. (Default: 45)', default=45, type=int)
parser.add_argument('-d', '--mindepth', dest='mindepth', help='Minimum depth covered by illumina sequences. (Default: 3)', default=3, type=int)
return parser
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.stderr.write("User interrupt\n")
sys.exit(0)
# python /mnt/e/Github/Chorus2/ChorusNoRef.py -g /mnt/e/Data/Ref/Potato/potato_dm_v404_all_pm_un.fasta -p /mnt/e/Data/Solanum/Oligo/potato_dm_v404/potato_dm_v404_all_pm_un_jffilted_pq2575.bed -r1 /mnt/e/Data/Solanum/Solanum_jamesii/SRR5349574_1.fastq.gz,/mnt/e/Data/Solanum/Solanum_etuberosum/SRR5349573_1.fastq.gz -r2 /mnt/e/Data/Solanum/Solanum_jamesii/SRR5349574_2.fastq.gz,/mnt/e/Data/Solanum/Solanum_etuberosum/SRR5349573_2.fastq.gz -n jamesii,etuberosum