/
write_outputs.py
2764 lines (2289 loc) · 96.5 KB
/
write_outputs.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
# py2/3 compatibility
from __future__ import print_function
try:
from builtins import range, bytes
from itertools import izip, chain
except ImportError:
from itertools import chain
izip = zip
# standard lib imports
import os
import glob
import time
import shutil
import pickle
from collections import Counter
# third party imports
import numpy as np
import pandas as pd
import ipyrad
from numba import njit
from .utils import IPyradError, clustdealer, splitalleles, chroms2ints
from .utils import BTS, GETCONS, DCONS # , bcomp
# suppress the terrible h5 warning
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
import h5py
# classes
class Step7:
def __init__(self, data, force, ipyclient):
self.data = data
self.force = force
self.ipyclient = ipyclient
self.lbview = self.ipyclient.load_balanced_view()
self.data.isref = bool("ref" in self.data.params.assembly_method)
self.data.ispair = bool("pair" in self.data.params.datatype)
# returns samples in the order we want them in the outputs
self.print_headers()
self.samples = self.get_subsamples()
self.setup_dirs()
self.get_chunksize()
# dict mapping of samples to padded names for loci file aligning.
self.data.snames = [i.name for i in self.samples]
self.data.pnames, self.data.snppad = self.get_padded_names()
# output file formats to produce ('l' is required).
self.formats = set(['l']).union(
set(self.data.params.output_formats))
def run(self):
# split clusters into bits.
self.split_clusters()
# get filter and snp info on edge trimmed data.
# write to chunks for building output files and save dimensions.
self.remote_process_chunks()
# write stats file while counting nsnps and nbases.
self.collect_stats()
self.store_file_handles()
# write loci and alleles outputs (parallelized on 3 engines)
self.remote_build_arrays_and_write_loci()
# send conversion jobs from array files to engines
self.remote_write_outfiles()
# send jobs to build vcf
if 'v' in self.formats:
# throttle job to avoid memory errors based on catg size
self.remote_fill_depths()
self.remote_build_vcf()
# cleanup
if os.path.exists(self.data.tmpdir):
shutil.rmtree(self.data.tmpdir)
def print_headers(self):
if self.data._cli:
self.data._print(
"\n{}Step 7: Filtering and formatting output files "
.format(self.data._spacer)
)
def get_subsamples(self):
"get subsamples for this assembly. All must have been in step6"
# bail out if no samples ready
if not hasattr(self.data.stats, "state"):
raise IPyradError("No samples ready for step 7")
# get samples from the database file
if not os.path.exists(self.data.clust_database):
raise IPyradError("You must first complete step6.")
with open(self.data.clust_database, 'r') as inloci:
dbsamples = inloci.readline()[1:].strip().split(",@")
# samples are in this assembly but not database (raise error)
nodb = set(self.data.samples).difference(set(dbsamples))
if nodb:
raise IPyradError(MISSING_SAMPLE_IN_DB.format(nodb))
# samples in database not in this assembly, that's OK, you probably
# branched to drop some samples.
# samples in populations file that are not in this assembly. Raise
# an error, it's probably a typo and should be corrected.
poplists = [i[1] for i in self.data.populations.values()]
popset = set(chain(*poplists))
badpop = popset.difference(set(self.data.samples))
if badpop:
raise IPyradError(BADPOP_SAMPLES.format(badpop))
# output files already exist for this assembly. Raise
# error unless using the force flag to prevent overwriting.
if not self.force:
_outdir = os.path.join(
self.data.params.project_dir,
"{}_outfiles".format(self.data.name),
)
_outdir = os.path.realpath(_outdir)
if os.path.exists(os.path.join(_outdir,
"{}.loci".format(self.data.name),
)):
raise IPyradError(
"Step 7 results exist for this Assembly. Use force to overwrite.")
# if ref init a new sample for reference if including
if self.data.params.assembly_method == 'reference':
ref = ipyrad.core.sample.Sample("reference")
samples = [ref] + sorted(
list(set(self.data.samples.values())),
key=lambda x: x.name)
return samples
else:
samples = sorted(
list(set(self.data.samples.values())),
key=lambda x: x.name)
return samples
def setup_dirs(self):
"Create temp h5 db for storing filters and depth variants"
# reset outfiles paths
for key in self.data.outfiles:
self.data.outfiles[key] = ""
# make new output directory
self.data.dirs.outfiles = os.path.join(
self.data.params.project_dir,
"{}_outfiles".format(self.data.name),
)
self.data.dirs.outfiles = os.path.realpath(self.data.dirs.outfiles)
if os.path.exists(self.data.dirs.outfiles):
shutil.rmtree(self.data.dirs.outfiles)
if not os.path.exists(self.data.dirs.outfiles):
os.makedirs(self.data.dirs.outfiles)
# stats output handle
self.data.stats_files.s7 = os.path.abspath(
os.path.join(
self.data.dirs.outfiles,
"{}_stats.txt".format(self.data.name),
)
)
# make tmpdir directory
self.data.tmpdir = os.path.join(
self.data.dirs.outfiles,
"tmpdir",
)
if os.path.exists(self.data.tmpdir):
shutil.rmtree(self.data.tmpdir)
if not os.path.exists(self.data.tmpdir):
os.makedirs(self.data.tmpdir)
# make new database files
self.data.seqs_database = os.path.join(
self.data.dirs.outfiles,
self.data.name + ".seqs.hdf5",
)
self.data.snps_database = os.path.join(
self.data.dirs.outfiles,
self.data.name + ".snps.hdf5",
)
for dbase in [self.data.snps_database, self.data.seqs_database]:
if os.path.exists(dbase):
os.remove(dbase)
def get_chunksize(self):
"get nloci and ncpus to chunk and distribute work across processors"
# this file is inherited from step 6 to allow step7 branching.
with open(self.data.clust_database, 'r') as inloci:
# skip header
inloci.readline()
# get nraw loci
self.nraws = sum(1 for i in inloci if i == "//\n") // 2
# chunk to approximately 4 chunks per core
self.ncpus = len(self.ipyclient.ids)
self.chunksize = sum([
(self.nraws // (self.ncpus * 4)),
(self.nraws % (self.ncpus * 4)),
])
def get_padded_names(self):
# get longest name
longlen = max(len(i) for i in self.data.snames)
# Padding distance between name and seq.
padding = 5
# add pad to names
pnames = {
name: "{}{}".format(name, " " * (longlen - len(name) + padding))
for name in self.data.snames
}
snppad = "//" + " " * (longlen - 2 + padding)
return pnames, snppad
def store_file_handles(self):
# always produce a .loci file + whatever they ask for.
testformats = list(self.formats)
for outf in testformats:
# if it requires a pop file and they don't have one then skip
# and write the warning to the expected file, to prevent an
# annoying message every time if you don't have a pops file, but
# still to be transparent about skipping some files. This caused
# me some real amount of pain, like "why isnt' the treemix file
# being created, fudkckkk!!!1" And then like 10 minutes later, oh
# yeah, no pops file, fml. 3/2020 iao.
if (outf in ("t", "m")) and (not self.data.populations):
outfile = os.path.join(
self.data.dirs.outfiles,
self.data.name + OUT_SUFFIX[outf][0])
with open(outfile, 'w') as out:
out.write(POPULATION_REQUIRED.format(outf))
# remove format from the set
self.formats.discard(outf)
continue
else:
# store handle to data object
for ending in OUT_SUFFIX[outf]:
# store
self.data.outfiles[ending[1:]] = os.path.join(
self.data.dirs.outfiles,
self.data.name + ending)
def collect_stats(self):
"Collect results from Processor and write stats file."
# organize stats into dataframes
ftable = pd.DataFrame(
columns=["total_filters", "applied_order", "retained_loci"],
index=[
"total_prefiltered_loci",
"filtered_by_rm_duplicates",
"filtered_by_max_indels",
"filtered_by_max_SNPs",
"filtered_by_max_shared_het",
"filtered_by_min_sample", # "filtered_by_max_alleles",
"total_filtered_loci"],
)
# load pickled dictionaries into a dict
pickles = glob.glob(os.path.join(self.data.tmpdir, "*.p"))
pdicts = {}
for pkl in pickles:
with open(pkl, 'rb') as inp:
pdicts[pkl.rsplit("-", 1)[-1][:-2]] = pickle.load(inp)
# join dictionaries into global stats
afilts = np.concatenate([i['filters'] for i in pdicts.values()])
lcovs = Counter({})
scovs = Counter({})
cvar = Counter({})
cpis = Counter({})
nbases = 0
for lcov in [i['lcov'] for i in pdicts.values()]:
lcovs.update(lcov)
for scov in [i['scov'] for i in pdicts.values()]:
scovs.update(scov)
for var in [i['var'] for i in pdicts.values()]:
cvar.update(var)
for pis in [i['pis'] for i in pdicts.values()]:
cpis.update(pis)
for count in [i['nbases'] for i in pdicts.values()]:
nbases += count
# make into nice DataFrames
ftable.iloc[0, :] = (0, 0, self.nraws)
# filter rm dups
ftable.iloc[1, 0:2] = afilts[:, 0].sum()
ftable.iloc[1, 2] = ftable.iloc[0, 2] - ftable.iloc[1, 1]
mask = afilts[:, 0]
# filter max indels
ftable.iloc[2, 0] = afilts[:, 1].sum()
ftable.iloc[2, 1] = afilts[~mask, 1].sum()
ftable.iloc[2, 2] = ftable.iloc[1, 2] - ftable.iloc[2, 1]
mask = afilts[:, 0:2].sum(axis=1).astype(np.bool)
# filter max snps
ftable.iloc[3, 0] = afilts[:, 2].sum()
ftable.iloc[3, 1] = afilts[~mask, 2].sum()
ftable.iloc[3, 2] = ftable.iloc[2, 2] - ftable.iloc[3, 1]
mask = afilts[:, 0:3].sum(axis=1).astype(np.bool)
# filter max shared H
ftable.iloc[4, 0] = afilts[:, 3].sum()
ftable.iloc[4, 1] = afilts[~mask, 3].sum()
ftable.iloc[4, 2] = ftable.iloc[3, 2] - ftable.iloc[4, 1]
mask = afilts[:, 0:4].sum(axis=1).astype(np.bool)
# filter minsamp
ftable.iloc[5, 0] = afilts[:, 4].sum()
ftable.iloc[5, 1] = afilts[~mask, 4].sum()
ftable.iloc[5, 2] = ftable.iloc[4, 2] - ftable.iloc[5, 1]
mask = afilts[:, 0:4].sum(axis=1).astype(np.bool)
ftable.iloc[6, 0] = ftable.iloc[:, 0].sum()
ftable.iloc[6, 1] = ftable.iloc[:, 1].sum()
ftable.iloc[6, 2] = ftable.iloc[5, 2]
# save stats to the data object
self.data.stats_dfs.s7_filters = ftable
self.data.stats_dfs.s7_samples = pd.DataFrame(
pd.Series(scovs, name="sample_coverage"))
## get locus cov and sums
lrange = range(1, len(self.samples) + 1)
covs = pd.Series(lcovs, name="locus_coverage", index=lrange)
start = self.data.params.min_samples_locus - 1
sums = pd.Series(
{i: np.sum(covs[start:i]) for i in lrange},
name="sum_coverage",
index=lrange)
self.data.stats_dfs.s7_loci = pd.concat([covs, sums], axis=1)
# fill pis to match var
for i in cvar:
if not cpis.get(i):
cpis[i] = 0
## get SNP distribution
sumd = {}
sump = {}
for i in range(max(cvar.keys()) + 1):
sumd[i] = np.sum([i * cvar[i] for i in range(i + 1)])
sump[i] = np.sum([i * cpis[i] for i in range(i + 1)])
self.data.stats_dfs.s7_snps = pd.concat([
pd.Series(cvar, name="var"),
pd.Series(sumd, name="sum_var"),
pd.Series(cpis, name="pis"),
pd.Series(sump, name="sum_pis"),
],
axis=1
)
# trim SNP distribution to exclude unobserved endpoints
snpmax = np.where(
np.any(
self.data.stats_dfs.s7_snps.loc[:, ["var", "pis"]] != 0, axis=1
)
)[0]
if snpmax.size:
snpmax = snpmax.max()
self.data.stats_dfs.s7_snps = (
self.data.stats_dfs.s7_snps.loc[:snpmax])
## store dimensions for array building
self.nloci = ftable.iloc[6, 2]
self.nbases = nbases
self.nsnps = self.data.stats_dfs.s7_snps["sum_var"].max()
self.ntaxa = len(self.samples)
# write to file
with open(self.data.stats_files.s7, 'w') as outstats:
print(STATS_HEADER_1, file=outstats)
self.data.stats_dfs.s7_filters.to_string(buf=outstats)
print(STATS_HEADER_2, file=outstats)
self.data.stats_dfs.s7_samples.to_string(buf=outstats)
print(STATS_HEADER_3, file=outstats)
self.data.stats_dfs.s7_loci.to_string(buf=outstats)
print(STATS_HEADER_4, file=outstats)
self.data.stats_dfs.s7_snps.to_string(buf=outstats)
print("\n\n\n## Final Sample stats summary", file=outstats)
statcopy = self.data.stats.copy()
statcopy.state = 7
statcopy['loci_in_assembly'] = self.data.stats_dfs.s7_samples
statcopy.to_string(buf=outstats)
print("\n\n\n## Alignment matrix statistics:", file=outstats)
# bail out here if no loci were found
if not self.nloci:
raise IPyradError("No loci passed filters.")
def split_clusters(self):
with open(self.data.clust_database, 'rb') as clusters:
# skip header
clusters.readline()
# build iterator
pairdealer = izip(*[iter(clusters)] * 2)
# grab a chunk of clusters
idx = 0
while 1:
# if an engine is available pull off a chunk
try:
done, chunk = clustdealer(pairdealer, self.chunksize)
except IndexError:
raise IPyradError(
"clust_database formatting error in %s", chunk)
# write to tmpdir and increment counter
if chunk:
chunkpath = os.path.join(
self.data.tmpdir,
"chunk-{}".format(idx),
)
with open(chunkpath, 'wb') as outfile:
outfile.write(b"//\n//\n".join(chunk))
idx += 1
# break on final chunk
if done:
break
def remote_process_chunks(self):
"""
Calls process_chunk() function in parallel.
"""
start = time.time()
printstr = ("applying filters ", "s7")
rasyncs = {}
jobs = glob.glob(os.path.join(self.data.tmpdir, "chunk-*"))
jobs = sorted(jobs, key=lambda x: int(x.rsplit("-")[-1]))
for jobfile in jobs:
args = (self.data, self.chunksize, jobfile)
rasyncs[jobfile] = self.lbview.apply(process_chunk, *args)
# iterate until all chunks are processed
while 1:
# get and enter results into hdf5 as they come in
ready = [rasyncs[i].ready() for i in rasyncs]
self.data._progressbar(len(ready), sum(ready), start, printstr)
time.sleep(0.5)
if len(ready) == sum(ready):
self.data._print("")
break
# write stats
for job in rasyncs:
if not rasyncs[job].successful():
rasyncs[job].get()
def remote_build_arrays_and_write_loci(self):
"""
Calls write_loci_and_alleles(), fill_seq_array() and fill_snp_array().
"""
# start loci concatenating job on a remote
start = time.time()
printstr = ("building arrays ", "s7")
rasyncs = {}
args1 = (self.data, self.ntaxa, self.nbases, self.nloci)
args2 = (self.data, self.ntaxa, self.nsnps)
# print(self.nbases)
# fill with filtered loci chunks from Processor
rasyncs[0] = self.lbview.apply(write_loci_and_alleles, self.data)
rasyncs[1] = self.lbview.apply(fill_seq_array, *args1)
# fill with filtered loci chunks but also applies min_samples_SNP
rasyncs[2] = self.lbview.apply(fill_snp_array, *args2)
# track progress.
while 1:
ready = [rasyncs[i].ready() for i in rasyncs]
self.data._progressbar(len(ready), sum(ready), start, printstr)
time.sleep(0.5)
if len(ready) == sum(ready):
self.data._print("")
break
# check for errors
for job in rasyncs:
if not rasyncs[job].successful():
rasyncs[job].get()
def remote_write_outfiles(self):
"""
Calls convert_outputs() in parallel.
"""
start = time.time()
printstr = ("writing conversions ", "s7")
rasyncs = {}
for outf in self.formats:
rasyncs[outf] = self.lbview.apply(
convert_outputs, *(self.data, outf))
# iterate until all chunks are processed
while 1:
ready = [rasyncs[i].ready() for i in rasyncs]
self.data._progressbar(len(ready), sum(ready), start, printstr)
time.sleep(0.5)
if len(ready) == sum(ready):
self.data._print("")
break
# write stats
for job in rasyncs:
if not rasyncs[job].successful():
try:
rasyncs[job].get()
except Exception as inst:
# Allow one file to fail without breaking all step 7
# but print out the error and some info
print(inst)
def remote_fill_depths(self):
"""
Call fill_vcf_depths() in parallel.
"""
start = time.time()
printstr = ("indexing vcf depths ", "s7")
rasyncs = {}
for sample in self.data.samples.values():
if not sample.name == "reference":
rasyncs[sample.name] = self.lbview.apply(
fill_vcf_depths, *(self.data, self.nsnps, sample))
# iterate until all chunks are processed
while 1:
ready = [rasyncs[i].ready() for i in rasyncs]
self.data._progressbar(len(ready), sum(ready), start, printstr)
time.sleep(0.5)
if len(ready) == sum(ready):
self.data._print("")
break
# write stats
for job in rasyncs:
if not rasyncs[job].successful():
rasyncs[job].get()
def remote_build_vcf(self):
"""
Calls build_vcf() in parallel.
"""
start = time.time()
printstr = ("writing vcf output ", "s7")
rasync = self.lbview.apply(build_vcf, self.data)
# iterate until all chunks are processed
while 1:
ready = rasync.ready()
self.data._progressbar(1, ready, start, printstr)
time.sleep(0.5)
if ready:
self.data._print("")
break
# write stats
if not rasync.successful():
rasync.get()
# ------------------------------------------------------------
# Classes initialized and run on remote engines.
# ------------------------------------------------------------
def process_chunk(data, chunksize, chunkfile):
# process chunk writes to files and returns proc with features.
proc = Processor(data, chunksize, chunkfile)
proc.run()
# check for variants or set max to 0
try:
mvar = max([i for i in proc.var if proc.var[i]])
except ValueError:
mvar = 0
try:
mpis = max([i for i in proc.pis if proc.pis[i]])
except ValueError:
mpis = 0
# shorten dictionaries
proc.var = {i: j for (i, j) in proc.var.items() if i <= mvar}
proc.pis = {i: j for (i, j) in proc.pis.items() if i <= mpis}
# write process stats to a pickle file for collating later.
# We have to write stats for each process, even if it returns
# no loci in order for the filtering stats to make sense.
# https://github.com/dereneaton/ipyrad/issues/358
out = {
"filters": proc.filters,
"lcov": proc.lcov,
"scov": proc.scov,
"var": proc.var,
"pis": proc.pis,
"nbases": proc.nbases
}
with open(proc.outpickle, 'wb') as outpickle:
pickle.dump(out, outpickle)
##############################################################
class Processor(object):
def __init__(self, data, chunksize, chunkfile):
"""
Takes a chunk of aligned loci and (1) applies filters to it;
(2) gets edges, (3) builds snpstring, (4) returns chunk and stats.
(5) writes
"""
# init data
self.data = data
self.chunksize = chunksize
self.chunkfile = chunkfile
self.isref = self.data.isref
self.ispair = self.data.ispair
self.minsamp = self.data.params.min_samples_locus
# Minsamp is calculated _before_ the reference sequence is removed
# and so if we want the minsamp param to be honored as it is written
# in the params file we need to _add_ 1 to the value, so that when
# the ref is excluded the minsamp value will be accurate.
# If the ref is _included_ then it counts toward minsample and no
# adjustment is necessary.
if self.isref:
if self.data.hackersonly.exclude_reference:
self.minsamp += 1
# filters (dups, minsamp, maxind, maxall, maxvar, maxshared)
self.filters = np.zeros((self.chunksize, 5), dtype=np.bool_)
self.filterlabels = (
'dups',
'maxind',
'maxvar',
'maxshared',
'minsamp',
)
# (R1>, <R1, R2>, <R2)
self.edges = np.zeros((self.chunksize, 4), dtype=np.uint16)
# check filter settings
self.fmaxsnps = self.data.params.max_SNPs_locus
if isinstance(self.fmaxsnps, tuple):
self.fmaxsnps = self.fmaxsnps[0]
if isinstance(self.fmaxsnps, int):
self.fmaxsnps = 0.10 # backwards compatibility make as a float
self.fmaxhet = self.data.params.max_shared_Hs_locus
if isinstance(self.fmaxhet, tuple):
self.fmaxhet = self.fmaxhet[0]
# TODO: This backwards compatibility is hard coded. Maybe better to
# just raise an error here, or really during parsing of the params
# file is best.
if isinstance(self.fmaxhet, int):
self.fmaxhet = 0.5 # backwards compatibility make as a float
self.maxinds = self.data.params.max_Indels_locus
if isinstance(self.maxinds, tuple):
self.maxinds = self.maxinds[0] # backwards compatibility
# store stats on sample coverage and locus coverage
self.scov = {i: 0 for i in self.data.snames}
self.lcov = {i: 0 for i in range(1, len(self.data.snames) + 1)}
self.var = {i: 0 for i in range(5000)}
self.pis = {i: 0 for i in range(5000)}
self.nbases = 0
# tmp outfile list and filename
self.outlist = []
self.outfile = self.chunkfile + '.loci'
self.outpickle = self.chunkfile + '.p'
self.outarr = self.chunkfile + '.npy'
# open a generator to the chunks
self.io = open(self.chunkfile, 'rb')
self.loci = enumerate(iter(self.io.read().split(b"//\n//\n")))
# filled in each chunk
self.names = []
self.nidxs = []
self.aseqs = []
self.useqs = []
def next_locus(self):
self.names = []
self.nidxs = []
self.aseqs = []
self.useqs = []
# advance locus to next, parse names and seqs
self.iloc, lines = next(self.loci)
lines = lines.decode().strip().split("\n")
for line in lines:
if line[0] == ">":
name, nidx = line[1:].rsplit("_", 1)
self.names.append(name)
self.nidxs.append(nidx)
else:
self.aseqs.append(list(bytes(line.encode())))
self.useqs.append(list(bytes(line.upper().encode())))
# filter to include only samples in this assembly
mask = np.array([i in self.data.snames for i in self.names])
self.names = np.array(self.names)[mask].tolist()
if not self.filter_dups():
# [ref] store consens read start position as mapped to ref
self.nidxs = np.array(self.nidxs)[mask].tolist()
self.useqs = np.array(self.useqs)[mask, :].astype(np.uint8)
self.aseqs = np.array(self.aseqs)[mask, :].astype(np.uint8)
def run(self):
# iterate through loci in the chunk
while 1:
try:
self.next_locus()
except StopIteration:
break
# fill filter 0
if self.filter_dups():
continue
# apply filters
edges = Edges(self.data, self.useqs)
edges.get_edges()
self.edges[self.iloc] = edges.edges
# fill filter 4
self.filter_minsamp_pops()
self.filters[self.iloc, 4] += int(edges.bad)
# trim edges, need to use uppered seqs for maxvar & maxshared
edg = self.edges[self.iloc]
ublock = self.useqs[:, edg[0]:edg[3]]
ablock = self.aseqs[:, edg[0]:edg[3]]
# filter if are any empty samples after trimming
self.filters[self.iloc, 4] += np.sum(np.all(ublock == 45, axis=1))
# bail out of locus now if it is already bad...
if self.filters[self.iloc].sum():
continue
# [denovo]: store shift of left edge start position from
# alignment, this position is needed for pulling depths in VCF.
# [ref]: nidx string will be updated in to_locus() with edg
self.masked = None
if not self.isref:
# what is the leftmost consens edge (not -)
ishift = [
np.where(self.aseqs[i] != 45)[0].min()
for i in range(self.aseqs.shape[0])
]
# fill nidxs with nidxs and shift info
inidxs = []
for idx, (i, j) in enumerate(zip(self.nidxs, ishift)):
# add to ishift if trimmed region contains indels
indshift = (self.aseqs[idx, j:edges.edges[0]] == 45).size
inidxs.append("{}-{}".format(i, j + indshift))
self.nidxs = inidxs
# mask insert in denovo data
self.aseqs[:, edges.edges[1]:edges.edges[2]] = 110 # n
self.useqs[:, edges.edges[1]:edges.edges[2]] = 78 # N
# for is-ref we need to mask the insert between pairs
else:
if self.ispair and self.data.params.min_samples_locus > 1:
inserts = np.all(ublock[1:, :] == 78, axis=0)
self.masked = ublock[:, np.invert(inserts)]
# apply filters on edge trimmed reads
self.filter_maxindels(ublock)
# get snpstring on trimmed reads
if self.isref and self.data.hackersonly.exclude_reference:
snparr = self.get_snpsarrs(ublock, True)
else:
snparr = self.get_snpsarrs(ublock)
self.filter_maxvars(ublock, snparr)
# apply filters on edge trimmed reads
self.filter_maxshared(ublock)
# store stats for the locus that passed filtering
if not self.filters[self.iloc, :].sum():
# do sample and locus counters
for name in self.names:
self.scov[name] += 1
# advance locus counter
if self.isref and self.data.hackersonly.exclude_reference:
self.lcov[self.useqs.shape[0] - 1] += 1
else:
self.lcov[self.useqs.shape[0]] += 1
# do SNP distribution counter
if self.masked is None:
self.nbases += ublock.shape[1]
else:
self.nbases += self.masked.shape[1]
self.var[snparr[:, :].sum()] += 1
self.pis[snparr[:, 1].sum()] += 1
# write to .loci string
locus = self.to_locus(ablock, snparr, edg)
self.outlist.append(locus)
# If no loci survive filtering then don't write the files
if np.fromiter(self.lcov.values(), dtype=int).sum() > 0:
# write the chunk to tmpdir
with open(self.outfile, 'w') as outchunk:
outchunk.write("\n".join(self.outlist) + "\n")
# thin edgelist to filtered loci and write to array
mask = np.invert(self.filters.sum(axis=1).astype(np.bool_))
np.save(self.outarr, self.edges[mask, 0])
# close file handle
self.io.close()
def to_locus(self, block, snparr, edg):
"write chunk to a loci string"
# store as a list
locus = []
# convert snparrs to snpstrings
snpstring = "".join([
"-" if snparr[i, 0] else "*" if snparr[i, 1] else " "
for i in range(len(snparr))
])
# get nidx string for getting vcf depths to match SNPs
if self.isref:
# get ref position from nidxs
refpos = ":".join(self.nidxs[0].rsplit(":", 2)[-2:])
# trim ref position string for edge trims
chrom, pos = refpos.split(":")
ostart, end = pos.split("-")
start = int(ostart) + edg[0]
end = start + (edg[3] - edg[0])
# get consens hit indexes and start positions
nidbits = []
for bit in self.nidxs[1:]:
# handle multiple consens merged
bkey = []
for cbit in bit.split(";"):
cidx, _, pos = cbit.split(":")
# start pos of sample is its consens start pos + ostart
# where ostart is the ref position start after trim. So
# how far ahead of ref start does the consens read start.
posplus = int(pos.split("-")[0]) - int(ostart)
bkey.append("{}:{}".format(cidx, posplus))
nidbits.append("-".join(bkey))
# put ref back into string and append consens hits
refpos = "{}:{}-{}".format(chrom, start, end)
nidbits = [refpos] + nidbits
nidxstring = ",".join(nidbits)
# denovo stores start read start position in the nidx string
else:
nidxstring = ",".join(self.nidxs)
# if not paired data (with an insert)
for idx, name in enumerate(self.names):
locus.append(
"{}{}".format(
self.data.pnames[name],
block[idx, :].tostring().decode())
)
locus.append("{}{}|{}|".format(
self.data.snppad, snpstring, nidxstring))
return "\n".join(locus)
def filter_dups(self):
if len(set(self.names)) < len(self.names):
self.filters[self.iloc, 0] = 1
return True
return False
def filter_minsamp_pops(self):
"filter by minsamp or by minsamp x populations"
# default: no population information
if not self.data.populations:
if len(self.names) < self.minsamp: # data.params.min_samples_locus:
# store locus filter
self.filters[self.iloc, 4] = 1
# return True
# return False
# use populations
else:
minfilters = []
for pop in self.data.populations:
samps = self.data.populations[pop][1]
minsamp = self.data.populations[pop][0]
if len(set(samps).intersection(set(self.names))) < minsamp:
minfilters.append(pop)
if any(minfilters):
self.filters[self.iloc, 4] = 1
# return True
# return False
def filter_maxindels(self, ublock):
"max size of internal indels. Denovo vs. Ref, single versus paired."
# get max indels for read1, read2
inds = maxind_numba(ublock)
if inds > self.maxinds:
self.filters[self.iloc, 1] = 1
# return True
# return False
def filter_maxvars(self, ublock, snpstring):
# mask insert area
if self.masked is not None:
if snpstring.sum() > (self.masked.shape[1] * self.fmaxsnps):
self.filters[self.iloc, 2] = 1
# return True
# use full locus
else:
if snpstring.sum() > (ublock.shape[1] * self.fmaxsnps):
self.filters[self.iloc, 2] = 1
# return True
# return False
def filter_maxshared(self, ublock):
nhs = count_maxhet_numba(ublock)
if nhs > (self.fmaxhet * ublock.shape[0]):
self.filters[self.iloc, 3] = 1
# return True
# return False
def get_snpsarrs(self, block, exclude_ref=False):
"count nsnps with option to exclude reference sample from count"
snpsarr = np.zeros((block.shape[1], 2), dtype=np.bool_)
return snpcount_numba(block, snpsarr, int(bool(exclude_ref)))
##############################################################