/
clustmap.py
2817 lines (2357 loc) · 100 KB
/
clustmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
de-replicates edit files and clusters de-replciated reads
by sequence similarity using vsearch
"""
from __future__ import print_function
try:
from itertools import izip, islice, chain
except ImportError:
from itertools import islice, chain
izip = zip
import os
import gzip
import glob
import time
import shutil
import warnings
import subprocess as sps
from loguru import logger
import numpy as np
import pysam
import ipyrad as ip
from ipyrad.assemble.utils import IPyradError, bcomp, comp, AssemblyProgressBar
class Step3:
"""
Distributing derep, clust/map, and build functions on samples.
"""
def __init__(self, data, force, ipyclient):
# store attributes
self.data = data
self.maxindels = 8
self.force = force
self.ipyclient = ipyclient
self.gbs = bool("gbs" in self.data.params.datatype)
self.print_headers()
self.samples = self.get_subsamples()
# init funcs
self.setup_dirs()
self.tune_threads()
def run(self):
"""
Run the assembly functions for this step
"""
# index reference fa files if there are any (bwa and sam index)
if (self.data.params.reference_sequence or
self.data.params.reference_as_filter):
self.remote_index_refs()
# i: sample.files.edits is [(r1,r2),(r1,r2),(...)] for multiple fastq
# o: tmpdir/[r1,r2]_concatedit.fastq
if any(len(sample.files.edits) > 1 for sample in self.samples):
self.remote_run(
function=concat_multiple_edits,
printstr=("concatenating ", "s3"),
args=(),
threaded=True, # needed?
)
# paired-end data methods ------------------------------
if "pair" in self.data.params.datatype:
# DENOVO (paired, denovo, optional refminus)
if self.data.params.assembly_method == "denovo":
# vsearch merge read pairs back together based on overlap.
# i: tmpdir/concatedits.fq.gz or sample.files.edits
# o: tmpdir/{}_merged.fastq, tmpdir/{}_nonmerged_R[1,2].fastq
self.remote_run(
function=merge_pairs_with_vsearch,
printstr=("join merged pairs ", "s3"),
args=(),
)
# join non-merged reads with a spacer (nnnn)
# i: tmpdir/{}_nonmerged_R[1,2].fastq
# o: tmpdir/{}_merged.fastq (appended to)
self.remote_run(
function=merge_end_to_end,
printstr=("join unmerged pairs ", "s3"),
args=(True, True,),
)
# [optional] tag for declone by moving i5 tag to sequence 5'
# i: tmpdir/{}_merged.fastq
# o: tmpdir/{}_declone.fastq
if self.data.hackersonly.declone_PCR_duplicates:
self.remote_run(
function=tag_for_decloning,
printstr=("tag for decloning ", "s3"),
args=(),
)
# dereplicate leaving pcr duplicates unreduced
# i: tmpdir/{}_declone.fastq
# o: tmpdir/{}_derep.fa
self.remote_run(
function=dereplicate,
printstr=("dereplicating ", "s3"),
args=(self.nthreads,),
threaded=True,
)
# [optional] move i5 tag from derepseq to header
# i: tmpdir/{}_derep.fa
# o: tmpdir/{}_tagged.fa
if self.data.hackersonly.declone_PCR_duplicates:
self.remote_run(
function=tag_to_header_for_decloning,
printstr=("retag for decloning ", "s3"),
args=(),
)
# [optional] remove reads mapping to the alt reference
if self.data.params.reference_as_filter:
# split reads back into fasta pairs for mapping. This had
# to be done here after tag-for-decloning.
# i: tmpdir/{}_tagged.fa OR tmpdir/{}_derep.fa
# o: tmpdir/{}_R[1,2]-tmp.fa
self.remote_run(
function=split_endtoend_reads,
printstr=("splitting dereps ", "s3"),
args=(),
)
# map reads to altref to get unmapped fastQ outputs
# i: tmpdir/{}_R[1,2]-tmp.fa
# o: tmpdir/{}-tmp-umap[1,2].FASTQ
self.remote_run(
function=mapping_reads,
printstr=("mapping minus reads ", "s3"),
args=(self.nthreads, 1,),
threaded=True,
)
# discard dir with successfully mapped reads
shutil.rmtree(self.data.dirs.refmapping)
# merge unmapped fastqs back into single end-to-end fa
# i: tmpdir/{}-tmp-umap[1,2].fastq
# o: tmpdir/{sample}_merged.fa
self.remote_run(
function=merge_end_to_end,
printstr=("join unmerged pairs ", "s3"),
args=(False, False, True,),
)
# cluster and build clusters from vsearch outputs
# o: clustdir/{sample}_clust.gz
self.remote_run_cluster_build()
# o: clustdir/{sample}_clustS.gz
self.remote_run_align_cleanup()
# REFERENCE (paired, reference, optional refminus)
elif self.data.params.assembly_method == "reference":
if self.data.params.reference_as_filter:
# map reads to altref to get unmapped fastQ outputs
# i: tmpdir/{}_R[1,2]-tmp.fa
# o: tmpdir/{}-tmp-umap[1,2].FASTQ
self.remote_run(
function=mapping_reads,
printstr=("mapping minus reads ", "s3"),
args=(self.nthreads, 1,),
threaded=True,
)
# merge pairs for dereplicating (several input options, ranked)
# i: edits/{}_trimmed_R[1,2].fastq
# i: tmpdir/{}-tmp-umap[1,2].fastq
# o: tmpdir/{}_merged.fastq
self.remote_run(
function=merge_end_to_end,
printstr=("join unmerged pairs ", "s3"),
args=(False, False,),
threaded=True,
)
# [optional] tag for declone by moving i5 tag to sequence 5'
# i: tmpdir/{}_merged.fastq
# o: tmpdir/{}_declone.fastq
if self.data.hackersonly.declone_PCR_duplicates:
self.remote_run(
function=tag_for_decloning,
printstr=("tag for decloning ", "s3"),
args=(),
)
# i: tmpdir/{}_[merged,declone].fastq
# o: tmpdir/{}_derep.fa
self.remote_run(
function=dereplicate,
printstr=("dereplicating ", "s3"),
args=(self.nthreads,),
threaded=True,
)
# [optional] move i5 tag from derepseq to header
# i: tmpdir/{}_derep.fa
# o: tmpdir/{}_tagged.fa
if self.data.hackersonly.declone_PCR_duplicates:
self.remote_run(
function=tag_to_header_for_decloning,
printstr=("retag for decloning ", "s3"),
args=(),
)
# i: tmpdir/{}_[derep,tagged].fa
# o: tmpdir/{}_R[1,2]-tmp.fa
self.remote_run(
function=split_endtoend_reads,
printstr=("splitting dereps ", "s3"),
args=(),
)
# i: tmpdir/{}_R[1,2]-tmp.fa
# o: refmapping/{}.bam
self.remote_run(
function=mapping_reads,
printstr=("mapping reads ", "s3"),
args=(self.nthreads,),
threaded=True,
)
# i: refmapping/{}.bam
# o: clustdir/{}.clustS.gz
self.remote_run(
function=build_clusters_from_cigars,
printstr=("building clusters ", "s3"),
args=(),
)
# DENOVO MINUS
elif self.data.params.assembly_method == "denovo-reference":
raise NotImplementedError(
"denovo-reference no longer supported. "
"see reference_as_filter parameter instead.")
elif self.data.params.assembly_method == "denovo+reference":
raise NotImplementedError(
"datatype + assembly_method combo not currently supported")
else:
raise NotImplementedError(
"datatype + assembly_method combo not currently supported")
# single-end methods ------------------------------------
else:
# DENOVO
if self.data.params.assembly_method == "denovo":
# TODO: add support for refminus, needs testing still...
# if self.data.params.reference_as_filter:
# # map reads to altref to get unmapped fastQ outputs
# # i: tmpdir/{}_R[1,2]-tmp.fa
# # o: tmpdir/{}-tmp-umap[1,2].FASTQ
# self.remote_run(
# function=mapping_reads,
# printstr=("mapping minus reads ", "s3"),
# args=(self.nthreads, 0,),
# threaded=True,
# )
# i: edits/{}_trimmed_R1.fastq # trimmed
# i: tmpdir/r1_concatedit.fastq # concat trimmed
# i: tmpdir/{}-tmp-umap1.fastq # " + refminus
# o: tmpdir/{}_derep.fa
self.remote_run(
function=dereplicate,
printstr=("dereplicating ", "s3"),
args=(self.nthreads,),
threaded=True,
)
self.remote_run_cluster_build()
self.remote_run_align_cleanup()
# REFERENCE
elif self.data.params.assembly_method == "reference":
self.remote_run(
function=dereplicate,
printstr=("dereplicating ", "s3"),
args=(self.nthreads,),
threaded=True,
)
self.remote_run(
function=mapping_reads,
printstr=("mapping reads ", "s3"),
args=(self.nthreads,),
threaded=True,
)
self.remote_run(
function=build_clusters_from_cigars,
printstr=("building clusters ", "s3"),
args=(),
)
else:
raise NotImplementedError(
"datatype + assembly_method combo not currently supported.")
self.remote_run_sample_cleanup()
self.cleanup()
def print_headers(self):
# print headers
if self.data._cli:
self.data._print(
"\n{}Step 3: Clustering/Mapping reads within samples"
.format(self.data._spacer)
)
def get_subsamples(self):
"Apply state, ncluster, and force filters to select samples"
# bail out if no samples ready
if not hasattr(self.data.stats, "state"):
raise IPyradError("No samples ready for step 3")
# filter samples by state
state1 = self.data.stats.index[self.data.stats.state < 2]
state2 = self.data.stats.index[self.data.stats.state == 2]
state3 = self.data.stats.index[self.data.stats.state > 2]
# tell user which samples are not ready for step 3
if state1.any():
self.data._print(
"skipping samples not yet in state==2:\n{}"
.format(state1.tolist()))
if self.force:
# run all samples above state 1
subs = self.data.stats.index[self.data.stats.state > 1]
subsamples = [self.data.samples[i] for i in subs]
else:
# tell user which samples have already cmopleted step 3
if state3.any():
self.data._print(
"skipping samples already finished step 3:\n{}"
.format(state3.tolist()))
# run all samples in state 2
subsamples = [self.data.samples[i] for i in state2]
# check that kept samples have clusters
checked_samples = []
for sample in subsamples:
if sample.stats.reads_passed_filter:
checked_samples.append(sample)
else:
self.data._print("skipping {}; no reads found.")
if not any(checked_samples):
raise IPyradError("No samples ready for step 3.")
# sort samples so the largest is first
checked_samples.sort(
key=lambda x: x.stats.reads_passed_filter,
reverse=True,
)
return checked_samples
def setup_dirs(self):
"setup directories for the tmp files and cluster/ref outputs"
# make output folder for clusters
pdir = os.path.realpath(self.data.params.project_dir)
self.data.dirs.clusts = os.path.join(
pdir, "{}_clust_{}"
.format(self.data.name, self.data.params.clust_threshold))
if not os.path.exists(self.data.dirs.clusts):
os.mkdir(self.data.dirs.clusts)
# make a tmpdir for align files
self.data.tmpdir = os.path.abspath(os.path.expanduser(
os.path.join(pdir, self.data.name + '-tmpalign')))
if os.path.exists(self.data.tmpdir):
shutil.rmtree(self.data.tmpdir)
if not os.path.exists(self.data.tmpdir):
os.mkdir(self.data.tmpdir)
# If ref mapping, init samples and make refmapping output directory
ref1 = self.data.params.reference_sequence
ref2 = self.data.params.reference_as_filter
if not (ref1 or ref2):
# warn if assembly_method is reference but no refseqs
if self.data.params.assembly_method == "reference":
print(
"Warning: using assembly_method=='reference' but no "
"reference_sequence or reference_as_filter parameters"
"wer set")
# set refmapping dir
if (ref1 or ref2):
self.data.dirs.refmapping = os.path.join(
pdir, "{}_refmapping".format(self.data.name))
if not os.path.exists(self.data.dirs.refmapping):
os.mkdir(self.data.dirs.refmapping)
# set a filepath for stored cluster results
for sname in self.data.samples:
self.data.samples[sname].files.clusters = os.path.join(
self.data.dirs.clusts,
"{}.clustS.gz".format(sname))
def tune_threads(self):
"setup threading to efficiently run clust/ref across HPC"
# set nthreads based on _ipcluster dict (default is 2)
if "threads" in self.data.ipcluster.keys():
self.nthreads = int(self.data.ipcluster["threads"])
# create standard load-balancers
self.lbview = self.ipyclient.load_balanced_view()
self.thview = self.ipyclient.load_balanced_view() # to be threaded
# if nthreads then scale thview to use threads
eids = self.ipyclient.ids
if self.nthreads:
if self.nthreads <= len(self.ipyclient.ids):
self.thview = self.ipyclient.load_balanced_view(
targets=eids[::self.nthreads])
# else try auto-tuning to 2 or 4 threaded
else:
if len(self.ipyclient) >= 40:
self.thview = self.ipyclient.load_balanced_view(
targets=eids[::4])
else:
self.thview = self.ipyclient.load_balanced_view(
targets=eids[::2])
def cleanup(self):
"cleanup / statswriting function for Assembly obj"
self.data.stats_dfs.s3 = self.data._build_stat("s3")
self.data.stats_files.s3 = os.path.join(
self.data.dirs.clusts, "s3_cluster_stats.txt")
with open(self.data.stats_files.s3, 'w') as outfile:
self.data.stats_dfs.s3.to_string(
buf=outfile,
formatters={
# 'merged_pairs': '{:.0f}'.format,
'clusters_total': '{:.0f}'.format,
'clusters_hidepth': '{:.0f}'.format,
'filtered_bad_align': '{:.0f}'.format,
'avg_depth_stat': '{:.2f}'.format,
'avg_depth_mj': '{:.2f}'.format,
'avg_depth_total': '{:.2f}'.format,
'sd_depth_stat': '{:.2f}'.format,
'sd_depth_mj': '{:.2f}'.format,
'sd_depth_total': '{:.2f}'.format,
'pcr_duplicate_reads': '{:.0f}'.format,
'pcr_duplicate_reads_prop': '{:.3f}'.format,
"refseq_mapped_reads": '{:.0f}'.format,
"refseq_mapped_reads_prop": '{:.3f}'.format,
# 'prop_pcr_duplicates': '{:.2f}'.format
})
# remove temporary alignment chunk and derep files
if os.path.exists(self.data.tmpdir):
shutil.rmtree(self.data.tmpdir)
def remote_index_refs(self):
"""
index the reference seq for bwa and samtools (pysam).
"""
logger.debug("indexing reference with bwa and samtools")
jobs = {}
if self.data.params.reference_sequence:
rasync1 = self.lbview.apply(index_ref_with_bwa, self.data)
rasync2 = self.lbview.apply(index_ref_with_sam, self.data)
jobs['bwa_index_ref'] = rasync1
jobs['sam_index_ref'] = rasync2
if self.data.params.reference_as_filter:
rasync1 = self.lbview.apply(index_ref_with_bwa, self.data, alt=1)
rasync2 = self.lbview.apply(index_ref_with_sam, self.data, alt=1)
jobs['bwa_index_alt'] = rasync1
jobs['sam_index_alt'] = rasync2
# track job
printstr = ("indexing reference ", "s3")
prog = AssemblyProgressBar(jobs, None, printstr, self.data)
prog.block()
prog.check()
def remote_run_cluster_build(self):
"""
submit clustering/mapping job
"""
start = time.time()
casyncs = {}
for sample in self.samples:
casyncs[sample.name] = self.thview.apply(
cluster,
*(self.data, sample, self.nthreads, self.force)
)
# submit cluster building job
basyncs = {}
for sample in self.samples:
with self.lbview.temp_flags(after=casyncs[sample.name]):
basyncs[sample.name] = self.lbview.apply(
build_clusters,
*(self.data, sample, self.maxindels)
)
# submit cluster chunking job
hasyncs = {}
for sample in self.samples:
with self.lbview.temp_flags(after=basyncs[sample.name]):
hasyncs[sample.name] = self.lbview.apply(
muscle_chunker,
*(self.data, sample)
)
# track job progress
printstr = ("clustering/mapping ", "s3")
prog = AssemblyProgressBar(casyncs, start, printstr, self.data)
prog.block()
prog.check()
# track job progress
start = time.time()
printstr = ("building clusters ", "s3")
prog = AssemblyProgressBar(basyncs, start, printstr, self.data)
prog.block()
prog.check()
# track job progress
start = time.time()
printstr = ("chunking clusters ", "s3")
prog = AssemblyProgressBar(hasyncs, start, printstr, self.data)
prog.block()
prog.check()
def remote_run_align_cleanup(self):
"""
submit ten aligning jobs for each sample
"""
start = time.time()
aasyncs = {}
for sample in self.samples:
aasyncs[sample.name] = []
for idx in range(10):
handle = os.path.join(
self.data.tmpdir,
"{}_chunk_{}.ali".format(sample.name, idx))
args = (
handle, self.maxindels, self.gbs,
self.data.hackersonly.declone_PCR_duplicates
)
rasync = self.lbview.apply(align_and_parse, *args)
aasyncs[sample.name].append(rasync)
# a list with all aasyncs concatenated
allasyncs = chain(*[aasyncs[i] for i in aasyncs])
allasyncs = dict(enumerate(allasyncs))
# submit cluster building job for each sample *after* all align jobs
basyncs = {}
for sample in self.samples:
with self.lbview.temp_flags(after=aasyncs[sample.name]):
rasync = self.lbview.apply(reconcat, *(self.data, sample))
basyncs[sample.name] = rasync
# track job 1 progress
printstr = ("aligning clusters ", "s3")
prog = AssemblyProgressBar(allasyncs, start, printstr, self.data)
prog.block()
prog.check()
# track job 2 progress
start = time.time()
printstr = ("concat clusters ", "s3")
prog = AssemblyProgressBar(basyncs, start, printstr, self.data)
prog.block()
prog.check()
# compile stats on highindel filteres, and duplicates
# if self.data.hackersonly.declone_PCR_duplicates:
# for sample in self.samples:
# # list of 3-tuples
# res = [i.get() for i in aasyncs[sample.name]]
# logger.debug("declone {} {}".format(sample.name, res))
# # count proportio of reads that are PCR duplicates
# nreads = [i[1] for i in res]
# nwodups = [i[2] for i in res]
# propdup = float(nwodups) / nreads
# sample.stats_dfs.s3["prop_pcr_duplicates"] = propdup
# logger.debug(
# "declone {} prop_pcr_duplicates={:.3f}"
# .format(sample.name, propdup))
def remote_run_sample_cleanup(self):
"""
Send samples to calc depths on remote, and then enter stats
to sample objects non-parallel.
"""
printstr = ("calc cluster stats ", "s3")
start = time.time()
rasyncs = {}
njobs = len(self.samples)
for sample in self.samples:
args = [self.data, sample]
rasyncs[sample.name] = self.lbview.apply(get_quick_depths, *args)
# enter result stats as the jobs finish
finished = 0
while 1:
samplelist = list(rasyncs.keys())
for sname in samplelist:
if rasyncs[sname].ready():
# enter results to sample object and checks for errors
maxlens, depths, counts = rasyncs[sname].get()
store_sample_stats(
self.data, self.data.samples[sname], maxlens, depths, counts)
finished += 1
# remove sample from todo list, and del from rasyncs mem
rasyncs.pop(sname)
# progress bar
self.data._progressbar(njobs, finished, start, printstr)
time.sleep(0.1)
if finished == njobs:
break
self.data._print("")
def remote_run(self, printstr, function, args, threaded=False):
"""
General remote distributor
"""
# submit job
start = time.time()
rasyncs = {}
for sample in self.samples:
fargs = [self.data, sample] + list(args)
if threaded:
rasyncs[sample.name] = self.thview.apply(function, *fargs)
else:
rasyncs[sample.name] = self.lbview.apply(function, *fargs)
# track job
prog = AssemblyProgressBar(rasyncs, start, printstr, self.data)
prog.block()
prog.check()
# clean up to free any RAM
self.ipyclient.purge_everything()
def dereplicate(data, sample, nthreads):
"""
Dereplicates reads and sorts so reads that were highly replicated are at
the top, and singletons at bottom, writes output to derep file. Paired
reads are dereplicated as one concatenated read and later split again.
Updated this function to take infile and outfile to support the double
dereplication that we need for 3rad (5/29/15 iao).
"""
logger.debug("dereplicating: {}".format(sample.name))
# find input file with following precedence:
# .trimmed.fastq.gz, .concatedit.fq.gz, ._merged.fastq, ._declone.fastq
infiles = [
os.path.join(
data.dirs.edits,
"{}.trimmed_R1_.fastq.gz".format(sample.name)),
os.path.join(
data.tmpdir,
"{}_R1_concatedit.fq.gz".format(sample.name)),
os.path.join(
data.tmpdir,
"{}_merged.fastq".format(sample.name)),
os.path.join(
data.tmpdir,
"{}_declone.fastq".format(sample.name)),
]
infiles = [i for i in infiles if os.path.exists(i)]
infile = infiles[-1]
# datatypes options
strand = "plus"
if data.params.datatype in ['gbs', '2brad']:
strand = "both"
# do dereplication with vsearch
cmd = [
ip.bins.vsearch,
"--derep_fulllength", infile,
"--strand", strand,
"--output", os.path.join(data.tmpdir, sample.name + "_derep.fa"),
"--fasta_width", str(0),
"--minseqlength", str(data.params.filter_min_trim_len),
"--sizeout",
"--relabel_md5",
"--quiet",
# "--threads", str(nthreads),
#"--fastq_qmax", "1000",
]
# decompress argument (IF ZLIB is missing this will not work!!)
# zlib is part of the conda installation.
if infile.endswith(".gz"):
cmd.append("--gzip_decompress")
# build PIPEd job
proc = sps.Popen(cmd, stderr=sps.STDOUT, stdout=sps.PIPE, close_fds=True)
errmsg = proc.communicate()[0]
if proc.returncode:
raise IPyradError(errmsg.decode())
def concat_multiple_edits(data, sample):
"""
Create a temporary concatenated file for multiple edits input
files, which arises when Assemblies were merged between steps
2 and 3.
"""
# define output files
concat1 = os.path.join(
data.tmpdir,
"{}_R1_concatedit.fq.gz".format(sample.name))
concat2 = os.path.join(
data.tmpdir,
"{}_R2_concatedit.fq.gz".format(sample.name))
# check for files to concat
if len(sample.files.edits) > 1:
# cat all inputs; index 0 b/c files are in tuples for r1, r2
cmd1 = ["cat"] + [i[0] for i in sample.files.edits]
# write to new concat handle
with open(concat1, 'w') as cout1:
proc1 = sps.Popen(
cmd1, stderr=sps.STDOUT, stdout=cout1, close_fds=True)
res1 = proc1.communicate()[0]
if proc1.returncode:
raise IPyradError("error in: {} {}".format(cmd1, res1))
# Only set conc2 if R2 actually exists
if os.path.exists(str(sample.files.edits[0][1])):
cmd2 = ["cat"] + [i[1] for i in sample.files.edits]
with gzip.open(concat2, 'w') as cout2:
proc2 = sps.Popen(
cmd2, stderr=sps.STDOUT, stdout=cout2, close_fds=True)
res2 = proc2.communicate()[0]
if proc2.returncode:
raise IPyradError("error in: {} {}".format(cmd2, res2))
def merge_pairs_with_vsearch(data, sample):
"""
Merge PE reads using vsearch to find overlap.
"""
logger.debug("merging pairs: {}".format(sample.name))
# input files (select only the top one)
in1 = [
os.path.join(data.tmpdir, "{}-tmp-umap1.fastq".format(sample.name)),
os.path.join(data.tmpdir, "{}_R1_concatedit.fq.gz".format(sample.name)),
sample.files.edits[0][0],
]
in2 = [
os.path.join(data.tmpdir, "{}-tmp-umap2.fastq".format(sample.name)),
os.path.join(data.tmpdir, "{}_R2_concatedit.fq.gz".format(sample.name)),
sample.files.edits[0][1],
]
index = min([i for i, j in enumerate(in1) if os.path.exists(j)])
infile1 = in1[index]
infile2 = in2[index]
# define output files
mergedfile = os.path.join(
data.tmpdir,
"{}_merged.fastq".format(sample.name))
nonmerged1 = os.path.join(
data.tmpdir,
"{}_nonmerged_R1_.fastq".format(sample.name))
nonmerged2 = os.path.join(
data.tmpdir,
"{}_nonmerged_R2_.fastq".format(sample.name))
# get the maxn and minlen values
try:
maxn = sum(data.params.max_low_qual_bases)
except TypeError:
maxn = data.params.max_low_qual_bases
minlen = str(max(32, data.params.filter_min_trim_len))
# vsearch merge can now take gzipped files (v.2.8)
cmd = [
ip.bins.vsearch,
"--fastq_mergepairs", infile1,
"--reverse", infile2,
"--fastqout", mergedfile,
"--fastqout_notmerged_fwd", nonmerged1,
"--fastqout_notmerged_rev", nonmerged2,
"--fasta_width", "0",
"--fastq_minmergelen", minlen,
"--fastq_maxns", str(maxn),
"--fastq_minovlen", "20",
"--fastq_maxdiffs", "4",
"--label_suffix", "_m1",
"--fastq_qmax", "93", # <- Set high to allow FASTQ+64
"--threads", "2",
"--fastq_allowmergestagger",
]
proc = sps.Popen(cmd, stderr=sps.STDOUT, stdout=sps.PIPE)
res = proc.communicate()[0].decode()
if proc.returncode:
logger.exception(res)
raise IPyradError("Error merge pairs:\n {}\n{}".format(cmd, res))
def merge_end_to_end(data, sample, revcomp, append, identical=False):
"""
Combines read1 and read2 with a 'nnnn' separator. If the data are going
to be refmapped then do not revcomp the read2.
Parameters:
----------
identical (bool):
*only for paired denovo refminus*
It will split paired reads that have already been
merged by vsearch. In this case it does not split them, but just uses
the full seq as both R1 and R2. When joining them back we will join
other reads with nnnn, but if R1 and R2 are identical then we keep
just the R1 as the merged readpair.
"""
logger.debug("join unmerged pairs end-to-end: {}".format(sample.name))
# input files;
if identical:
mergedfile = os.path.join(
data.tmpdir,
"{}_remerged.fa".format(sample.name))
else:
mergedfile = os.path.join(
data.tmpdir,
"{}_merged.fastq".format(sample.name))
# input file options
altmapped1 = os.path.join(
data.tmpdir,
"{}-tmp-umap1.fastq".format(sample.name))
altmapped2 = os.path.join(
data.tmpdir,
"{}-tmp-umap2.fastq".format(sample.name))
nonmerged1 = os.path.join(
data.tmpdir,
"{}_nonmerged_R1_.fastq".format(sample.name))
nonmerged2 = os.path.join(
data.tmpdir,
"{}_nonmerged_R2_.fastq".format(sample.name))
concat1 = os.path.join(
data.tmpdir,
"{}_R1_concatedit.fq.gz".format(sample.name))
concat2 = os.path.join(
data.tmpdir,
"{}_R2_concatedit.fq.gz".format(sample.name))
# data.dirs.edits doesn't exist if you merge after step 2, so
# here we access the edits files through the sample object.
# Sorry it makes the code less harmonious. iao 12/31/19.
edits1 = sample.files.edits[0][0]
edits2 = sample.files.edits[0][1]
# file precedence
order1 = (edits1, concat1, nonmerged1, altmapped1)
order2 = (edits2, concat2, nonmerged2, altmapped2)
nonm1 = [i for i in order1 if os.path.exists(i)][-1]
nonm2 = [i for i in order2 if os.path.exists(i)][-1]
# Combine the unmerged pairs and append to the merge file
if append:
combout = open(mergedfile, 'a')
else:
combout = open(mergedfile, 'w')
# read in paired end read files 4 lines at a time
if nonm1.endswith(".gz"):
fr1 = gzip.open(nonm1, 'rb')
else:
fr1 = open(nonm1, 'rb')
quart1 = izip(*[iter(fr1)] * 4)
if nonm2.endswith(".gz"):
fr2 = gzip.open(nonm2, 'rb')
else:
fr2 = open(nonm2, 'rb')
quart2 = izip(*[iter(fr2)] * 4)
quarts = izip(quart1, quart2)
# a list to store until writing
writing = []
counts = 0
# iterate until done
while 1:
try:
read1s, read2s = next(quarts)
except StopIteration:
break
# [paired-denovo-refminus option] do not join truly merged reads
if identical:
# keep already merged r1 and the read, or combine with nnnn
if read1s[1] == read2s[1]:
newread = [
b">" + read1s[0][1:],
read1s[1],
]
else:
newread = [
b">" + read1s[0][1:],
read1s[1].strip() + b"nnnn" + read2s[1].strip() + b"\n",
]
writing.append(b"".join(newread))
# the standard pipeline
else:
# revcomp for denovo data
if revcomp:
writing.append(b"".join([
read1s[0],
read1s[1].strip() + b"nnnn" + (
bcomp(read2s[1].strip()[::-1]) + b"\n"),
read1s[2],
read1s[3].strip() + b"nnnn" + (
read2s[3].strip()[::-1] + b"\n"),
]))
# no revcomp for reference mapped data
else:
writing.append(b"".join([
read1s[0],
read1s[1].strip() + b"nnnn" + (
read2s[1]),
read1s[2],
read1s[3].strip() + b"nnnn" + (
read2s[3]),
]))
# keep count
counts += 1
if not counts % 5000:
combout.write(b"".join(writing).decode())
writing = []
if writing:
combout.write(b"".join(writing).decode())
# close handles
fr1.close()
fr2.close()
combout.close()
def count_merged_reads(data, sample):
"""
record how many read pairs were merged
"""
mergedfile = os.path.join(
data.tmpdir,
"{}_merged.fastq".format(sample.name))
with open(mergedfile, 'r') as tmpf:
nmerged = sum(1 for i in tmpf.readlines()) // 4
return nmerged