-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathdenoising.py
executable file
·2246 lines (2033 loc) · 123 KB
/
denoising.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 python3
__author__ = 'Olivier Rué - Migale/MaIAGE & Frédéric Escudié - Genotoul/MIAT - INRAE & Maria Bernard - SIGENAE/GABI'
__copyright__ = 'Copyright (C) 2024 INRAE'
__license__ = 'GNU General Public License'
__version__ = '5.0.0'
__email__ = '[email protected]'
__status__ = 'prod'
import re
import os
import sys
import gzip
import json
import shutil
import tarfile
import argparse
import threading
import multiprocessing
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
# PATH
BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(CURRENT_DIR), "libexec"))
os.environ['PATH'] = BIN_DIR + os.pathsep + os.environ['PATH']
# PYTHONPATH
LIB_DIR = os.path.abspath(os.path.join(os.path.dirname(CURRENT_DIR), "lib"))
sys.path.append(LIB_DIR)
if os.getenv('PYTHONPATH') is None: os.environ['PYTHONPATH'] = LIB_DIR
else: os.environ['PYTHONPATH'] = LIB_DIR + os.pathsep + os.environ['PYTHONPATH']
from frogsUtils import *
from frogsSequenceIO import *
from frogsBiom import Biom, BiomIO
##################################################################################################################################################
#
# COMMAND LINES
#
##################################################################################################################################################
class Depths(Cmd):
"""
@summary: Writes by abundance the number of clusters.
"""
def __init__(self, in_biom, out_tsv):
"""
@param in_biom: [str] The processed BIOM path.
@param out_tsv: [str] The path of the output.
"""
Cmd.__init__( self,
'biomTools.py',
'Writes by abundance the number of clusters.',
'obsdepth --input-file ' + in_biom + ' --output-file ' + out_tsv,
'--version' )
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class ExtractSwarmsFasta(Cmd):
"""
@summary: Extracts seeds sequences to produce the seeds fasta.
"""
def __init__(self, in_fasta, in_swarms, out_seeds_file):
"""
@param in_fasta: [str] Path to the input fasta file.
@param in_swarms: [str] Path to swarm output file. It describes which reads compose each swarm.
@param out_seeds_file: [str] Path to the output fasta file.
"""
Cmd.__init__( self,
'extractSwarmsFasta.py',
'Extracts seeds sequences to produce the seeds fasta.',
'--input-fasta ' + in_fasta + ' --input-swarms ' + in_swarms + ' --output-fasta ' + out_seeds_file,
'--version' )
def get_version(self):
"""
@summary: Returns the program version number.
@return: [str] Version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout').strip()
class Swarm2Biom(Cmd):
"""
@summary: Converts swarm results in BIOM file.
"""
def __init__(self, in_swarms, in_count, out_biom):
"""
@param in_swarms: [str] Path to swarm output file. It describes which reads compose each swarm.
@param in_count: [str] Path to the count file. It contains the count by sample for each representative sequence.
@param out_biom: [str] Path to the output BIOM.
"""
Cmd.__init__( self,
'swarm2biom.py',
'Converts swarm output to abundance file (format BIOM).',
"--clusters-file " + in_swarms + " --count-file " + in_count + " --output-file " + out_biom,
'--version' )
def get_version(self):
"""
@summary: Returns the program version number.
@return: [str] Version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout').strip()
class Swarm(Cmd):
"""
@summary: Sequences clustering.
@see: https://github.com/torognes/swarm
"""
def __init__(self, in_fasta, out_swarms, out_log, distance, fastidious_opt, nb_cpus):
"""
@param in_fasta: [str] Path to fasta file to process.
@param out_swarms: [str] Path to swarm output file. It describes which reads compose each swarm.
@param out_log: [str] Path to swarm log file.
@param distance: [int] The 'param.distance'
@param fastidious_opt: [bool] True if fastidious option is chosen
@param nb_cpus : [int] 'param.nb_cpus'.
"""
opt = ' --fastidious ' if fastidious_opt else ''
Cmd.__init__( self,
'swarm',
'Clustering sequences.',
"--differences " + str(distance) + opt + " --threads " + str(nb_cpus) + " --log " + out_log + " --output-file " + out_swarms + " " + in_fasta,
'--version' )
def get_version(self):
"""
@summary: Returns the program version number.
@return: [str] Version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stderr').split()[1]
class SortFasta(Cmd):
"""
@summary: Sort dereplicated sequences by decreasing abundance.
"""
def __init__(self, in_fasta, out_fasta, debug, size_separator=';size='):
"""
@param in_fasta: [str] Path to unsorted file.
@param out_fasta: [str] Path to file after sort.
@param debug: [bool] True if debug mode activated
@param size_separator: [str] Each sequence in in_fasta is see as a pre-cluster. The number of sequences represented by the pre-cluster is stored in sequence ID.
Sequence ID format : '<REAL_ID><size_separator><NB_SEQ>'. If this size separator is missing in ID, the number of sequences represented is 1.
"""
opt = ' --debug ' if debug else ''
Cmd.__init__( self,
'sortAbundancies.py',
'Sort pre-clusters by abundancies.',
"--size-separator '" + size_separator + "' --input-file " + in_fasta + ' --output-file ' + out_fasta + opt,
'--version' )
def get_version(self):
"""
@summary: Returns the program version number.
@return: [str] Version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout').strip()
class Dada2Core(Cmd):
"""
@summary: Launch R script dada2_process.R to obtain denoised R1 and R2 FASTQ files from R1 and R2 FASTQ files
@see: https://benjjneb.github.io/dada2/index.html
"""
def __init__(self, r1_files, r2_files, output_dir, output_filenames, stderr, param ):
"""
@param r1_files: [str] Path to input R1 files
@param r2_files: [str] Path to input R2 files
@param output_dir: [str] Path to write output files
@param output_filenames: [str] File containing coma separated list of R1 and R2 output files
@param stderr: [str] Path to stderr output file
@param pseudo_pooling: [bool] True if pseudo-pooling option is chosen
@param param: [Namespace] The 'param.sequencer', 'param.pseudo_pooling', 'param.nb_cpus'
"""
opts = ""
if param.sample_inference == "pseudo-pooling":
opts = " --pseudopooling "
elif param.sample_inference == "pooling":
opts = " --pooling "
if args.debug:
opts += " --debug"
if r2_files:
Cmd.__init__( self,
'dada2_process.R',
'Write denoised FASTQ files from cutadapted and cleaned FASTQ files',
' --R1Files ' + ",".join(r1_files) + ' --R2Files ' + ",".join(r2_files) + opts + ' --outputDir ' + output_dir + ' --fileNames ' + output_filenames + ' --sequencer ' + param.sequencer + ' --threads ' + str(param.nb_cpus) + ' 2> ' + stderr,
'--version')
else:
Cmd.__init__( self,
'dada2_process.R',
'Write denoised FASTQ files from cutadapted and cleaned FASTQ files',
' --R1Files ' + ",".join(r1_files) + opts + ' --outputDir ' + output_dir + ' --fileNames ' + output_filenames + ' --sequencer ' + param.sequencer + ' --threads ' + str(param.nb_cpus) + ' 2> ' + stderr,
'--version')
def get_version(self):
"""
@summary: Returns the program version number.
@return : [str] Version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout')
class Pear(Cmd):
"""
@summary: Overlapping and merging R1 and R2 reads with pear
@see: https://github.com/tseemann/PEAR
"""
def __init__(self, in_R1, in_R2, out_prefix, pear_log, pear_stderr, param):
"""
@param in_R1: [str] Path to the R1 fastq file.
@param in_R2: [str] Path to the R2 fastq file.
@param out_prefix: [str] Prefix of path to the output fastq files.
@param pear_log: [str] Path to log file
@param pear_stderr: [str] Path to stderr file
@param param: [Namespace] The 'param.min_amplicon_size', 'param.max_amplicon_size', 'param.R1_size', 'param.R2_size'
"""
min_overlap=max(param.R1_size+param.R2_size-param.max_amplicon_size, 10)
max_assembly_length=min(param.max_amplicon_size, param.R1_size + param.R2_size -10)
min_assembly_length=param.min_amplicon_size
Cmd.__init__(self,
'pear',
'join overlapping paired reads',
' --forward-fastq ' + in_R1 + ' --reverse-fastq ' + in_R2 +' --output ' + out_prefix \
+ ' --min-overlap ' + str(min_overlap) + ' --max-assembly-length ' + str(max_assembly_length) + ' --min-assembly-length ' + str(min_assembly_length) \
+ ' --keep-original 2> ' + pear_stderr + ' &> ' + pear_log,
' --version')
self.output = out_prefix + '.assembled.fastq'
self.unassembled_forward = out_prefix + '.unassembled.forward.fastq'
self.unassembled_reverse = out_prefix + '.unassembled.reverse.fastq'
self.process = param.process
self.in_R1 = in_R1
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout').split()[1].strip()
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
if not os.path.isfile(self.output):
open(self.output, "x")
open(self.unassembled_forward, "x")
open(self.unassembled_reverse, "x")
nb_seq_merged = get_nb_seq(self.output)
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
if self.process == "dada2":
nb_seq_denoised = get_nb_seq(self.in_R1)
FH_log.write( '\tnb seq denoised: ' + str(nb_seq_denoised) + '\n' )
FH_log.write( '\tnb seq paired-end assembled: ' + str(nb_seq_merged) + '\n' )
FH_log.close()
class Flash(Cmd):
"""
@summary: Overlapping and merging mate pairs from fragments shorter than twice the length of reads. The others fragments are discarded.
"""
def __init__(self, in_R1, in_R2, out_join_prefix , flash_err, param):
"""
@param in_R1: [str] Path to the R1 fastq file.
@param in_R2: [str] Path to the R2 fastq file.
@param out_join_prefix: [str] Path to the output fastq file.
@param flash_err: [str] Path to the temporary stderr output file
@param param: [Namespace] The 'param.min_amplicon_size', 'param.max_amplicon_size', 'param.expected_amplicon_size', 'param.fungi' and param.mismatch_rate'
"""
min_overlap=max(param.R1_size+param.R2_size-param.max_amplicon_size, 10)
max_expected_overlap = (param.R1_size + param.R2_size) - param.expected_amplicon_size + min(20, int((param.expected_amplicon_size - param.min_amplicon_size)/2))
out_dir=os.path.dirname(out_join_prefix) if os.path.dirname(out_join_prefix)!= "" else "."
Cmd.__init__( self,
'flash',
'Join overlapping paired reads.',
'--threads 1 --allow-outies --min-overlap ' + str(min_overlap) + ' --max-overlap ' + str(max_expected_overlap) + ' --max-mismatch-density ' + str(param.mismatch_rate) +' --compress ' + in_R1 + ' ' + in_R2 + ' --output-directory '+ out_dir + ' --output-prefix ' + os.path.basename(out_join_prefix) +' 2> ' + flash_err,
' --version' )
self.output = out_join_prefix + ".extendedFrags.fastq.gz"
self.process = param.process
self.in_R1 = in_R1
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout').split()[1].strip()
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
nb_seq_merged = get_nb_seq(self.output)
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
if self.process == "dada2":
nb_seq_denoised = get_nb_seq(self.in_R1)
FH_log.write( '\tnb seq denoised: ' + str(nb_seq_denoised) + '\n' )
FH_log.write( '\tnb seq paired-end assembled: ' + str(nb_seq_merged) + '\n' )
FH_log.close()
class Vsearch(Cmd):
"""
@summary: Overlapping and merging R1 and R2 files with vsearch.
@see: https://github.com/torognes/vsearch
"""
def __init__(self, in_R1, in_R2, out_prefix, log, param):
"""
@param in_R1: [str] Path to the R1 fastq file.
@param in_R2: [str] Path to the R2 fastq file.
@param out_prefix: [str] Prefix of path to the output fastq files.
@param log: [str] Path to log file
@param param: [Namespace] The 'param.min_amplicon_size', 'param.max_amplicon_size', 'param.R1_size', 'param.R2_size'
"""
min_overlap=max(param.R1_size+param.R2_size-param.max_amplicon_size, 10)
Cmd.__init__(self,
'vsearch',
'join overlapping paired reads',
' --threads 1 --fastq_mergepairs ' + in_R1 + ' --reverse ' + in_R2 \
+ ' --fastqout ' + out_prefix + '.assembled.fastq ' + ' --fastqout_notmerged_fwd ' + out_prefix + '.unassembled_R1.fastq ' + ' --fastqout_notmerged_rev ' + out_prefix + '.unassembled_R2.fastq '\
+ ' --fastq_allowmergestagger --fastq_ascii ' + param.quality_scale + ' --fastq_maxdiffpct ' + str(param.mismatch_rate*100) + ' --fastq_minovlen ' + str(min_overlap) \
+ ' 2> ' + log,
'--version')
self.output = out_prefix + '.assembled.fastq'
self.process = param.process
self.in_R1 = in_R1
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stderr').split(",")[0].split()[1] # vsearch v1.1.3_linux_x86_64, 126.0GB RAM, 32 cores
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
nb_seq_merged = get_nb_seq(self.output)
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
if self.process == "dada2":
nb_seq_denoised = get_nb_seq(self.in_R1)
FH_log.write( '\tnb seq denoised: ' + str(nb_seq_denoised) + '\n' )
FH_log.write( '\tnb seq paired-end assembled: ' + str(nb_seq_merged) + '\n' )
FH_log.close()
class Remove454prim(Cmd):
"""
@summary: Removes reads without the 3' and 5' primer and removes primers sequences.
"""
def __init__(self, in_fastq, out_fastq, cutadapt_log, cutadapt_err, param):
"""
@param in_fastq: [str] Path to the processed fastq.
@param out_fastq: [str] Path to the fastq with valid sequences.
@param cutadapt_log: [str] Path to the log file.
@param cutadapt_err: [str] Path to the stderr file.
@param param: [Namespace] 'param.five_prim_primer', 'param.three_prim_primer' and 'param.min_amplicon_size'.
"""
Cmd.__init__( self,
'remove454Adapt.py',
"Removes reads without the 3' and 5' primer and removes primers sequences.",
'--five-prim-primer ' + param.five_prim_primer + ' --three-prim-primer ' + param.three_prim_primer + ' --error-rate 0.1 --non-overlap 1 --min-length ' + str(args.min_amplicon_size) + ' -i ' + in_fastq + ' -o ' + out_fastq + ' > ' + cutadapt_log + ' 2> ' + cutadapt_err,
'--version' )
self.output_seq = out_fastq
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
FH_output_seq = SequenceFileReader.factory( self.output_seq )
nb_cleaned = 0
for record in FH_output_seq:
nb_cleaned += 1
FH_output_seq.close()
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
FH_log.write( "\tnb seq with the two primers : " + str(nb_cleaned) + '\n' )
FH_log.close()
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class Cutadapt5prim(Cmd):
"""
@summary: Removes reads without the 5' primer and removes primer sequence.
"""
def __init__(self, in_fastq, out_fastq, cutadapt_log, cutadapt_err, param):
"""
@param in_fastq: [str] Path to the processed fastq.
@param out_fastq: [str] Path to the fastq with valid sequences.
@param cutadapt_log: [str] Path to the log file.
@param cutadapt_err: [str] Path to the error file.
@param param: [Namespace] The primer sequence 'param.five_prim_primer', 'param.sequencer'
"""
opt = ''
if param.sequencer == "longreads":
opt = ' --revcomp '
Cmd.__init__( self,
'cutadapt',
"Removes reads without the 5' primer and removes primer sequence.",
'-g ' + param.five_prim_primer + ' --error-rate 0.1 --discard-untrimmed --match-read-wildcards --overlap ' + str(len(param.five_prim_primer) -1) + opt + ' -o ' + out_fastq + ' ' + in_fastq + ' > ' + cutadapt_log + ' 2> ' + cutadapt_err,
'--version' )
self.output_seq = out_fastq
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
FH_output_seq = SequenceFileReader.factory( self.output_seq )
nb_cleaned = 0
for record in FH_output_seq:
nb_cleaned += 1
FH_output_seq.close()
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
FH_log.write( "\tnb seq with 5' primer : " + str(nb_cleaned) + '\n' )
FH_log.close()
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout')
class Cutadapt3prim(Cmd):
"""
@summary: Removes reads without the 3' primer and removes primer sequence.
"""
def __init__(self, in_fastq, out_fastq, cutadapt_log, cutadapt_err, param):
"""
@param in_fastq: [str] Path to the processed fastq.
@param out_fastq: [str] Path to the fastq with valid sequences.
@param cutadapt_log: [str] Path to the log file.
@param cutadapt_err: [str] Path to the error file.
@param param: [Namespace] The primer sequence 'param.three_prim_primer', 'param.sequencer'
"""
opt = ''
if param.sequencer == "longreads":
opt = ' --revcomp '
Cmd.__init__( self,
'cutadapt',
"Removes reads without the 3' primer and removes primer sequence.",
'-a ' + param.three_prim_primer + ' --error-rate 0.1 --discard-untrimmed --match-read-wildcards --overlap ' + str(len(param.three_prim_primer) -1) + opt + ' -o ' + out_fastq + ' ' + in_fastq + ' > ' + cutadapt_log + ' 2> ' + cutadapt_err,
'--version' )
self.output_seq = out_fastq
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
FH_output_seq = SequenceFileReader.factory( self.output_seq )
nb_cleaned = 0
for record in FH_output_seq:
nb_cleaned += 1
FH_output_seq.close()
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
FH_log.write( "\tnb seq with 3' primer : " + str(nb_cleaned) + '\n' )
FH_log.close()
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout')
class CutadaptPaired(Cmd):
"""
@summary: Removes read pairs without 5' primer in R1 and 3' primer in R2 and removes primer sequences.
"""
def __init__(self, in_R1_fastq, in_R2_fastq, out_R1_fastq, out_R2_fastq, cutadapt_log, cutadapt_err, param):
"""
@param in_R1_fastq: [str] Path to the R1 fastq file to process.
@param in_R2_fastq: [str] Path to the R2 fastq file to process.
@param out_R1_fastq: [str] Path to the R1 fastq with valid sequences.
@param out_R2_fastq: [str] Path to the R2 fastq with valid sequences.
@param cutadapt_log: [str] Path to the log file.
@param cutadapt_err: [str] Path to the error file.
@param param: [Namespace] The primer sequence 'param.three_prim_primer'.
"""
Cmd.__init__( self,
'cutadapt',
"Removes read pairs without the 5' and 3' primer and removes primer sequence.",
'-g \"' + param.five_prim_primer + ';min_overlap=' + str(len(param.five_prim_primer)-1) + '\" -G \"' + revcomp(param.three_prim_primer) + ';min_overlap=' + str(len(param.three_prim_primer)-1) + '\" --minimum-length 1 --error-rate 0.1 --discard-untrimmed --match-read-wildcards --pair-filter=any ' + ' -o ' + out_R1_fastq + ' -p ' + out_R2_fastq + ' ' + in_R1_fastq + ' ' + in_R2_fastq + ' > ' + cutadapt_log + ' 2> ' + cutadapt_err,
'--version' )
self.cutadapt_log = cutadapt_log
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
FH_cutadapt_log = open(self.cutadapt_log, 'rt')
five_count = 0
both = 0
for line in FH_cutadapt_log:
if line.strip().startswith('Read 1 with adapter:'):
five_count = str(line.split()[4].replace(',',''))
if line.strip().startswith('Pairs written (passing filters):'):
both = str(line.split()[4].replace(',',''))
FH_cutadapt_log.close()
# Write result
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
FH_log.write( "\tnb seq with 5' primer : " + str(five_count) + '\n' )
FH_log.write( "\tnb seq with 3' primer : " + str(both) + '\n' )
FH_log.close()
def get_version(self):
"""
@summary: Returns the program version number.
@return: version number if this is possible, otherwise this method return 'unknown'.
"""
return Cmd.get_version(self, 'stdout')
class MultiFilter(Cmd):
"""
@summary : Filters sequences.
"""
def __init__(self, in_r1, in_r2, min_len, max_len, max_n, tag, out_r1, out_r2, log_file, force_fasta, write_nb_seqs_r1_in_log, param):
"""
@param in_r1: [str] Path to the R1 fastq file to filter.
@param in_r2: [str] Path to the R2 fastq file to filter.
@param min_len [int]: minimum and maximum length filter criteria.
@param max_len [int]: maximum length filter criteria.
@param max_n [int]: maximum N's filter criteria.
@param tag [str] : check the presence of tag in sequence.
@param out_r1: [str] Path to the output R1 fastq file.
@param out_r2: [str] Path to the output R2 fastq file.
@param log_file: [str] Path to the log file.
@param force_fasta: [bool] True if a FASTA file must be generated.
@param write_nb_seqs_r1_in_log: [bool] True if number of sequences in R1 file must be written in log file for summary report
@param param: [Namespace] The 'param.sequencer'
"""
cmd_description = 'Filters amplicons without primers by length and N count.',
add_options = ""
if param.sequencer == "454":
cmd_description = 'Filters amplicons without primers by length, N count, homopolymer length and distance between quality low quality.',
add_options = ' --max-homopolymer 7 --qual-window threshold:10 win_size:10'
if min_len is not None:
add_options += ' --min-length ' + str(min_len)
if max_len is not None:
add_options += ' --max-length ' + str(max_len)
if not tag is None:
add_options += ' --tag ' + tag
if not max_n is None:
add_options += ' --max-N ' + str(max_n)
if force_fasta:
add_options += ' --force-fasta '
if in_r2 is None:
Cmd.__init__( self,
'filterSeq.py',
'Filters amplicons without primers by length and N count',
add_options + ' --input-file1 ' + in_r1 + ' --output-file1 ' + out_r1 + ' --log-file ' + log_file,
'--version' )
else:
Cmd.__init__( self,
'filterSeq.py',
'Filters amplicons without primers by length and N count.',
add_options + ' --input-file1 ' + in_r1 + ' --input-file2 ' + in_r2 + ' --output-file1 ' + out_r1 + ' --output-file2 ' + out_r2 + ' --log-file ' + log_file,
'--version' )
self.program_log = log_file
self.process = param.process
self.sequencer = param.sequencer
self.in_R1 = in_r1
self.write_nb_seqs_r1_in_log = write_nb_seqs_r1_in_log
def parser(self, log_file):
"""
@summary: Parse the command results to add information in log_file.
@log_file: [str] Path to the sample process log file.
"""
# Parse output
FH_log_filter = open( self.program_log )
nb_processed = 0
filtered_on_length = None
filtered_on_tag = None
filtered_on_N = None
filtered_on_homopolymer = None
filtered_on_quality = None
for line in FH_log_filter:
if line.startswith('Nb seq filtered on length'):
filtered_on_length = int(line.split(':')[1].strip())
if line.startswith('Nb seq filtered on absence of tag'):
filtered_on_tag = int(line.split(':')[1].strip())
elif line.startswith('Nb seq filtered on N'):
filtered_on_N = int(line.split(':')[1].strip())
elif line.startswith('Nb seq filtered on homopolymer'):
filtered_on_homopolymer = int(line.split(':')[1].strip())
elif line.startswith('Nb seq filtered on quality'):
filtered_on_quality = int(line.split(':')[1].strip())
elif line.startswith('Nb seq processed'):
nb_processed = int(line.split(':')[1].strip())
FH_log_filter.close()
# Write result
previous_nb_seq = nb_processed
FH_log = Logger( log_file )
FH_log.write( 'Results:\n' )
if self.write_nb_seqs_r1_in_log:
if self.process == "dada2" and self.sequencer == "longreads":
nb_seq_denoised = get_nb_seq(self.in_R1)
FH_log.write( '\tnb seq denoised: ' + str(nb_seq_denoised) + '\n' )
if filtered_on_tag is not None:
FH_log.write( '\t(nb seq with expected tag : ' + str(previous_nb_seq - filtered_on_tag) + ')\n' )
previous_nb_seq -= filtered_on_tag
if filtered_on_length is not None:
FH_log.write( '\tinitial seqs given to filtering : ' + str(previous_nb_seq) + '\n' )
FH_log.write( '\tnb seq with expected length : ' + str(previous_nb_seq - filtered_on_length) + '\n' )
previous_nb_seq -= filtered_on_length
if filtered_on_N is not None:
FH_log.write( '\tnb seq without N : ' + str(previous_nb_seq - filtered_on_N) + '\n' )
previous_nb_seq -= filtered_on_N
if filtered_on_homopolymer is not None:
FH_log.write( '\tnb seq without large homopolymer : ' + str(previous_nb_seq - filtered_on_homopolymer) + '\n' )
previous_nb_seq -= filtered_on_homopolymer
if filtered_on_quality is not None:
FH_log.write( '\tnb seq without nearest poor quality : ' + str(previous_nb_seq - filtered_on_quality) + '\n' )
previous_nb_seq -= filtered_on_quality
FH_log.close()
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class Combined(Cmd):
"""
@summary : Artificially combined reads by adding a combined tag
"""
def __init__(self, in_R1, in_R2, join_tag , out_join_file ):
"""
@param in_R1: [str] Path to sequence 5' (fasta/q format)
@param in_R2: [str] Path to sequence 3' (fasta/q format)
@param join_tag: [str] the sequence tag to add between sequences
@param out_join_file: [str] Path to fasta/q combined sequence output file
"""
Cmd.__init__( self,
'combine_and_split.py',
'Concatenate paired reads.',
' --reads1 ' + in_R1+ ' --reads2 ' + in_R2 + ' -c ' + join_tag + ' --combined-output ' + out_join_file,
'--version' )
self.output = out_join_file
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class ReplaceJoinTag(Cmd):
"""
@summary : Replace join tag
"""
def __init__(self, combined_input , split_tag , join_tag , out_join_file ):
"""
@param combined_input: [str] Path to combined sequence
@param split_tag: [str] the sequence tag on which to split sequences
@param join_tag: [str] the sequence tag to add between sequences
@param out_join_file: [str] Path to fasta/q combined sequence output file
"""
Cmd.__init__( self,
'combine_and_split.py',
'Replace join tag.',
' --reads1 ' + combined_input + ' -s ' + split_tag + ' -c ' + join_tag + ' --combined-output ' + out_join_file,
'--version' )
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class DerepBySample(Cmd):
"""
@summary: Dereplicates sample sequences.
"""
def __init__(self, in_fasta, out_fasta, out_count, size_separator=None):
"""
@param in_fasta: [str] Path to the processed fasta.
@param out_fasta: [str] Path to the dereplicated fasta.
@param out_count: [str] Path to the count file.
@param size_separator: [str] size separator (optional)
"""
if size_separator is not None:
Cmd.__init__( self,
'derepSamples.py',
'Dereplicates sample sequences.',
'--sequences-files ' + in_fasta + ' --dereplicated-file ' + out_fasta + ' --count-file ' + out_count + ' --size-separator ' + size_separator + ' ',
'--version' )
else:
Cmd.__init__( self,
'derepSamples.py',
'Dereplicates sample sequences.',
'--sequences-files ' + in_fasta + ' --dereplicated-file ' + out_fasta + ' --count-file ' + out_count,
'--version' )
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
class DerepGlobalMultiFasta(Cmd):
"""
@summary: Dereplicates together sequences from several files.
"""
def __init__(self, all_fasta, samples_names, out_samples_ref, out_fasta, out_count, param):
"""
@param all_fasta: [list] Path to the processed fasta.
@param samples_names: [list] The sample name for each fasta.
@param out_samples_ref: [str] Path to the file containing the link between samples names and path.
@param out_fasta: [str] Path to the dereplicated fasta.
@param out_count: [str] Path to the count file. It contains the count by sample for each representative sequence.
@param param: [str] The 'param.nb_cpus'.
"""
# Write sample description
FH_ref = open(out_samples_ref, "wt")
FH_ref.write( "#Sequence_file\tSample_name\n" )
for idx, current_name in enumerate(samples_names):
FH_ref.write( all_fasta[idx] + "\t" + current_name + "\n" )
FH_ref.close()
# Init
Cmd.__init__( self,
'derepSamples.py',
'Dereplicates together sequences from several samples.',
"--nb-cpus " + str(param.nb_cpus) + " --size-separator ';size=' --samples-ref " + out_samples_ref + " --dereplicated-file " + out_fasta + " --count-file " + out_count,
'--version' )
def get_version(self):
return Cmd.get_version(self, 'stdout').strip()
##################################################################################################################################################
#
# FUNCTIONS
#
##################################################################################################################################################
def is_empty_compressed_file(file_path):
"""
@summary: check if the file is empty or not
@param file_path: [str] file path to check
"""
try:
with gzip.open(file_path, 'rb') as file:
return not file.read(1)
except FileNotFoundError:
return False
def spl_name_type( arg_value ):
"""
@summary: Argparse type for samples-names.
@param arg_value: [str] --samples-names parameter
"""
if re.search("\s", arg_value): raise_exception( argparse.ArgumentTypeError( "\n\n#ERROR : A sample name must not contain white spaces.\n\n" ))
return str(arg_value)
def sort_fasta_and_count(in_fasta, in_count, out_fasta, out_count):
fasta_data = []
in_fasta_fh = FastaIO( in_fasta )
out_fasta_fh = open( out_fasta, "w")
for record in in_fasta_fh:
sequence_id = record.id.split(";")[0]
size = int(record.id.split(';')[1].split('=')[1])
sequence = str(record.string)
fasta_data.append((sequence_id, size, sequence))
# Lecture du tableau de données et calcul de la somme des colonnes
tsv_data = []
with open(in_count) as tsv_file:
header = next(tsv_file).strip() # Ignorer la première ligne
for line in tsv_file:
parts = line.strip().split('\t')
sequence_id = parts[0]
sums = sum(map(int, parts[1:]))
whole_line = [i for i in parts[1:]]
tsv_data.append((sequence_id, sums, whole_line))
# Tri des données par abondance, puis par identifiant de séquence
sorted_fasta_data = sorted(fasta_data, key=lambda x: (x[1], x[0]), reverse=True)
sorted_tsv_data = sorted(tsv_data, key=lambda x: (x[1], x[0]), reverse=True)
# Affichage des résultats triés
cpt=1
for entry in sorted_fasta_data:
if "FROGS_combined" in entry[0]:
seqid = "Cluster_"+str(cpt)+"_FROGS_combined"#+";"+sizes
else:
seqid = "Cluster_"+str(cpt)#+";"+sizes
out_fasta_fh.write(">"+seqid+"\n"+entry[2]+"\n")
cpt+=1
out_count_fh = open(out_count,"w")
out_count_fh.write(header+"\n")
cpt=1
for entry in sorted_tsv_data:
if "FROGS_combined" in str(entry[0]):
seqid = "Cluster_"+str(cpt)+"_FROGS_combined"#+";"+sizes
else:
seqid = "Cluster_"+str(cpt)#+";"+sizes
out_count_fh.write(seqid+"\t"+"\t".join(entry[2])+"\n")
cpt+=1
def to_biom(count_file, output_biom, process):
"""
@summary : Write a biom and a fasta file from a count and a fasta file by adding Cluster_ prefix
@param count_file : [str] path to the count file. It contains the count of
sequences by sample of each preclusters.
Line format : "Precluster_id nb_in_sampleA nb_in_sampleB"
@param output_biom : [str] path to the output biom file.
@param process: [str] process used to generate sequences to transform to biom and fasta.
"""
if process == "dada2":
biom = Biom( generated_by='dada2', matrix_type="sparse")
else: # only dereplication
biom = Biom( generated_by='frogs', matrix_type="sparse")
# Preclusters count by sample
preclusters_count = dict()
count_fh = open( count_file )
samples = count_fh.readline().strip().split()[1:]
cpt=1
for line in count_fh:
count_str, count_str = line.strip().split(None, 1)
preclusters_count[cpt] = count_str # For large dataset store count into a string consumes minus RAM than a sparse count
cpt+=1
count_fh.close()
# Add samples
for sample_name in samples:
biom.add_sample( sample_name )
# Process count
cluster_idx = 1
clusters_fh = open( count_file )
for line in clusters_fh:
if not line.startswith("#"):
seq_id = line.strip().split()[0]
if "FROGS_combined" in seq_id:
cluster_name = "Cluster_" + str(cluster_idx) + "_FROGS_combined"
comment = ["FROGS_combined"]
else:
cluster_name = "Cluster_" + str(cluster_idx)
comment = list()
cluster_count = {key:0 for key in samples}
sample_counts = preclusters_count[cluster_idx].split("\t")
for sample_idx, sample_name in enumerate(samples):
cluster_count[sample_name] += int(sample_counts[sample_idx])
preclusters_count[cluster_idx] = None
# Add cluster on biom
biom.add_observation( cluster_name, {'comment': comment, 'seed_id':"None"} )
observation_idx = biom.find_idx("observation", cluster_name)
for sample_idx, sample_name in enumerate(samples):
if cluster_count[sample_name] > 0:
biom.data.change( observation_idx, sample_idx, cluster_count[sample_name] )
# Next cluster
cluster_idx += 1
# Write
BiomIO.write( output_biom, biom )
def replaceNtags(in_fasta, out_fasta):
"""
@summary : for FROGS_combined sequence, replace N tags by A and record start and stop positions in description
@param in_fasta: [str] Path to input fasta file
@param out_fasta: [str] Path to output fasta file
"""
FH_in = FastaIO(in_fasta)
FH_out = FastaIO(out_fasta, "wt")
for record in FH_in:
if "FROGS_combined" in record.id :
if not 100*"N" in record.string:
raise_exception(Exception("\n\n#ERROR : record " + record.id + " is a FROGS_combined sequence but it does not contain de 100N tags\n"))
N_idx1 = record.string.find("N")
N_idx2 = record.string.rfind("N")
replace_tag = 50*"A" + 50 * "C"
record.string = record.string.replace(100*"N",replace_tag)
if record.description :
record.description += "50A50C:" + str(N_idx1) + ":" + str(N_idx2)
else:
record.description = "50A50C:" + str(N_idx1) + ":" + str(N_idx2)
FH_out.write(record)
FH_in.close()
FH_out.close()
def addNtags(in_fasta, output_fasta):
"""
@summary : replace sequence indicated in seed description by N : ex A:10:110 replace 100A from 10 to 110 by N
@param in_fasta : [str] Path to input fasta file
@param output_fasta : [str] Path to output fasta file
"""
FH_in = FastaIO(in_fasta)
FH_out = FastaIO(output_fasta, "wt")
regexp = re.compile('50A50C:\d+:\d+$')
for record in FH_in:
if "FROGS_combined" in record.id :
search = regexp.search(record.description)
if search is None:
raise_exception( Exception("\n\n#ERROR : " + record.id + " is a FROGS_combined cluster but has not combining tag positions in its description.\n\n"))
desc = search.group()
[N_idx1,N_idx2] = desc.split(":")[1:]
if record.string[int(N_idx1):int(N_idx2)+1] != 50*"A" + 50*"C":
raise_exception( Exception("\n\n#ERROR : " + record.id + " is a FROGS_combined cluster but has not combining tag 50 As followed by 50 Cs to replace with 100 Ns\n\n"))
record.string = record.string[:int(N_idx1)]+"N"*(int(N_idx2)-int(N_idx1)+1)+record.string[int(N_idx2)+1:]
record.description = record.description.replace(desc,"")
FH_out.write(record)
FH_out.close()
FH_in.close()
def link_inputFiles(file_list, tmpFiles, log):
"""
@summary : link Galaxy input file into working dir to add comprehensive extension for cutadapt
@param file_list [list] : list of input path files
@param tmpFile [object] : tmpFiles to store link to remove at the end
@param logfile [str] : path to logFile
@return input file or link to process
"""
out_list = list()
track = True
for file in file_list:
if not file.endswith(".dat"):
out_list.append(file)
# working through Galaxy
else:
if track:
Logger.static_write(log, '##Create symlink for Galaxy inputs\n')
track = False
if FastqIO.is_valid(file):
if is_gzip(file):
link = tmpFiles.add(os.path.basename(file) + '.fastq.gz')
os.symlink(file, link)
Logger.static_write(log, '\tln -s '+ file + ' ' + link + '\n')
out_list.append(link)
else:
link = tmpFiles.add(os.path.basename(file) + '.fastq')
os.symlink(file, link)
Logger.static_write(log, '\tln -s '+ file + ' ' + link + '\n')
out_list.append(link)
elif FastaIO.is_valid(file):
if is_gzip(file):
link = tmpFiles.add(os.path.basename(file) + '.fasta.gz')
os.symlink(file, link)
Logger.static_write(log, '\tln -s '+ file + ' ' + link + '\n')
out_list.append(link)
else:
link = tmpFiles.add(os.path.basename(file) + '.fasta')
os.symlink(file, link)
Logger.static_write(log, '\tln -s '+ file + ' ' + link + '\n')
out_list.append(link)
else:
raise_exception(Exception('\n\n#ERROR :' + file + ' is neither a fasta or a fastq file\n\n'))
return out_list
def revcomp(seq):
"""
@summary : return reverse complement iupac sequence
@param: [str] the sequence to revcomp
@return: [str] the sequence reverse complemented
"""
return seq.translate(str.maketrans('ACGTacgtRYMKrymkVBHDvbhdSWsw', 'TGCAtgcaYRKMyrkmBVDHbvdhSWsw'))[::-1]
def get_seq_length( input_file, size_separator=None ):
"""
@summary: Returns the number of sequences by sequences lengths.
@param input_file: [str] The sequence file path.
@param size_separator: [str] If it exists the size separator in sequence ID.
@return: [dict] By sequences lengths the number of sequence.
"""
nb_by_length = dict()
FH_seq = SequenceFileReader.factory( input_file )