-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathporeFUME.py
1526 lines (1084 loc) · 71.2 KB
/
poreFUME.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
from Bio import SeqIO
import pandas as pd
import logging
import sys
import os
import Bio as bio
import operator
import numpy as np
import pandas as pd
import pickle
import math
import errno
from types import *
from time import sleep
from random import randint
#from shutil import rmtree
import shutil
from shutil import copyfile
from Barcode import Barcode
import argparse
import multiprocessing
from subprocess import Popen, PIPE
logger = logging.getLogger()
def main():
"""
Main function that calls subroutines.
Layout:
Setup command line parser
Setup logging
1a. Call demux()
1b. Call demuxCollect()
2. Call nanocorrect()
3. Call nanopolish()
4. Call annotateCARD()
done
All the steps can be turned on and off using --skipXXX this allows flexible analysis and intermidate exits.
1a Demux
uses the Smith-Waterman implementation which is very slow on this dataset. Relevant parameters are --barcodeEdge , --barcodeThreshold and --match, --mismatch, --gapopen, --gapextend. The returned sequences will be reverse complemented such that the read always starts with the forward primer. The collected reads are stored in mysample.AFTERBC.fasta
2. nanocorrect uses nanocorrect by Loman,Simpson,Quick and is also slow. Relevant parameters are --pathNanocorrect. The collected reads are stored as mysample.AFTERNC1.fasta (first round of nanocorrect) and mysample.AFTERNC2.fasta (second round of nanocorrect without the coverage requirement)
3. nanopolish uses nanopolish by Loman,Simpson,Quick.
4. annotateCARD find high scoring segmens in the result list, which is not extremly fast. --annotateAll will invoke the annotation of the start and intermidiate files (ie. the afterBC and afterNC1 )
This is an example of initial file structure
inputData/
-yourBarcodeData.fasta
-yourNanoporeData.fasta
poreFUME will create
output/
barcode/
yoursample/
{n}.yoursample.afterBC.fasta
etc.
Final results the user is interested in are in output/annotation/xxx where
"""
###
### Setup the command line parser
###
parser = argparse.ArgumentParser()
parser.add_argument("fileONTreads", help="path to FASTA where the (2D) nanopore reads are stored",
type=str)
parser.add_argument("fileBarcodes", help="path to FASTA where the barcodes are stored, format should be ie F_34 for forward and R_34 for reverse barcode",
type=str)
parser.add_argument("--PacBioLegacyBarcode",help="the pacbio_barcodes_paired.fasta file has first digist as 4 instead of 04, turning this option on will fix this",
action="store_true")
parser.add_argument("--verbose",help="switch the logging from INFO to DEBUG",
action="store_true")
parser.add_argument("--overwriteDemux",help="overwrite results in the output/barcode/runid directory if they exist",
action="store_true")
parser.add_argument("--overwriteNanocorrect",help="overwrite the results in the output/nanocorrect/runid directory if the exist",
action="store_true")
parser.add_argument("--overwriteNanopolish",help="overwrite the results in the output/nanopolish/runid directory, if the exist",
action="store_true")
parser.add_argument("--overwriteCARD",help="overwrite the results in the output/annotation/runid directory if the exist",
action="store_true")
parser.add_argument("--skipDemux",help="Skip the barcode demux step and proceed with nanocorrect, cannot be used with overwrite. Assumes the output/barcode/ and output/ directory are populated accordingly",
action="store_true")
parser.add_argument("--skipDemuxCollect",help="will skip the demux it self and go to collection based on the pickle",
action="store_true")
parser.add_argument("--skipNanocorrect",help="Skip the nanocorrect step.",
action="store_true")
parser.add_argument("--skipNanopolish",help="Skip the nanocorrect step.",
action="store_true")
parser.add_argument("--skipCARD",help="Skip the CARD annotation",
action="store_true")
parser.add_argument("--match",help="Score for match in alignment (default: %(default)s)",nargs='?', default=2.7,type=float)
parser.add_argument("--mismatch",help="Score for mis-match in alignment (default: %(default)s)",nargs='?', default=-4.5,type=float)
parser.add_argument("--gapopen",help="Score for gap-open in alignment (default: %(default)s)",nargs='?', default=-4.7,type=float)
parser.add_argument("--gapextend",help="Score for gap-extend in alignment (default: %(default)s)",nargs='?', default=-1.6,type=float)
parser.add_argument("--cores",help="Amount of args.cores to use for multiprocessing (default: %(default)s)",nargs='?', default=1,type=int)
parser.add_argument("--barcodeThreshold",help="Minimum score for a barcode pair to pass (default: %(default)s)",nargs='?', default=58,type=int) #58 was used on the 'lib A set', 54 on porecamp?
parser.add_argument("--barcodeEdge",help="Maximum amount of bp from the edge of a read to look for a barcode. (default: %(default)s)",nargs='?', default=60,type=int) #60 was used on the 'lib A set' , 120 on the lib B since it had a different experimental ligation protocol
parser.add_argument("--pathNanocorrect",help="Set the path to the nanocorrect files (default: %(default)s)",nargs='?', default="/Users/evand/Downloads/testnanocorrect/nanocorrect/",type=str) #make sure it has an extra copy of nanocorrect with a coverage of 0 in it
parser.add_argument("--pathNanopolish",help="Set the path to the nanopolish files (default: %(default)s)",nargs='?', default="/Users/evand/Downloads/nanopolish/nanopolish/",type=str) #location of nanopolish
parser.add_argument("--pathBWA",help="Set the path to BWA (default: %(default)s)",nargs='?', default="/Users/evand/Downloads/nanopolish/bwa",type=str) #location of nanopolish
parser.add_argument("--pathRawreads",help="Set the path to the raw reads (.fast5 files), nanopolish needs this. As a hint, this should be the absolute path to which the last part of the header on the poretools produced fasta file referes to. poreFUME will make a symlink to the directory containing the .fast5 files.",nargs='?', default="inputData/NB6",type=str) #location of fast5 files as refered to in the datafiles created by poreTools. See nanopolish docs for more info
parser.add_argument("--pathCARD",help="Set the path to CARD fasta file (default: %(default)s)",nargs='?', default="inputData/n.fasta.protein.homolog.fasta",type=str)
parser.add_argument("--annotateAll",help="By default only the final (demuxed and two times corrected) dataset is annotated, however by turning on this option all the files, raw, after demux, after 1st round of correction, after 2nd round of correction are annotated. This obviously takes longer.",
action="store_true")
parser.add_argument("--minCoverage",help="sequences will only be nanopolish'ed if they have a coverage that is higher than this threshold. (default: %(default)s)",nargs='?', default=30,type=int) #Jared suggested using at least 30x coverage
args = parser.parse_args()
#baseFileName is used throughout poreFUME to refer to the specific runname
try:
baseFileName = os.path.splitext(os.path.basename(args.fileONTreads))[0]
except:
ValueError('Invalid file name (fileONTreads)')
if not os.path.exists('output'): #it it does not exist
os.makedirs('output') #create it
####################
### Setup logging ##
####################
# create file handler which logs even debug messages
fh = logging.FileHandler('output/' + baseFileName + '.info.log')
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
fh2 = logging.FileHandler('output/' + baseFileName + '.debug.log')
fh2.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh2.setFormatter(formatter)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
if args.verbose: #Switch the root log level
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
logging.basicConfig(stream=sys.stdout, level=loglevel,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[fh,ch])
logging.getLogger('').addHandler(fh)
logging.getLogger('').addHandler(fh2)
##############
#Test inputs #
##############
#check if blast is in the path
if not cmdExists('makeblastdb'):
raise RuntimeError('makeblastdb is not avialable in PATH')
else:
logger.info('makeblastdb found in path')
if not cmdExists('blastn'):
raise RuntimeError('blastn is not avialable in PATH')
else:
logger.info('blastn found in path')
if not cmdExists('poa'):
raise RuntimeError('poa is not avialable in PATH, install http://sourceforge.net/projects/poamsa/')
else:
logger.info('poa found in path')
if not cmdExists('LAcat'):
raise RuntimeError('LAcat is not avialable in PATH, install https://github.com/thegenemyers/DALIGNER and https://github.com/thegenemyers/DAZZ_DB')
else:
logger.info('LAcat found in path')
if not cmdExists('bwa'):
raise RuntimeError('bwa is not avialable in PATH, did you run . env.sh? Check install.sh or install manually from https://github.com/lh3/bwa')
else:
logger.info('bwa found in path')
if not cmdExists('samtools'):
raise RuntimeError('samtools is not avialable in PATH, did you run . env.sh? Check install.sh or install manually from https://github.com/samtools/samtools')
else:
logger.info('samtools found in path')
if not cmdExists('parallel'):
raise RuntimeError('GNU parallel is not avialable, did you install it correctly? Check install.sh or install manually from https://www.gnu.org/software/parallel/')
else:
logger.info('GNU parallel found')
if not os.path.isfile(args.fileONTreads):
raise IOError('fileONTreads does not exist',args.fileONTreads)
if not os.path.isfile(args.fileBarcodes):
raise IOError('fileBarcodes does not exist',args.fileBarcodes)
#Barcode dir
if not os.path.exists(getBarcodeDir(baseFileName)): #it it does not exist
os.makedirs(getBarcodeDir(baseFileName)) #create it
if not args.skipNanocorrect:
if not os.path.exists(args.pathNanocorrect):
raise IOError('the pathNanocorrect is not valid!')
###start putting correct paths inplace
if not args.skipNanocorrect: #Do a check for clean directory now instead of when demux is done
##Direcotry handeling
nanocorrectDir = getNanocorrectDir(baseFileName)
if not os.path.exists(nanocorrectDir): #it it does not exist
os.makedirs(nanocorrectDir) #create it
logger.info(nanocorrectDir + ' did not exist, created it')
else: #it exists
logger.info(nanocorrectDir + ' already exists')
if args.overwriteNanocorrect: #if we are sure to overwrite the existing barcode output
shutil.rmtree(nanocorrectDir)
os.makedirs(nanocorrectDir) #create it
logger.info(nanocorrectDir + ' emptied because of --overwriteNanocorrect flag')
else:
try:
os.rmdir(nanocorrectDir) #remove it
except OSError: #Cannot be removed, because it is not empty
raise RuntimeError('The nanocorrect directory is not empty! Is there a previous run present? --overwriteNanocorrect can be used to proceed', nanocorrectDir)
#TODO: build a flag so this can be overwritten. Smart solution to store these files anyway
logger.info(nanocorrectDir + ' existst but was empty, so proceed')
os.makedirs(nanocorrectDir) #create it
if not args.skipNanopolish: #Do a check for clean directory now instead of when demux is done
if not os.path.exists(args.pathNanopolish):
raise IOError('the pathNanopolish is not valid!')
##Direcotry handeling
nanopolishDir = getNanopolishDir(baseFileName)
if not os.path.exists(nanopolishDir): #it it does not exist
os.makedirs(nanopolishDir) #create it
logger.info(nanopolishDir + ' did not exist, created it')
else: #it exists
logger.info(nanopolishDir + ' already exists')
if args.overwriteNanopolish: #if we are sure to overwrite the existing nanopolish data?
shutil.rmtree(nanopolishDir)
os.makedirs(nanopolishDir) #create it
logger.info(nanopolishDir + ' emptied because of --overwriteNanopolish flag')
else:
try:
os.rmdir(nanopolishDir) #remove it
except OSError: #Cannot be removed, because it is not empty
raise RuntimeError('The nanopolish directory is not empty! Is there a previous run present? --overwriteNanopolish can be used to proceed', nanopolishDir)
#TODO: build a flag so this can be overwritten. Smart solution to store these files anyway
logger.info(nanopolishDir + ' existst but was empty, so proceed')
os.makedirs(nanopolishDir) #create it
if not os.path.exists(args.pathRawreads): #When we run nanopolish we need to have the raw reads defined
raise IOError('the pathRawreads is not valid! This should point to your .fast5 files, see doc.')
if not args.skipCARD: #Do a check for clean directory now instead of when demux is done
##Direcotry handeling
annotationDir = getAnnotationDir(baseFileName)
if not os.path.exists(annotationDir): #it it does not exist
os.makedirs(annotationDir) #create it
logger.info(annotationDir + ' did not exist, created it')
else: #it exists
logger.info(annotationDir + ' already exists')
if args.overwriteCARD: #if we are sure to overwrite the existing barcode output
shutil.rmtree(annotationDir)
os.makedirs(annotationDir) #create it
logger.info(annotationDir + ' emptied because of --overwriteCARD flag')
else:
try:
os.rmdir(annotationDir) #remove it
except OSError: #Cannot be removed, because it is not empty
raise RuntimeError('The CARD annotation directory is not empty! Is there a previous run present? --overwriteCARD can be used to proceed', annotationDir)
#TODO: build a flag so this can be overwritten. Smart solution to store these files anyway
logger.info(annotationDir + ' existst but was empty, so proceed')
os.makedirs(annotationDir) #create it
#####################################
#Call all the relevant sub routines #
#####################################
if not args.skipDemux:
deMux(baseFileName,args)
else:
logger.info('Skip the demux step because of --skipDemux')
if not args.skipDemuxCollect: #a debug hook, skip demux but still use the .p file
deMuxCollect(baseFileName,args)
else:
logger.info('Skip the demuxCollect step because of --skipDemuxCollect')
if not args.skipNanocorrect:
nanocorrect(baseFileName,args)
else:
logger.info('Skip the nanocorrect step because of --skipNanocorrect')
if not args.skipNanopolish:
nanopolish(baseFileName,args)
else:
logger.info('Skip the nanopolish step because of --skipNanopolish')
if not args.skipCARD:
annotateCARD(baseFileName,args)
else:
logger.info('Skip the CARD annotation step because of --skipCARD')
logger.info('poreFUME done')
logging.shutdown()
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
# helper functions start. These are not directly called from main()
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
def getBarcodeDir(baseFileName):
return os.path.join('output','barcode',baseFileName)
def getNanocorrectDir(baseFileName):
return os.path.join('output','nanocorrect',baseFileName)
def getNanocorrectDirABS(baseFileName):
return os.path.join(os.getcwd(),'output','nanocorrect',baseFileName)
def getNanopolishDir(baseFileName):
return os.path.join('output','nanopolish',baseFileName)
def getAnnotationDir(baseFileName):
return os.path.join('output','annotation',baseFileName)
def spawnNanocorrect(thisInput):
"""
The function spawns the nanocorrect pipeline, first the make and then the nanocorrect.py
It takes a range of barcodes as argument that will be procced serially. This function is designed to be called using multiprocess so it can run in parallel.
The round argument will not only decide the name of the interFixInput/Output but also if nanocorrect.py or nanocorrectC0.py is called
Parameters:
dictonary with:
ranger = list of integers that represent that barcode to work on
round = round of nanocorrect we can do two round. so either 1 or 2
"""
#unpack argument list
thisRound = int(thisInput['round'])
thisRange = thisInput['ranger']
baseFileName = thisInput['baseFileName']
pathNanocorrect = thisInput['pathNanocorrect']
logger.debug('Spawned a process with range ' + str(thisRange) + ' for nanocorrect round ' + str(thisRound))
if thisRound==1:
interFixInput = 'afterBC'
interFixOutput = 'afterNC1'
elif thisRound==2:
interFixInput = 'afterNC1'
interFixOutput = 'afterNC2'
else:
raise ValueError('Invalid round number selected, only 1 or 2')
for thisBarcode in thisRange: #Go through each barcode of the range that was passed
logger.debug ('Running one-by-one nanocorrect on barcode ' + str(thisBarcode) + ' in round' +str(thisRound))
#Make sure the input file can be used for error correction
currentInputFile = os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), ".".join([str(thisBarcode),baseFileName,interFixInput,'fasta']) ) #makes output/nanocorrect/samplename/23/23.samplename.a
if not os.path.isfile(currentInputFile): #Check the input fasta, ie the .afterBC. or afterNC1. really exists
logger.warning(currentInputFile + 'does not exist. If this is a .afterNC1. file it can be nanocorrect did not generate output in the first round. Continue with next barcode')
continue
else:
if len(list(SeqIO.parse(open(currentInputFile),"fasta"))) < 1: #Check how many records the start file has
logger.warning(currentInputFile + ' does exist but has no records! If this is a .afterNC1. file it can be nanocorrect did not generate output in the first round. Continue with next barcode')
continue
### RUN MAKE, this will run daligner under the hood to make the alignments (this is fast!)
process = Popen(['make'
,'-f'
,os.path.join(pathNanocorrect,'nanocorrect-overlap.make')
,'INPUT=' + ".".join([str(thisBarcode),baseFileName,interFixInput,'fasta'])
,'NAME=' + str(thisBarcode)
], stdout=PIPE, stderr=PIPE, cwd= os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode)) ) #Set Current Working Directory to the barcode folder, as nanocorrect needs its own folder. This also means that the INPUT argument is relative to cwd and does not need a path
stdout, stderr = process.communicate()
process.wait() #wait till finished
logger.debug(str(stdout))
if stderr:
logger.error('the nanocorrect MAKE file gave the following error while processing barcode: ' + str(thisBarcode) + ' : '+ str(stderr))
logger.debug('Done with nanocorrect make for barcode ' +str(thisBarcode) + ' start nanocorrectX.py' + ' in round' +str(thisRound))
### RUN NANOCORRECT.py #Next step in the nanocorrect pipeline is to run nanocorrect.py itself. This calls poa on each alignment, which is a slow process
if thisRound == 1:
nanocorrectFilename = 'nanocorrect.py' #Has the min_coverage as 3
elif thisRound == 2:
nanocorrectFilename = 'nanocorrectC0.py' #Has the min_coverage as 1
currentOutputFile = os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), ".".join([str(thisBarcode),baseFileName,interFixOutput,'fasta']) ) #makes
correctFastaHandle = open(currentOutputFile, "wb") #Used to store the output
process = Popen(['python'
,os.path.join(pathNanocorrect,nanocorrectFilename) #Executeable of nanocorret.py/nanocorrectC0.py
, str(thisBarcode)
,'all'
], stdout=correctFastaHandle, stderr=PIPE, cwd= os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode)) ) #Set Current Working Directory to the barcode folder, as nanocorrect needs its own folder. This also means that the INPUT argument is relative to cwd and does not need a path
stdout, stderr = process.communicate()
process.wait() #wait till finished
correctFastaHandle.close()
logger.debug(str(stdout))
if stderr:
logger.error('the nanocorrect python script gave the following error while parsing barcode: ' + str(thisBarcode) + '. '+ str(stderr))
#Clean up the nanocorrect files
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), str(thisBarcode) + '.las'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), str(thisBarcode) + '.pp.fasta.fai'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), str(thisBarcode) + '.db'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), str(thisBarcode) + '.pp.fasta'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), '.' + str(thisBarcode) + '.idx'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), '.' + str(thisBarcode) + '.dust.data'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), '.' + str(thisBarcode) + '.dust.anno'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), '.' + str(thisBarcode) + '.bps'))
os.remove(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode), 'HPCcommands.txt'))
logger.debug('Done with nanocorrect for barcode ' + str(thisBarcode) + ' in round' +str(thisRound))
def getJobrange(totalBarcode,cores):
"""
Distribute the barcodes over cores, can be used as range(start[i],end[i])
Returns a (start,end)
Paramters:
totalreads = list of the barcodes to distribute, does not need to be consecutive ie. [1,3,9,12,48]
cores = number of cores to split over ie 2
"""
steps = int(math.ceil(len(totalBarcode)/float(cores)))
start = range(0,len(totalBarcode),steps)
end = [x+steps for x in start]
end[-1] = len(totalBarcode)
return start,end
#from http://biopython.org/wiki/Split_large_file
#to avoid loading everything in memory
def batch_iterator(iterator, batch_size):
"""Returns lists of length batch_size.
This can be used on any iterator, for example to batch up
SeqRecord objects from Bio.SeqIO.parse(...), or to batch
Alignment objects from Bio.AlignIO.parse(...), or simply
lines from a file handle.
This is a generator function, and it returns lists of the
entries from the supplied iterator. Each list will have
batch_size entries, although the final list may be shorter.
"""
entry = True # Make sure we loop once
while entry:
batch = []
while len(batch) < batch_size:
try:
entry = iterator.next()
except StopIteration:
entry = None
if entry is None:
# End of file
break
batch.append(entry)
if batch:
yield batch
def blastDatabase(queryFile,dbFile,args):
"""
Returns a dataframe of a BLAST operation of the queryFile on the dbFile
Parameters:
queryFile = path to file that will be used as query in the BLAST process
dbFile = path to file that will be used as database in the BLAST process
"""
#Create a blast DB http://www.ncbi.nlm.nih.gov/books/NBK279688/
assert type(queryFile) is StringType, "queryFile is not a string: %r" % queryFile
assert type(dbFile) is StringType, "databaseFile is not a string: %r" % dbFile
#Test inputs
if not os.path.isfile(queryFile):
raise IOError('queryFile does not excist',queryFile)
if not os.path.isfile(dbFile):
raise IOError('queryFile does not excist',dbFile)
#Create dbase
logger.info("Start builing blast database")
process = Popen(['makeblastdb', '-in', str(dbFile), '-dbtype', 'nucl'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
process.wait() #wait till finished
logger.info(str(stdout))
if stderr:
logger.error(str(stderr))
#Search with blast
logger.info("Start BLASTing for subsample %s",queryFile)
process = Popen(['blastn','-db',str(dbFile),'-query',str(queryFile),'-max_hsps', '1', '-max_target_seqs', '1000', '-num_threads', str(args.cores), '-outfmt' ,'10','-out','blastn.tmp.output'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
process.wait() #Wait till finished
logger.info(str(stdout))
if stderr:
logger.error(str(stderr))
logger.info("Finished BLASTing for subsample %s",queryFile)
if not os.path.isfile('blastn.tmp.output'):
raise RuntimeError('BLAST did not produce an alignment, one can implement an exception here. But for now stop')
#Read in blast results
dfBlast = None
dfBlast = pd.read_csv('blastn.tmp.output',names=['qseqid' ,'sseqid' ,'pident', 'length', 'mismatch', 'gapopen', 'qstart', 'qend' ,'sstart' ,'send','evalue', 'bitscore']) #load demuxed and corrected Minion dbase blasted by Sanger
#TODO: make blastn baseFileName dependant!
os.remove(str(dbFile) +'.nhr') #cleanup subsample file blastDB
os.remove(str(dbFile) +'.nin') #cleanup subsample file blastDB
os.remove(str(dbFile) +'.nsq') #cleanup subsample file blastDB
os.remove('blastn.tmp.output') #cleanup blast output
return dfBlast
def calcGeneLength(row):
"""
The CARD database contains the position of the subject gene in the header name, this is originally stored in this script in
id2 but split into a subjectGeneSTart and subjectGeneEnd. Based on this we can calculate the original gene length
"""
return abs(int(row['subjectGeneStart'])- int(row['subjectGeneEnd']))
def calcCoverage(row):
"""
We can calculate the coverage of the alignment by dividing the length of the alignemnt over the subjectGeneLength
There is a glitch in the length of the header and the real length of the DNA in the card database, so limit of at 100%
"""
#return (int(row['length'])/ float(row['subjectGeneLength']))*100
return (int(row['length'])/ float(row['subjectGeneLength']))*100 if (int(row['length'])/ float(row['subjectGeneLength']))*100 < 100 else 100
def calcSegments(thisDF):
"""
Calculates the most relevant hit for each segment on the read
Paramters:
thisDF = dataframe with the BLAST result for an INDIVIDUAL query. So don't pass the full BLAST table, but only from 1 qseqid, ie. thisDF[thisDF.qseqid == thisSeqid], where thisSeqid is the current seqid of interest
"""
#from PIL import Image, ImageDraw #For viz purposes
#im = Image.new('RGBA', (6000, 1000), (0, 0, 0, 0)) #initialize a debug drawing screen
#draw = ImageDraw.Draw(im)
thisDF.reset_index(drop=True,inplace=True)
dy = 50 #off set for debug drawing
highscore = [] #Store the coordinates of the visited positions in a [start,end] format
highindex = [] #Store the index number (=blast hit) of each visited position
#for row in thisDF.itertuples(): #go through all the rows of the dataframe, not the most effient way! When this scales up write a new implemetation based on sorting
for index,qstart,qend in zip(thisDF.index.values, thisDF.qstart, thisDF.qend): #this speeds up 5x compared to using iterrows(). However it is still slow. #TODO: make this vectorized if possible
#print row
if len(highscore) == 0: #First hit
highscore.append([qstart,qend]) #Add position to the position list
highindex.append(index) #also keep track of the index
#draw.line((row['qstart'],dy,row['qend'],dy), fill=(255,255,255)) #draw bright
else:
doesOverlap = False
for thisScore in highscore: #Go through all the set positions
if calcOverlap(thisScore[0],thisScore[1],qstart,qend) > 0: #If there is an overlap
#print 'Overlapping, skip'
doesOverlap = True
break #Exit loop, no need to continue
if doesOverlap == False: #We found a new segment
highscore.append([qstart,qend]) #Add position to list
#draw.line((row['qstart'],dy,row['qend'],dy), fill=(255,255,255)) #Draw bright
highindex.append(index)
else: #Old segment
pass
#draw.line((row['qstart'],dy,row['qend'],dy), fill=(55,55,55)) #Draw darker for debugging
#print row['qstart'],row['qend']
dy = dy + 2
#im.save('out.png',"PNG")
#im.show() #show a debug figure
return thisDF.iloc[highindex] #Return a dataframe with the most relevant hit on each segment
def calcOverlap(a,b,c,d):
"""
Returns the overlap between two segments (ab) vs (cd)
Parameters:
a = start position of segment AB
b = end position of segment AB
c = start position of segment CD
d = end position of segment CD
Can be in any direction and any order
"""
return min([max([a,b]), max([c,d])]) - max([min([c,d]), min([a,b])]) #calculate overlap between two segments
def cmdExists(cmd):
return any(
os.access(os.path.join(path, cmd), os.X_OK)
for path in os.environ["PATH"].split(os.pathsep)
)
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
# core functions start. These are directly called from main()
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
def deMux(baseFileName,args):
###########################
##### Barcode Demux module
###########################
"""
STEP 1a
This basically finds the barcodes in the edges of a read using the smith waterman aligner.
Results are retreived in a dataframe of which the barcodes are evaluated to pass a thershold (args.barcodeThreshold)
"""
readcounter = 0
scoreList = [2.7, -4.5, -4.7, -1.6]
scoreList = [args.match,args.mismatch,args.gapopen,args.gapextend]
shortHand = '_'.join([str(mli) for mli in scoreList])
logger.info( 'Start with scoreList: ' + shortHand)
logger.info('Split jobs over %s args.cores', args.cores)
dictBarcode = {}
for record in SeqIO.parse(args.fileBarcodes, "fasta"):
seq = str(record.seq)
if args.PacBioLegacyBarcode:
## This will add a 0 between the first 10 barcodes if it is entered like F_1 instead of F_01
if record.id[-2] =="_": #from 1 to 9
record.id = record.id[0:2] + '0' + record.id[-1]
record.id = record.id[-2:]
if record.id in dictBarcode: #lookup barcode in list
dictBarcode[record.id].append(str(record.seq))
else:
dictBarcode.setdefault(record.id, [])
dictBarcode[record.id].append(str(record.seq))
#PB barcode is 5 padding + 16 barcodesc
logger.info("Using barcode file: %s with %s barcodes",args.fileBarcodes,len(dictBarcode))
logger.info("Using nanopore file: %s ",args.fileONTreads)
logger.info("Runname: %s",baseFileName)
logger.info("argument list: %s", args)
record_iter = SeqIO.parse(open(args.fileONTreads),"fasta") #One generator for the file it self
record_iter2 = SeqIO.parse(open(args.fileONTreads),"fasta") #And one generator to find the length
inputLength = len(list(record_iter2))
if inputLength<args.cores*2: #We run into trouble if there are more cores than sequences, since we get emtpy queues intitially. Since this is not a production run scenario we just stop the script here
raise ValueError('There are less sequence records in the input file than there are cores defined. I guess this is a test run? Increase the amount of sequence in the input file, or lower the number of --cores')
logger.debug("Each thread will have %s records to process", int(math.ceil(float(inputLength)/args.cores)))
#Split fasta files into batches so they can be processed parallel
for i, batch in enumerate(batch_iterator(record_iter, int(math.ceil(float(inputLength)/args.cores)))):
filename = baseFileName+ '.fasta.'+ str(i) +'.tmp'
try:
os.remove(filename)
except OSError:
pass
handle = open(filename, "w")
count = SeqIO.write(batch, handle, "fasta")
handle.close()
barcodeList = [] #Store barcode objects
jobs = [] #Store multiprocessing objects
#Run the barcoding in parallel
for i in range(args.cores):
thisFile = baseFileName+ '.fasta.'+ str(i) +'.tmp'
thisInstance = Barcode(baseFileName,i)
p = multiprocessing.Process(target=thisInstance.splitBarcode, args=(thisFile,dictBarcode, scoreList,args.barcodeEdge))
jobs.append(p)
p.start()
barcodeList.append(thisInstance)
for thisJob in jobs: #Wait till all jobs are done
thisJob.join()
#Finally collect the results from the barcoding in one dataframe
dfCollector = pd.DataFrame()
for i in range(args.cores):
thisFilename = baseFileName + 'dfCollector.p.' + str(i) + '.tmp'
dfthisCollector = pickle.load( open( thisFilename, "rb" ) )
dfCollector = pd.concat([dfCollector,dfthisCollector])
#cleanup
os.remove(baseFileName+ '.fasta.'+ str(i) +'.tmp') #clenup temporary fasta file
os.remove(thisFilename) #clean up temporary pickle file from processes
count = str(len(dfCollector[dfCollector.wasMatch == 1].index))
pickle.dump( dfCollector, open(os.path.join('output', baseFileName + ".afterBC.p"), "wb" ) )
logger.info('Done demuxing, amount of double matches:' + str(len(dfCollector[dfCollector.wasMatch == 1].index)))
logger.info('Start writing demuxed files')
def deMuxCollect(baseFileName,args):
"""
Step 1b. Collect the results from the deMux() step
"""
#Make sure the barcode directory is avialable
barcodeDir = getBarcodeDir(baseFileName)
if not os.path.exists(barcodeDir): #it it does not exist
os.makedirs(barcodeDir) #create it
logger.info(barcodeDir + ' did not exist, created it')
else: #it exists
logger.info(barcodeDir + ' already exists')
if args.overwriteDemux: #if we are sure to overwrite the existing barcode output
shutil.rmtree(barcodeDir)
os.makedirs(barcodeDir) #create it
logger.info(barcodeDir + ' emptied because of --overwriteDemux flag')
else:
try:
os.rmdir(barcodeDir) #remove it
except OSError: #Cannot be removed, because it is not empty
raise RuntimeError('The barcode directory is not empty! Is there a previous run present? --overwriteDemux can be used to proceed', barcodeDir)
#TODO: build a flag so this can be overwritten. Smart solution to store these files anyway
logger.info(barcodeDir + ' existst but was empty, so proceed')
os.makedirs(barcodeDir) #create it
dfCollector = pickle.load( open(os.path.join('output', baseFileName + ".afterBC.p"), "rb" ) )
logger.info("%s amount of reads will be collected" ,dfCollector[(dfCollector[['scoreF','scoreR']].sum(axis=1)>args.barcodeThreshold)][['barcode']].stack().value_counts().sort_index().sum())
counter = 0
for record in SeqIO.parse(args.fileONTreads, "fasta"): #Walk through all the fasta sequences, this way requires a lot of writing IO, can be optimized by going per barcode
logger.debug('Parsing: %s', record.description)
if float(dfCollector[dfCollector.seqID == record.description][['scoreF','scoreR']].sum(axis=1)) > args.barcodeThreshold:
logger.debug('Pass args.barcodeThreshold of ' + str(args.barcodeThreshold))
if str(dfCollector[dfCollector.seqID == record.description]['direction'].item()) == 't':
logger.debug('Strand is in template')
start = int(dfCollector[dfCollector.seqID == record.description]['pos_F_end'])
end = args.barcodeEdge-int(dfCollector[dfCollector.seqID == record.description]['pos_R_begin'])
logger.debug('Forward cutoff:' +str(start) + ', end cutoff: -' + str(end))
record.seq = record.seq[start:-end]
elif str(dfCollector[dfCollector.seqID == record.description]['direction'].item()) == 'c':
logger.debug('Strand is in complement')
#For fun, but should write this in the manual as well we make the strand reverse complement.
record.seq = bio.Seq.reverse_complement(record.seq)
start = int(dfCollector[dfCollector.seqID == record.description]['pos_F_end'])
end = args.barcodeEdge-int(dfCollector[dfCollector.seqID == record.description]['pos_R_begin'])
logger.debug('Forward cutoff:' +str(start) + ', end cutoff: -' + str(end))
record.seq = record.seq[start:-end]
else:
print str(dfCollector[dfCollector.seqID == record.description].direction.item())
logger.error('Direction should be t or c')
raise ValueError('Direction should be t or c')
#open up directory
#TODO: need to empty barcode files first!
handle = open( os.path.join(getBarcodeDir(baseFileName),str(int(dfCollector[dfCollector.seqID == record.description].barcode))+ '.' + baseFileName +'.afterBC.fasta'),"a")
record.id = 'BC_' + str(int(dfCollector[dfCollector.seqID == record.description].barcode)) + '_' + record.id
SeqIO.write(record,handle,"fasta")
handle.close()
else:
handle = open( os.path.join(getBarcodeDir(baseFileName), 'unknown.afterBC.fasta'),"a")
SeqIO.write(record,handle,"fasta")
handle.close()
logger.debug('Lower (%s)then treshold, store as undefined' , float(dfCollector[dfCollector.seqID == record.description][['scoreF','scoreR']].sum(axis=1)))
counter = counter + 1
if counter%1000==0:
logger.debug(counter)
#break
def nanocorrect(baseFileName,args):
"""
Step 2. Run two times error correction on the demuxed data
"""
logger.info('Start Nanocorrect')
#Load in the demuxed files
barcodeFiles = next(os.walk(getBarcodeDir(baseFileName)))[2] #Find demuxed files in barode directory TODO:errorhandeling
demuxedBarcodes = []
logger.info( 'Work on the following files: ' + " ".join(barcodeFiles))
if 'unknown.afterBC.fasta' in barcodeFiles: #Unknown barcodes will not be parsed
barcodeFiles.remove('unknown.afterBC.fasta')
for thisFilename in barcodeFiles: #Go through each filename
demuxedBarcodes.append(int(thisFilename.split('.')[0])) #Save the '8' of '8.poreCamp.2D.min500.afterBC.fasta'
demuxedBarcodes = sorted(demuxedBarcodes) #For fun, sort the list
### This returns a tuple of start and end. These numbers refer to the index of the demuxedBarcodes list. ie [(0, 11), (11, 22), (22, 33), (33, 43)]
if len(demuxedBarcodes) == 0:
raise ValueError('There are no barcodes to distribute. Did the deMux step result in any hits?')
jobRange = zip(*getJobrange(demuxedBarcodes,args.cores))
###PREPARE THE DIRECTORY FOR NANOCORRECT
for thisPosition in jobRange: #loop through each tuple of the barcode list
thisRange = demuxedBarcodes[thisPosition[0]:thisPosition[1]] #make a slice of the barcode list
logger.debug('Ranges:')
logger.debug (thisRange )
for thisBarcode in thisRange:
#Nanocorrect runs in an individual directory so need to create this
os.makedirs(os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode)))
#populate the individual barcode directory with the post barcode file
#This will copy a file from output/barcode/mysample/32.mysample.afterBC.fasta to output/nanocorrect/mysample/32/32.mysample.afterBC.fasta
copyfile(
os.path.join(getBarcodeDir(baseFileName),".".join([str(thisBarcode),baseFileName,'afterBC.fasta'])) ,
os.path.join(getNanocorrectDir(baseFileName),str(thisBarcode),".".join([str(thisBarcode),baseFileName,'afterBC.fasta']) ))
jobs = [] #Store multiprocessing jobs
#### LOOP TO SPAWN IN PARALLEL NANOCORRECT round 1
for thisPosition in jobRange: #loop through each tuple of the barcode
thisRange = demuxedBarcodes[thisPosition[0]:thisPosition[1]] #make a slice of the barcode list
argList = {'round':1,