-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.py
executable file
·1506 lines (1241 loc) · 48.6 KB
/
run.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
import re
import os
import warnings
import glob
import gzip
import json
import math
import time
import atexit
import argparse
import tempfile
import contextlib
import subprocess
import numpy as np
import random
from collections import Counter
from collections import defaultdict
from Bio import SeqIO
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
S3_BUCKET = None
WORK_ROOT = None
THISDIR = os.path.abspath(os.path.dirname(__file__))
COLOR_RED = "\x1b[0;31m"
COLOR_GREEN = "\x1b[0;32m"
COLOR_CYAN = "\x1b[0;36m"
COLOR_END = "\x1b[0m"
# Intended for https://github.com/naobservatory/mgs-pipeline/issues/65
# migration.
with open(os.path.join(THISDIR, "reference-suffix.txt")) as inf:
REFERENCE_SUFFIX = inf.read().strip()
def check_call_shell(cmd):
# Unlike subprocess.check_call, if any member of the pipeline fails then
# this fails too.
subprocess.check_call(["bash", "-c", "set -o pipefail; %s" % cmd])
def check_output_shell(cmd):
# Unlike subprocess.check_output, if any member of the pipeline fails then
# this fails too.
return subprocess.check_output(
["bash", "-c", "set -o pipefail; %s" % cmd]
)
def work_fname(*fnames):
return os.path.join(THISDIR, WORK_ROOT, *fnames)
def get_sample_priority(sample):
m = re.findall(r"L00\d$", sample)
if not m:
return "A"
m, = m
return m
def get_samples(args):
if args.sample:
return [args.sample]
with open(
work_fname("deliveries", args.delivery, "metadata", "metadata.tsv")
) as inf:
samples = [line.strip().split("\t")[0] for line in inf]
for sample in samples:
if "." in sample:
raise Exception("Bad sample for %s: %s" % (
args.delivery, sample))
decorated_samples = [
(get_sample_priority(sample), sample)
for sample in samples]
decorated_samples.sort()
return [sample for _, sample in decorated_samples]
@contextlib.contextmanager
def tempdir(stage, msg):
olddir = os.getcwd()
with tempfile.TemporaryDirectory(
dir=os.path.expanduser("~/tmp/")) as workdir:
os.chdir(workdir)
try:
print("%s: handling %s in %s" % (stage, msg, workdir))
yield workdir
finally:
os.chdir(olddir)
def exists_s3_prefix(s3_path):
try:
subprocess.check_call(
["aws", "s3", "ls", s3_path], stdout=subprocess.DEVNULL
)
return True # exit code 0 if present
except subprocess.CalledProcessError as e:
if e.returncode == 1:
return False # exit code 1 if absent
raise # any other exit code means something else is wrong
def ls_s3_dir(s3_dir, min_size=0, min_date=""):
try:
cmd_out = subprocess.check_output(["aws", "s3", "ls", s3_dir])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
return [] # exit code 1 if absent or empty
raise # any other exit code means something is wrong
for line in cmd_out.split(b"\n"):
if not line.strip():
continue
if line.endswith(b"0 "):
continue
try:
date, time, size, fname = line.split()
except ValueError:
print(line)
print(s3_dir)
raise
if int(size) < min_size:
continue
if date.decode("utf-8") < min_date:
continue
yield fname.decode("utf-8")
def get_adapters(in1, in2, adapter1_fname, adapter2_fname):
output = subprocess.check_output(
[
"AdapterRemoval",
"--file1",
in1,
"--file2",
in2,
"--identify-adapters",
"--qualitymax",
"45", # Aviti goes up to N
"--threads",
"4",
]
)
output = output.decode("utf-8")
for line in output.split("\n"):
if "--adapter1:" in line:
adapter1 = line.replace("--adapter1:", "").strip()
elif "--adapter2:" in line:
adapter2 = line.replace("--adapter2:", "").strip()
for adapter, fname in [
[adapter1, adapter1_fname],
[adapter2, adapter2_fname],
]:
if not all(x in "ACTGN" for x in adapter) or len(adapter) < 20:
print(output)
raise Exception(
"Invalid adapter %r for %r and %r" % (adapter, in1, in2)
)
with open(fname, "w") as outf:
outf.write(adapter)
def is_nanopore(args):
return args.delivery.startswith("NAO-ONT-")
def rm_human(args):
return "-Zephyr" in args.delivery
def no_adapters_dirname(args):
if is_nanopore(args):
return "raw"
return "cleaned"
def final_fastq_dirname(args):
if rm_human(args):
return "nonhuman"
else:
return no_adapters_dirname(args)
def adapter_removal(args, dirname, trim_quality, collapse):
adapter_dir = work_fname("deliveries", args.delivery, "adapters")
try:
os.mkdir(adapter_dir)
except FileExistsError:
pass
available_inputs = get_files(args, "raw")
existing_outputs = get_files(args, "cleaned", min_size=100)
for sample in get_samples(args):
raw1 = "%s_1.fastq.gz" % sample
raw2 = "%s_2.fastq.gz" % sample
if raw1 not in available_inputs or raw2 not in available_inputs:
print("Skipping %s" % sample)
continue
if (
"%s.collapsed.gz" % sample in existing_outputs
and "%s.pair1.truncated.gz" % sample in existing_outputs
and "%s.pair2.truncated.gz" % sample in existing_outputs
):
# Already done
continue
with tempdir("adapter_removal", sample) as workdir:
in1 = "in1.fastq.gz"
in2 = "in2.fastq.gz"
s3_copy_down(args, "raw", raw1, local_fname=in1)
s3_copy_down(args, "raw", raw2, local_fname=in2)
adapter1_fname = os.path.join(adapter_dir, "%s.fwd" % sample)
adapter2_fname = os.path.join(adapter_dir, "%s.rev" % sample)
if not os.path.exists(adapter1_fname) or not os.path.exists(
adapter2_fname
):
get_adapters(in1, in2, adapter1_fname, adapter2_fname)
with open(adapter1_fname) as inf:
adapter1 = inf.read().strip()
with open(adapter2_fname) as inf:
adapter2 = inf.read().strip()
cmd = [
"AdapterRemoval",
"--file1",
in1,
"--file2",
in2,
"--basename",
sample,
"--threads",
"4",
"--qualitymax",
"45", # Aviti goes up to N
"--adapter1",
adapter1,
"--adapter2",
adapter2,
"--gzip",
]
if trim_quality:
cmd.extend(["--trimns", "--trimqualities"])
if collapse:
cmd.append("--collapse")
subprocess.check_call(cmd)
for output in glob.glob("%s.*" % sample):
s3_copy_up(args, output, dirname)
def clean(args):
if is_nanopore(args):
return
adapter_removal(args, "cleaned", trim_quality=True, collapse=True)
def full_s3_dirname(dirname):
if dirname in ["raw", "cleaned", "ribofrac", "nonhuman"]:
return dirname
return "%s-%s" % (dirname, REFERENCE_SUFFIX)
def s3_dir(args, dirname):
return "%s/%s/%s/" % (S3_BUCKET, args.delivery, full_s3_dirname(dirname))
def s3_file(args, dirname, fname):
return "%s%s" % (s3_dir(args, dirname), fname)
def s3_copy_down(args, dirname, remote_fname, local_fname=None):
if not local_fname:
local_fname = os.path.basename(remote_fname)
subprocess.check_call([
"aws",
"s3",
"cp",
s3_file(args, dirname, remote_fname),
local_fname,
])
def s3_copy_up(args, local_fname, dirname, remote_fname=None):
if not remote_fname:
remote_fname = os.path.basename(local_fname)
subprocess.check_call([
"aws",
"s3",
"cp",
local_fname,
s3_file(args, dirname, remote_fname),
])
def get_files(args, dirname, min_size=1, min_date=""):
return set(ls_s3_dir(s3_dir(args, dirname),
min_size=min_size,
min_date=min_date))
def ribofrac(args, subset_size=1000):
"""Fast algorithm to compute fraction of reads identified as rRNA by RiboDetector"""
available_inputs = get_files(
args,
no_adapters_dirname(args),
# tiny files are empty; ignore them
min_size=100,
)
existing_outputs = get_files(args, "ribofrac", min_date="2023-10-12")
def first_subset_fastq(file_paths, subset_size):
"""Selects the first subset of reads from gzipped fastq files"""
print(
f"Counting reads in input and selecting the first {subset_size}..."
)
output_files = []
total_reads = 0
# Count the total number of reads only for the first input file
with gzip.open(file_paths[0], "rt") as f:
total_reads = sum(1 for _ in FastqGeneralIterator(f))
for fp in file_paths:
# When reads in file < subset_size, return actual number of reads in subset
actual_subset_size = 0
with gzip.open(fp, "rt") as f:
# Create an output file handle
output_file = fp.replace(".fq.gz", ".subset.fq")
with open(output_file, "w") as out_handle:
for index, (title, seq, qual) in enumerate(
FastqGeneralIterator(f)
):
if index >= subset_size:
break
actual_subset_size += 1
out_handle.write(
"@%s\n%s\n+\n%s\n" % (title, seq, qual)
)
output_files.append(output_file)
return output_files, total_reads, actual_subset_size
def file_integrity_check(filename):
"""
Checks if the file exists and contains any reads.
If either condition fails, it raises a warning.
"""
if not os.path.exists(filename):
warnings.warn(f"File {filename} does not exist!")
return False
with gzip.open(filename, "rt") as f:
try:
# Check for the first read using the iterator
next(FastqGeneralIterator(f))
except StopIteration:
warnings.warn(f"File {filename} contains no reads!")
return False
return True
for sample in get_samples(args):
# Check for name of output file
sample_output_file = sample + ".ribofrac.txt"
if sample_output_file in existing_outputs:
continue
# Track for error handling
total_files_in_sample = 0
empty_files_in_sample = 0
total_reads_dict = {}
subset_reads_dict = {}
rrna_reads_dict = {}
for potential_input in available_inputs:
if not potential_input.startswith(sample):
continue
if ".settings" in potential_input:
continue
if "discarded" in potential_input:
continue
total_files_in_sample += 1
# Number of output and input files must match
tmp_fq_output = potential_input.replace(
".gz", ".subset.nonrrna.fq"
)
tmp_fq_outputs = [tmp_fq_output]
inputs = [potential_input]
if ".pair1." in potential_input:
tmp_fq_outputs.append(
tmp_fq_output.replace(".pair1.", ".pair2.")
)
inputs.append(potential_input.replace(".pair1.", ".pair2."))
elif ".pair2." in potential_input:
# Ribodetector handles pair1 and pair2 together.
continue
with tempdir("ribofrac", sample + " inputs") as workdir:
for input_fname in inputs:
s3_copy_down(args, no_adapters_dirname(args), input_fname)
# Check file integrity
file_valid = file_integrity_check(input_fname)
if not file_valid:
empty_files_in_sample += 1
# Ribodetector gets angry if the .fq extension isn't in the filename
os.rename(
input_fname, input_fname.replace(".gz", ".fq.gz")
)
if total_files_in_sample == empty_files_in_sample:
print(f"Skipping {sample}... all files are empty.")
continue
# Add .fq extensions to input files
inputs = [i.replace(".gz", ".fq.gz") for i in inputs]
# Get subset of inputs
subsets, total_reads, subset_reads = first_subset_fastq(
inputs, subset_size
)
subset_reads_dict[inputs[0]] = subset_reads
total_reads_dict[inputs[0]] = total_reads
# Compute average read lengths. For paired-end reads, average length is
# computed only from pair1 reads.
print("Calculating average read length...")
def calculate_average_read_length(file_path):
total_len = 0
total_reads = 0
with open(file_path, "rt") as inf:
for title, sequence, quality in FastqGeneralIterator(
inf
):
total_len += len(sequence)
total_reads += 1
return round(total_len / total_reads)
avg_length = calculate_average_read_length(subsets[0])
print("Done. Average read length is ", avg_length)
ribodetector_cmd = [
"ribodetector_cpu",
"--ensure",
"rrna",
"--threads",
"28",
]
ribodetector_cmd.extend(["--len", str(avg_length)])
ribodetector_cmd.append("--input")
ribodetector_cmd.extend(subsets)
# RiboDetector outputs fastq files containing non-rRNA sequences
# https://github.com/hzi-bifo/RiboDetector
ribodetector_cmd.append("--output")
ribodetector_cmd.extend(tmp_fq_outputs)
subprocess.check_call(ribodetector_cmd)
# Count number of rRNA reads in subset
non_rrna_count = sum(
1
for _ in FastqGeneralIterator(
open(tmp_fq_outputs[0], "rt")
)
)
rrna_reads_dict[inputs[0]] = subset_reads - non_rrna_count
if not total_files_in_sample:
print("%s wasn't processed by ribofrac because it's not present in cleaned" % sample)
continue
# Calculate the weighted average fraction of rRNA reads across all inputs in sample using numpy
# Extract the fractions of rRNA reads for each input
fractions_rrna_in_subset = [
rrna_reads_dict[input_filename] / subset_reads_dict[input_filename]
for input_filename in total_reads_dict
]
# Use the total number of reads for each input as weights
weights = list(total_reads_dict.values())
weighted_rrna_fraction = np.average(
fractions_rrna_in_subset, weights=weights
)
fraction_rrna = round(weighted_rrna_fraction, 4)
print(
f"Estimated fraction of rRNA reads in {sample} = {round(fraction_rrna*100, 2)}%"
)
# Save fraction of rRNA reads
with tempdir("ribofrac", sample + "_output") as workdir:
ribofrac_file = os.path.join(workdir, f"{sample}.ribofrac.txt")
with open(ribofrac_file, "w") as txt_file:
txt_file.write(str(fraction_rrna))
s3_copy_up(args, ribofrac_file, "ribofrac")
def interpret(args):
available_inputs = get_files(
args,
final_fastq_dirname(args),
# tiny files are empty; ignore them
min_size=100,
)
existing_outputs = get_files(args, "processed")
for sample in get_samples(args):
for potential_input in available_inputs:
if not potential_input.startswith(sample):
continue
if ".settings" in potential_input:
continue
if "discarded" in potential_input:
continue
output = potential_input.replace(".gz", ".kraken2.tsv")
inputs = [potential_input]
if ".pair1." in output:
output = output.replace(".pair1.", ".")
inputs.append(potential_input.replace(".pair1.", ".pair2."))
elif ".pair2" in output:
# We handle pair1 and pair2 together.
continue
compressed_output = output + ".gz"
if compressed_output in existing_outputs:
continue
with tempdir("interpret", ", ".join(inputs)) as workdir:
for input_fname in inputs:
s3_copy_down(args, final_fastq_dirname(args), input_fname)
kraken_cmd = [
"/home/ec2-user/kraken2-install/kraken2",
"--use-names",
"--output",
output,
]
db = "/dev/shm/kraken-db/"
kraken_cmd.append("--memory-mapping")
threads = "4"
assert os.path.exists(db)
kraken_cmd.append("--db")
kraken_cmd.append(db)
kraken_cmd.append("--threads")
kraken_cmd.append(threads)
if len(inputs) > 1:
kraken_cmd.append("--paired")
kraken_cmd.extend(inputs)
subprocess.check_call(kraken_cmd)
subprocess.check_call(["gzip", output])
s3_copy_up(args, compressed_output, "processed")
def cladecounts(args):
available_inputs = get_files(args, "processed")
existing_outputs = get_files(
args, "cladecounts", min_size=100, min_date="2023-05-19"
)
for sample in get_samples(args):
output = "%s.tsv.gz" % sample
if output in existing_outputs:
continue
if not any(x.startswith(sample) for x in available_inputs):
continue
subprocess.check_call(
["./count_clades.sh",
S3_BUCKET,
args.delivery,
sample,
REFERENCE_SUFFIX]
)
SAMPLE_READS_TARGET_LEN = 100_000
def samplereads(args):
human_viruses = set()
with open(os.path.join(THISDIR, "human-viruses.tsv")) as inf:
for line in inf:
taxid, _ = line.strip().split("\t")
human_viruses.add(int(taxid))
parents = {}
with open(os.path.join(THISDIR, "dashboard", "nodes.dmp")) as inf:
for line in inf:
child_taxid, parent_taxid, *_ = line.replace("\t|\n", "").split(
"\t|\t"
)
parents[int(child_taxid)] = int(parent_taxid)
def taxid_under(clade, taxid):
while taxid not in [0, 1]:
if taxid == clade:
return True
taxid = parents[taxid]
return False
def taxid_matches(taxid, category):
if category == "all":
return True
if category == "humanviral":
return taxid in human_viruses
return taxid_under(
{
"bacterial": 2,
"viral": 10239,
}[category],
taxid,
)
available_inputs = get_files(args, "processed")
existing_outputs = get_files(args, "samplereads", min_date="2023-11-03")
for sample in get_samples(args):
output = "%s.sr.tsv.gz" % sample
if output in existing_outputs:
continue
inputs = [x for x in available_inputs if x.startswith(sample)]
if not any(inputs):
continue
read_ids = {}
full_counts = Counter()
fname_counts = defaultdict(Counter)
for fname in inputs:
read_ids[fname] = {
"all": [],
"bacterial": [],
"viral": [],
"humanviral": [],
}
process = subprocess.Popen(
[
"aws",
"s3",
"cp",
s3_file(args, "processed", fname),
"-",
],
stdout=subprocess.PIPE,
shell=False,
)
try:
with gzip.open(process.stdout, "rt") as inf:
for line in inf:
bits = line.rstrip("\n").split("\t")
read_id = bits[1]
full_assignment = bits[2]
taxid = int(full_assignment.split()[-1].rstrip(")"))
for category in read_ids[fname]:
if taxid_matches(taxid, category):
full_counts[category] += 1
fname_counts[fname][category] += 1
if (
len(read_ids[fname][category])
< SAMPLE_READS_TARGET_LEN
):
read_ids[fname][category].append(read_id)
finally:
process.terminate()
subsetted_ids = {}
for category, full_count in full_counts.items():
subsetted_ids[category] = []
for fname in read_ids:
if full_count <= SAMPLE_READS_TARGET_LEN:
subsetted_ids[category].extend(read_ids[fname][category])
else:
target = (
SAMPLE_READS_TARGET_LEN
* fname_counts[fname][category]
// full_count
)
subsetted_ids[category].extend(
read_ids[fname][category][:target]
)
with tempdir("samplereads", sample) as workdir:
with gzip.open(output, "wt") as outf:
for category in sorted(subsetted_ids):
for selected_read_id in sorted(subsetted_ids[category]):
outf.write(
"%s\t%s\n" % (category[0], selected_read_id)
)
s3_copy_up(args, output, "samplereads")
def readlengths(args):
available_samplereads_inputs = get_files(args, "samplereads")
available_cleaned_inputs = get_files(args, final_fastq_dirname(args))
existing_outputs = get_files(args, "readlengths", min_date="2023-11-04")
for sample in get_samples(args):
output = "%s.rl.json.gz" % sample
if output in existing_outputs:
continue
inputs = [
x for x in available_samplereads_inputs if x.startswith(sample)
]
if not any(inputs):
continue
(fname,) = inputs
target_read_ids = defaultdict(set)
process = subprocess.Popen(
[
"aws",
"s3",
"cp",
s3_file(args, "samplereads", fname),
"-",
],
stdout=subprocess.PIPE,
shell=False,
)
try:
with gzip.open(process.stdout, "rt") as inf:
for line in inf:
bits = line.rstrip("\n").split("\t")
category, read_id = bits
target_read_ids[read_id].add(category)
finally:
process.terminate()
inputs = [x for x in available_cleaned_inputs if x.startswith(sample)]
assert inputs
lengths = {}
for category in "abhv":
lengths[category] = {"NC": 0}
for fname in inputs:
if ".collapsed." not in fname and not is_nanopore(args):
# We can only get fragment lengths from cases where we could
# collapse. Fragments longer than fwd + rev - minoverlap could be
# any length for all we know.
#
# (It would be possible to do better by aligning to genomes, but
# that's a ton of work)
continue
process = subprocess.Popen(
[
"aws",
"s3",
"cp",
s3_file(args, final_fastq_dirname(args), fname),
"-",
],
stdout=subprocess.PIPE,
shell=False,
)
try:
with gzip.open(process.stdout, "rt") as inf:
for title, sequence, quality in FastqGeneralIterator(inf):
title = title.split()[0]
if title not in target_read_ids:
continue
for category in target_read_ids[title]:
seql = len(sequence)
if seql not in lengths[category]:
lengths[category][seql] = 1
else:
lengths[category][seql] += 1
del target_read_ids[title]
finally:
process.terminate()
# We removed as we went, so any left here are non-collapsed
for target_read_id, categories in target_read_ids.items():
for category in categories:
lengths[category]["NC"] += 1
with tempdir("readlengths", sample) as workdir:
with gzip.open(output, "wt") as outf:
json.dump(lengths, outf)
s3_copy_up(args, output, "readlengths")
def humanviruses(args):
human_viruses = {}
with open(os.path.join(THISDIR, "human-viruses.tsv")) as inf:
for line in inf:
taxid, name = line.strip().split("\t")
human_viruses[int(taxid)] = name
available_inputs = get_files(args, "processed")
existing_outputs = get_files(args, "humanviruses")
for sample in get_samples(args):
output = "%s.humanviruses.tsv" % sample
if output in existing_outputs:
continue
inputs = [
input_fname
for input_fname in available_inputs
if input_fname.startswith(sample)
]
if not inputs:
continue
counts = Counter()
for input_fname in inputs:
with tempdir("humanviruses", sample) as workdir:
s3_copy_down(args, "processed", input_fname)
with gzip.open(input_fname, "rt") as inf:
for line in inf:
(taxid,) = re.findall("[(]taxid ([0-9]+)[)]", line)
taxid = int(taxid)
if taxid in human_viruses:
counts[taxid] += 1
with tempdir("humanviruses", sample) as workdir:
with open(output, "w") as outf:
for taxid, count in sorted(counts.items()):
outf.write(
"%s\t%s\t%s\n" % (taxid, count, human_viruses[taxid])
)
s3_copy_up(args, output, "humanviruses")
def allmatches(args):
human_viruses = {}
with open(os.path.join(THISDIR, "human-viruses.tsv")) as inf:
for line in inf:
taxid, name = line.strip().split("\t")
human_viruses[int(taxid)] = name
available_inputs = get_files(args, "processed")
existing_outputs = get_files(args, "allmatches")
for sample in get_samples(args):
output = "%s.allmatches.tsv" % sample
if output in existing_outputs:
continue
inputs = [
input_fname
for input_fname in available_inputs
if input_fname.startswith(sample)
]
if not inputs:
continue
with tempdir("allmatches", sample) as workdir:
kept = []
for input_fname in inputs:
s3_copy_down(args, "processed", input_fname)
with gzip.open(input_fname, "rt") as inf:
for line in inf:
keep = False
try:
taxid_matches = line.strip().split("\t")[4]
for taxid_match in taxid_matches.split(" "):
taxid, n_kmers = taxid_match.split(":")
if taxid == "A":
continue # ambiguous nucleotide
if taxid == "|":
continue # paired end transition
taxid = int(taxid)
if taxid in human_viruses:
keep = True
except Exception:
print(line)
raise
if keep:
kept.append(line)
with open(output, "w") as outf:
for line in kept:
outf.write(line)
s3_copy_up(args, output, "allmatches")
def valreads(args):
# The subset of hvreads where that pass an alignment threshold.
available_hvreads_inputs = get_files(args, "hvreads")
available_alignments2_inputs = get_files(args, "alignments2")
existing_outputs = get_files(args, "valreads")
for sample in get_samples(args):
output = "%s.valreads.json" % sample
if output in existing_outputs:
continue
input_hvreads_fname = "%s.hvreads.json" % sample
input_alignments2_fname = "%s.hv.alignments2.tsv.gz" % sample
if input_hvreads_fname not in available_hvreads_inputs:
continue
if input_alignments2_fname not in available_alignments2_inputs:
continue
with tempdir("valreads", sample) as workdir:
s3_copy_down(args, "hvreads", input_hvreads_fname)
s3_copy_down(args, "alignments2", input_alignments2_fname)
accepted_read_ids = set()
with gzip.open(input_alignments2_fname, "rt") as inf:
for line in inf:
(query_name, genomeid, taxid, cigarstring, ref_start,
as_val, query_len) = line.rstrip("\n").split("\t")
length_adjusted_score = int(as_val) / math.log(int(query_len))
if length_adjusted_score > 20:
accepted_read_ids.add(query_name)
valreads_out = {}
with open(input_hvreads_fname) as inf:
for read_id, record in json.load(inf).items():
if read_id in accepted_read_ids:
valreads_out[read_id] = record
with open(output, "w") as outf:
json.dump(valreads_out, outf)
s3_copy_up(args, output, "valreads")
def tmpvalreads(args):
available_hvreads_inputs = get_files(args, "hvreads")
available_alignments2_inputs = get_files(args, "alignments2")
existing_outputs = get_files(args, "tmpvalreads")
for sample in get_samples(args):
output = "%s.tmpvalreads.json" % sample
if output in existing_outputs:
continue
input_hvreads_fname = "%s.hvreads.json" % sample
input_alignments2_fname = "%s.hv.alignments2.tsv.gz" % sample
if input_hvreads_fname not in available_hvreads_inputs:
continue
if input_alignments2_fname not in available_alignments2_inputs:
continue
with tempdir("tmpvalreads", sample) as workdir:
s3_copy_down(args, "hvreads", input_hvreads_fname)
s3_copy_down(args, "alignments2", input_alignments2_fname)
read_scores = defaultdict(float)
with gzip.open(input_alignments2_fname, "rt") as inf:
for line in inf:
(query_name, genomeid, taxid, cigarstring, ref_start,
as_val, query_len) = line.rstrip("\n").split("\t")
length_adjusted_score = int(as_val) / math.log(int(query_len))
read_scores[query_name] = max(
read_scores[query_name], length_adjusted_score)
tmpvalreads_out = {}
with open(input_hvreads_fname) as inf:
for read_id, record in json.load(inf).items():
record.insert(0, read_scores[read_id])
tmpvalreads_out[read_id] = record
with open(output, "w") as outf:
json.dump(tmpvalreads_out, outf)
s3_copy_up(args, output, "tmpvalreads")