-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassemble.py
More file actions
1429 lines (1317 loc) · 49.9 KB
/
assemble.py
File metadata and controls
1429 lines (1317 loc) · 49.9 KB
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
"""
Assemble 2 Sanger ABI reads (forward + reverse) from a folder into a consensus FASTA.
Requires: biopython
pip install biopython
Usage:
python assemble.py /path/to/folder
python assemble.py --use-paired-mixture /path/to/folder
python assemble.py --use-single-mixture /path/to/folder
python assemble.py --min-phred-score-per-base 20 --min-consecutive-high-quality-bases 10 /path/to/folder
Input folder:
- forward .ab1 file stem ends with 'F'
- reverse .ab1 file stem ends with 'R'
Outputs are written into the same folder:
- <folder_name>.fasta
- forward_trimmed.fasta
- reverse_rc_trimmed.fasta
- <folder_name>_alignment.html
- <folder_name>_QA.html
"""
import argparse
from collections import Counter
import json
from pathlib import Path
import sys
from dataclasses import dataclass
from typing import Any, List, Tuple
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Align import PairwiseAligner
from jinja2 import Environment, FileSystemLoader, select_autoescape
from align_reference import (
align_consensus_to_reference_nucleotide,
read_reference_nucleotide_fasta,
write_amino_acid_alignment_fasta,
)
from mixture_detector import resolve_consensus_base
from single_strand_mixture_detector import (
build_single_strand_mixtures_header,
detect_single_strand_mixtures,
)
from quality_checks import run_quality_checks
TEMPLATE_ENV = Environment(
loader=FileSystemLoader(Path(__file__).parent),
autoescape=select_autoescape(["html"]),
)
def parse_min_phred_score_per_base(value: str | tuple[int, int]) -> tuple[int, int]:
if isinstance(value, tuple):
if len(value) != 2:
raise ValueError("min_phred_score_per_base must contain exactly two values.")
return value
parts = value.split(":")
if len(parts) != 2:
raise ValueError(
"min_phred_score_per_base must use format forward_phred:reverse_phred, for example 20:20."
)
try:
forward_min_phred_score_per_base = int(parts[0])
reverse_min_phred_score_per_base = int(parts[1])
except ValueError as exc:
raise ValueError(
"min_phred_score_per_base must use integer values like 20:20."
) from exc
return forward_min_phred_score_per_base, reverse_min_phred_score_per_base
def format_min_phred_score_per_base(value: tuple[int, int]) -> str:
return f"{value[0]}:{value[1]}"
@dataclass
class Read:
name: str
seq: str
qual: List[int]
start: int
end: int
@dataclass
class LowQualityPosition:
consensus_pos: int
forward_pos: int
forward_base: str
forward_qual: str
reverse_pos: int
reverse_base: str
reverse_qual: str
reason: str
@dataclass
class AbiTrace:
name: str
seq: str
base_positions: List[int]
channels: dict[str, List[int]]
metadata: dict[str, str]
key_sections: list[str]
hierarchy_text: str
@dataclass
class AssemblyArtifacts:
sample_name: str
report_files: list[Path]
consensus_files: list[Path]
warning_file: Path | None
@property
def primary_report(self) -> Path | None:
for suffix in ("_QA.html", "_alignment.html"):
for path in self.report_files:
if path.name.endswith(suffix):
return path
if self.warning_file is not None:
return self.warning_file
return self.report_files[0] if self.report_files else None
def read_ab1(path: str, name: str) -> Read:
rec = SeqIO.read(path, "abi")
seq = str(rec.seq).upper()
qual = rec.letter_annotations.get("phred_quality")
if qual is None:
raise ValueError(f"No phred qualities found in {path}.")
if len(qual) != len(seq):
raise ValueError(f"Quality length != sequence length in {path}.")
return Read(name=name, seq=seq, qual=list(qual), start=0, end=len(seq))
def read_ab1_trace(path: str, name: str) -> AbiTrace:
rec = SeqIO.read(path, "abi")
raw = rec.annotations.get("abif_raw")
if raw is None:
raise ValueError(f"No ABI raw trace data found in {path}.")
order = raw.get("FWO_1")
if isinstance(order, bytes):
order = order.decode("ascii")
if not isinstance(order, str) or len(order) != 4:
raise ValueError(f"Could not determine channel order from {path}.")
base_positions = raw.get("PLOC2")
if base_positions is None:
base_positions = raw.get("PLOC1")
if base_positions is None:
raise ValueError(f"Could not determine base positions from {path}.")
trace_keys = ["DATA9", "DATA10", "DATA11", "DATA12"]
channels: dict[str, List[int]] = {}
for base, key in zip(order, trace_keys):
values = raw.get(key)
if values is None:
raise ValueError(f"Missing trace channel {key} in {path}.")
channels[base] = list(values)
for base in "ACGT":
if base not in channels:
raise ValueError(f"Missing trace channel for base {base} in {path}.")
metadata = {}
metadata_keys = {
"SMPL1": "Sample Name",
"MCHN1": "Instrument",
"MODL1": "Instrument Model",
"LANE1": "Lane",
"RUNN1": "Run Name",
"RUND1": "Run Date",
"RUNT1": "Run Time",
"DYEP1": "Dye Set",
"CTID1": "Container ID",
}
for key, label in metadata_keys.items():
value = raw.get(key)
if isinstance(value, bytes):
value = value.decode("ascii", errors="ignore").strip("\x00 ")
if value not in (None, ""):
metadata[label] = str(value)
key_section_specs = [
("PBAS", ["PBAS2", "PBAS1"], "Base calls for the read sequence."),
("PCON", ["PCON2", "PCON1"], "Per-base confidence or quality values."),
("PLOC", ["PLOC2", "PLOC1"], "Trace indices for each called base."),
("FWO_", ["FWO_1"], "Channel order that maps trace data to A/C/G/T bases."),
(
"DATA",
["DATA9", "DATA10", "DATA11", "DATA12"],
"Raw fluorescence trace channels used to build the chromatogram.",
),
("SMPL", ["SMPL1"], "Sample identifier or sample name."),
("MCHN", ["MCHN1"], "Instrument identifier."),
("MODL", ["MODL1"], "Instrument model."),
("RUN", ["RUNN1", "RUND1", "RUNT1"], "Run name, date, and time metadata."),
("DYEP", ["DYEP1"], "Dye set or chemistry information."),
("CTID", ["CTID1"], "Container or plate/tube identifier."),
]
key_sections = []
hierarchy_lines = ["ABIF"]
for section_name, keys, purpose in key_section_specs:
present_keys = [key for key in keys if raw.get(key) is not None]
if present_keys:
key_sections.append(
f"{section_name}: present via {', '.join(present_keys)}. {purpose}"
)
hierarchy_lines.append(f"+- {section_name}: {purpose}")
for key in present_keys:
hierarchy_lines.append(f"| +- {key}")
return AbiTrace(
name=name,
seq=str(rec.seq).upper(),
base_positions=list(base_positions),
channels=channels,
metadata=metadata,
key_sections=key_sections,
hierarchy_text="\n".join(hierarchy_lines),
)
def trim_by_quality(
r: Read,
min_phred_score_per_base: int,
min_consecutive_high_quality_bases: int = 10,
) -> Read:
"""
Trim low-quality ends:
- find first position where there's a run of >= min_consecutive_high_quality_bases
bases with Q>=min_phred_score_per_base
- find last position similarly (from the end)
"""
n = len(r.seq)
good = [q >= min_phred_score_per_base for q in r.qual]
# find left trim
left = 0
found = False
for i in range(0, n - min_consecutive_high_quality_bases + 1):
if all(good[i : i + min_consecutive_high_quality_bases]):
left = i
found = True
break
if not found:
# nothing good: return empty
return Read(r.name, "", [], r.start, r.start)
# find right trim
right = n
found = False
for i in range(n, min_consecutive_high_quality_bases - 1, -1):
# window ends at i, starts at i-min_consecutive_high_quality_bases
if all(good[i - min_consecutive_high_quality_bases : i]):
right = i
found = True
break
if not found or right <= left:
return Read(r.name, "", [], r.start, r.start)
return Read(
r.name,
r.seq[left:right],
r.qual[left:right],
r.start + left,
r.start + right,
)
def revcomp_read(r: Read) -> Read:
"""
Reverse-complement sequence; reverse qualities (no complement needed for qualities).
"""
rc_seq = str(Seq(r.seq).reverse_complement())
rc_qual = list(reversed(r.qual))
return Read(r.name + "_rc", rc_seq, rc_qual, r.start, r.end)
def build_gapped_alignment(
fwd_seq: str,
rev_seq: str,
f_blocks: List[Tuple[int, int]],
r_blocks: List[Tuple[int, int]],
) -> Tuple[str, str]:
gf = []
gr = []
f_i = 0
r_i = 0
for (fs, fe), (rs, re) in zip(f_blocks, r_blocks):
if fs > f_i or rs > r_i:
f_gap = fs - f_i
r_gap = rs - r_i
if f_gap > 0 and r_gap == 0:
gf.append(fwd_seq[f_i:fs])
gr.append("-" * f_gap)
elif r_gap > 0 and f_gap == 0:
gf.append("-" * r_gap)
gr.append(rev_seq[r_i:rs])
else:
chunk_length = max(f_gap, r_gap)
gf.append(fwd_seq[f_i:fs] + "-" * (chunk_length - f_gap))
gr.append(rev_seq[r_i:rs] + "-" * (chunk_length - r_gap))
f_i = fs
r_i = rs
gf.append(fwd_seq[fs:fe])
gr.append(rev_seq[rs:re])
f_i = fe
r_i = re
if f_i < len(fwd_seq) or r_i < len(rev_seq):
f_suf = len(fwd_seq) - f_i
r_suf = len(rev_seq) - r_i
if f_suf > 0 and r_suf == 0:
gf.append(fwd_seq[f_i:])
gr.append("-" * f_suf)
elif r_suf > 0 and f_suf == 0:
gf.append("-" * r_suf)
gr.append(rev_seq[r_i:])
else:
chunk_length = max(f_suf, r_suf)
gf.append(fwd_seq[f_i:] + "-" * (chunk_length - f_suf))
gr.append(rev_seq[r_i:] + "-" * (chunk_length - r_suf))
gapped_f = "".join(gf)
gapped_r = "".join(gr)
if len(gapped_f) != len(gapped_r):
raise RuntimeError("Internal error: gapped strings have different lengths.")
return gapped_f, gapped_r
def configure_overlap_aligner(
aligner: PairwiseAligner,
match: float,
mismatch: float,
gap_open: float,
gap_extend: float,
) -> None:
aligner.mode = "global"
aligner.match_score = match
aligner.mismatch_score = mismatch
aligner.open_gap_score = gap_open
aligner.extend_gap_score = gap_extend
available_attrs = set(dir(aligner))
for attr in [
"target_end_open_gap_score",
"target_end_extend_gap_score",
"query_end_open_gap_score",
"query_end_extend_gap_score",
"target_left_open_gap_score",
"target_left_extend_gap_score",
"target_right_open_gap_score",
"target_right_extend_gap_score",
"query_left_open_gap_score",
"query_left_extend_gap_score",
"query_right_open_gap_score",
"query_right_extend_gap_score",
"target_end_gap_score",
"query_end_gap_score",
"open_end_gap_score",
"extend_end_gap_score",
"end_gap_score",
"end_open_gap_score",
"end_extend_gap_score",
]:
if attr in available_attrs:
setattr(aligner, attr, 0.0)
def build_consensus_from_gapped_alignment(
fwd: Read,
rev: Read,
gapped_f: str,
gapped_r: str,
use_paired_mixture: bool,
forward_min_phred_score_per_base: int,
reverse_min_phred_score_per_base: int,
min_phred_score_for_paired_base: int,
min_overlap: int,
forward_single_mixture_map: dict[int, str] | None = None,
reverse_single_mixture_map: dict[int, str] | None = None,
) -> Tuple[str, int, List[LowQualityPosition], List[str], List[str]]:
fi = 0
ri = 0
overlap = 0
consensus_chars = []
consensus_line = []
low_quality_positions: List[LowQualityPosition] = []
consensus_pos = 0
fwd_qual_line = []
rev_qual_line = []
for cf, cr in zip(gapped_f, gapped_r):
bf = cf != "-"
br = cr != "-"
if bf and br:
overlap += 1
qf = fwd.qual[fi]
qr = rev.qual[ri]
consensus_pos += 1
decision = resolve_consensus_base(
cf,
qf,
cr,
qr,
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
allow_mixture=use_paired_mixture,
forward_trimmed_position=fi + 1,
reverse_trimmed_position=ri + 1,
forward_single_mixture_map=forward_single_mixture_map,
reverse_single_mixture_map=reverse_single_mixture_map,
)
consensus_chars.append(decision.consensus_base)
consensus_line.append(decision.consensus_base)
if decision.low_quality:
low_quality_positions.append(
LowQualityPosition(
consensus_pos=consensus_pos,
forward_pos=fwd.start + fi + 1,
forward_base=cf,
forward_qual=str(qf),
reverse_pos=rev.start + ri + 1,
reverse_base=cr,
reverse_qual=str(qr),
reason=decision.reason or "low_quality",
)
)
fwd_qual_line.append(f"{qf:02d}")
rev_qual_line.append(f"{qr:02d}")
fi += 1
ri += 1
elif bf and not br:
consensus_pos += 1
qf = fwd.qual[fi]
decision = resolve_consensus_base(
cf,
qf,
"-",
None,
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
allow_mixture=use_paired_mixture,
forward_trimmed_position=fi + 1,
forward_single_mixture_map=forward_single_mixture_map,
reverse_single_mixture_map=reverse_single_mixture_map,
)
consensus_chars.append(decision.consensus_base)
consensus_line.append(decision.consensus_base)
if decision.low_quality:
low_quality_positions.append(
LowQualityPosition(
consensus_pos=consensus_pos,
forward_pos=fwd.start + fi + 1,
forward_base=cf,
forward_qual=str(qf),
reverse_pos=0,
reverse_base="-",
reverse_qual="-",
reason=decision.reason or "low_quality",
)
)
fwd_qual_line.append(f"{qf:02d}")
rev_qual_line.append("--")
fi += 1
elif br and not bf:
consensus_pos += 1
qr = rev.qual[ri]
decision = resolve_consensus_base(
"-",
None,
cr,
qr,
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
allow_mixture=use_paired_mixture,
reverse_trimmed_position=ri + 1,
forward_single_mixture_map=forward_single_mixture_map,
reverse_single_mixture_map=reverse_single_mixture_map,
)
consensus_chars.append(decision.consensus_base)
consensus_line.append(decision.consensus_base)
if decision.low_quality:
low_quality_positions.append(
LowQualityPosition(
consensus_pos=consensus_pos,
forward_pos=0,
forward_base="-",
forward_qual="-",
reverse_pos=rev.start + ri + 1,
reverse_base=cr,
reverse_qual=str(qr),
reason=decision.reason or "low_quality",
)
)
fwd_qual_line.append("--")
rev_qual_line.append(f"{qr:02d}")
ri += 1
else:
consensus_pos += 1
decision = resolve_consensus_base(
"-",
None,
"-",
None,
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
allow_mixture=use_paired_mixture,
forward_single_mixture_map=forward_single_mixture_map,
reverse_single_mixture_map=reverse_single_mixture_map,
)
consensus_chars.append(decision.consensus_base)
consensus_line.append(decision.consensus_base)
low_quality_positions.append(
LowQualityPosition(
consensus_pos=consensus_pos,
forward_pos=0,
forward_base="-",
forward_qual="-",
reverse_pos=0,
reverse_base="-",
reverse_qual="-",
reason=decision.reason or "double_gap",
)
)
fwd_qual_line.append("--")
rev_qual_line.append("--")
if overlap < min_overlap:
raise ValueError(
f"Overlap too short ({overlap} bp). "
f"Try lowering min_overlap or check trimming / correct reverse-complement."
)
consensus = "".join(consensus_chars).replace("-", "")
return consensus, overlap, low_quality_positions, consensus_line, fwd_qual_line, rev_qual_line
def assemble_pair(
fwd: Read,
rev: Read,
forward_min_phred_score_per_base: int,
reverse_min_phred_score_per_base: int,
min_phred_score_for_paired_base: int,
use_paired_mixture: bool = True,
use_single_mixture: bool = False,
forward_single_mixture_map: dict[int, str] | None = None,
reverse_single_mixture_map: dict[int, str] | None = None,
match: float = 2.0,
mismatch: float = -1.0,
gap_open: float = -5.0,
gap_extend: float = -1.0,
min_overlap: int = 40,
) -> Tuple[str, dict, List[LowQualityPosition]]:
"""
Align fwd vs rev (rev should already be reverse-complemented) and build a consensus.
Returns:
consensus_seq, alignment_payload, low_quality_positions
"""
if not fwd.seq or not rev.seq:
raise ValueError("One of the reads is empty after trimming.")
aligner = PairwiseAligner()
configure_overlap_aligner(
aligner=aligner,
match=match,
mismatch=mismatch,
gap_open=gap_open,
gap_extend=gap_extend,
)
best = next(iter(aligner.align(fwd.seq, rev.seq)))
gapped_f, gapped_r = build_gapped_alignment(
fwd.seq,
rev.seq,
best.aligned[0],
best.aligned[1],
)
consensus, overlap, low_quality_positions, consensus_line, fwd_qual_line, rev_qual_line = (
build_consensus_from_gapped_alignment(
fwd=fwd,
rev=rev,
gapped_f=gapped_f,
gapped_r=gapped_r,
use_paired_mixture=use_paired_mixture,
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
min_overlap=min_overlap,
forward_single_mixture_map=(
forward_single_mixture_map if use_single_mixture else None
),
reverse_single_mixture_map=(
reverse_single_mixture_map if use_single_mixture else None
),
)
)
fwd_readpos_line = []
rev_readpos_line = []
fwd_pos = fwd.start + 1
rev_pos = rev.start + 1
for cf, cr in zip(gapped_f, gapped_r):
if cf != "-":
fwd_readpos_line.append(str(fwd_pos))
fwd_pos += 1
else:
fwd_readpos_line.append("")
if cr != "-":
rev_readpos_line.append(str(rev_pos))
rev_pos += 1
else:
rev_readpos_line.append("")
mid = []
for cf, cr in zip(gapped_f, gapped_r):
mid.append("|" if (cf == cr and cf != "-" and cr != "-") else " ")
alignment_payload = {
"fwd_positions": f"{fwd.start + 1}-{fwd.end}",
"rev_positions": f"{rev.start + 1}-{rev.end}",
"overlap": overlap,
"alignment_data_json": json.dumps(
{
"gapped_f": list(gapped_f),
"gapped_r": list(gapped_r),
"consensus_line": consensus_line,
"match_line": list("".join(mid)),
"fwd_readpos_line": fwd_readpos_line,
"fwd_qual_line": fwd_qual_line,
"rev_readpos_line": rev_readpos_line,
"rev_qual_line": rev_qual_line,
}
),
}
return consensus, alignment_payload, low_quality_positions
def write_fasta(path: str, header: str, seq: str) -> None:
with open(path, "w") as f:
f.write(f">{header}\n")
for i in range(0, len(seq), 80):
f.write(seq[i : i + 80] + "\n")
def write_text(path: str, content: str) -> None:
with open(path, "w") as f:
f.write(content)
def write_warning_html(
folder: Path,
message: str,
title: str = "Assembly Warning",
banner_message: str | None = None,
) -> None:
template = TEMPLATE_ENV.get_template("warning_template.html")
warning_html = template.render(
title=title,
banner_message=banner_message,
intro_message=message,
min_consecutive_high_quality_bases=None,
forward_min_phred_score_per_base=None,
reverse_min_phred_score_per_base=None,
empty_reads=[],
footer_message=None,
)
write_text(str(folder / "Warning.html"), warning_html)
def cleanup_folder_outputs(folder: Path) -> None:
for path in sorted(
folder.rglob("*"), key=lambda item: len(item.parts), reverse=True
):
if path.is_file() and path.suffix.lower() != ".ab1":
path.unlink()
elif path.is_dir() and path != folder:
try:
path.rmdir()
except OSError:
pass
def collect_assembly_artifacts(folder: Path) -> AssemblyArtifacts:
folder = Path(folder).resolve()
sample_name = folder.name
report_files = sorted(
[
path
for path in (
folder / f"{sample_name}_QA.html",
folder / f"{sample_name}_alignment.html",
)
if path.is_file()
]
)
consensus_files = sorted(
[
path
for path in (
folder / f"{sample_name}.fasta",
folder / f"{sample_name}_aa_alignment.fasta",
folder / "forward_trimmed.fasta",
folder / "reverse_rc_trimmed.fasta",
)
if path.is_file()
]
)
warning_file = folder / "Warning.html"
return AssemblyArtifacts(
sample_name=sample_name,
report_files=report_files,
consensus_files=consensus_files,
warning_file=warning_file if warning_file.is_file() else None,
)
def build_low_quality_table_rows(
positions: List[LowQualityPosition],
) -> List[List[str | int]]:
return [
[
pos.consensus_pos,
pos.forward_pos,
pos.forward_base,
pos.forward_qual,
pos.reverse_pos,
pos.reverse_base,
pos.reverse_qual,
pos.reason,
]
for pos in positions
]
def build_single_strand_mixture_rows(
calls,
trimmed_read: Read,
) -> List[List[str | int | float]]:
return [
[
call.read_position,
(
call.read_position - trimmed_read.start
if trimmed_read.start < call.read_position <= trimmed_read.end
else ""
),
call.trace_index,
call.primary_base,
call.secondary_base,
call.iupac_code,
call.phred_quality,
call.primary_height,
call.secondary_height,
f"{call.peak_ratio:.3f}",
f"{call.local_noise:.3f}",
f"{call.secondary_snr:.3f}",
call.confidence,
]
for call in calls
]
def summarize_non_acgt_symbols(consensus_line: list[str]) -> str:
counts = Counter(
base for base in consensus_line if base not in {"A", "C", "G", "T", "-"}
)
if not counts:
return "none"
return ", ".join(
f"{symbol}={count}"
for symbol, count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))
)
def build_single_mixture_map(
rows: List[List[str | int | float]],
use_single_mixture: str,
) -> dict[int, str]:
mixture_map: dict[int, str] = {}
allowed_confidence = {"high"} if use_single_mixture == "high" else {"high", "medium"}
for row in rows:
trimmed_position = row[1]
iupac_code = row[5]
confidence = row[12]
if (
isinstance(trimmed_position, int)
and isinstance(iupac_code, str)
and isinstance(confidence, str)
and confidence in allowed_confidence
):
mixture_map[trimmed_position] = iupac_code
return mixture_map
def render_alignment_html(
folder_name: str,
alignment_payload: dict,
reference_aa_alignment_payload: dict | None,
forward_summary: str,
reverse_summary: str,
non_acgt_summary: str,
alignment_parameters: list[tuple[str, str]],
resolve_consensus_base_rules: list[str],
low_quality_rows: List[List[str | int]],
forward_mixture_rows: List[List[str | int | float]] | None = None,
reverse_mixture_rows: List[List[str | int | float]] | None = None,
forward_mixture_header_text: str | None = None,
reverse_mixture_header_text: str | None = None,
forward_mixture_name: str | None = None,
reverse_mixture_name: str | None = None,
single_mixture_parameters: list[tuple[str, str]] | None = None,
banner_message: str | None = None,
) -> str:
template = TEMPLATE_ENV.get_template("alignment_template.html")
return template.render(
folder_name=folder_name,
banner_message=banner_message,
forward_summary=forward_summary,
reverse_summary=reverse_summary,
non_acgt_summary=non_acgt_summary,
overlap=alignment_payload["overlap"],
alignment_data_json=alignment_payload["alignment_data_json"],
reference_aa_alignment_payload=reference_aa_alignment_payload,
alignment_parameters=alignment_parameters,
resolve_consensus_base_rules=resolve_consensus_base_rules,
low_quality_headers=[
"ConsensusPos",
"ForwardPos",
"ForwardBase",
"ForwardQ",
"ReversePos",
"ReverseBase",
"ReverseQ",
"Reason",
],
low_quality_rows=low_quality_rows,
mixture_headers=[
"ReadPos",
"TrimmedPos",
"TraceIndex",
"PrimaryBase",
"SecondaryBase",
"SuggestedIUPAC",
"Phred",
"PrimaryHeight",
"SecondaryHeight",
"PeakRatio",
"LocalNoise",
"SecondarySNR",
"Confidence",
],
forward_mixture_rows=forward_mixture_rows,
reverse_mixture_rows=reverse_mixture_rows,
forward_mixture_header_text=forward_mixture_header_text,
reverse_mixture_header_text=reverse_mixture_header_text,
forward_mixture_name=forward_mixture_name,
reverse_mixture_name=reverse_mixture_name,
single_mixture_parameters=single_mixture_parameters,
)
def build_resolve_consensus_base_rules(
forward_min_phred_score_per_base: int,
reverse_min_phred_score_per_base: int,
min_phred_score_for_paired_base: int,
) -> list[str]:
template = TEMPLATE_ENV.get_template("resolve_consensus_base_rules.txt")
return [
line
for line in template.render(
forward_min_phred_score_per_base=forward_min_phred_score_per_base,
reverse_min_phred_score_per_base=reverse_min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
).splitlines()
if line.strip()
]
def reverse_complement_trace(trace: AbiTrace) -> AbiTrace:
complement = {"A": "T", "T": "A", "C": "G", "G": "C"}
rc_channels = {
complement[base]: list(reversed(values))
for base, values in trace.channels.items()
}
trace_length = len(next(iter(trace.channels.values())))
rc_base_positions = [
trace_length - 1 - pos for pos in reversed(trace.base_positions)
]
rc_seq = str(Seq(trace.seq).reverse_complement())
return AbiTrace(
name=trace.name + "_rc",
seq=rc_seq,
base_positions=rc_base_positions,
channels=rc_channels,
metadata=dict(trace.metadata),
key_sections=list(trace.key_sections),
hierarchy_text=trace.hierarchy_text,
)
def find_ab1_pair(
folder: Path,
allow_single_strand: bool = False,
) -> Tuple[Path | None, Path | None]:
ab1_files = [
p for p in folder.iterdir() if p.is_file() and p.suffix.lower() == ".ab1"
]
forward = [p for p in ab1_files if p.stem.endswith("F")]
reverse = [p for p in ab1_files if p.stem.endswith("R")]
if len(forward) == 1 and len(reverse) == 0:
if allow_single_strand:
return forward[0], None
raise ValueError(
f"Found only a forward .ab1 file ending with 'F' in {folder}; missing reverse .ab1 file ending with 'R'."
)
if len(forward) == 0 and len(reverse) == 1:
if allow_single_strand:
return None, reverse[0]
raise ValueError(
f"Found only a reverse .ab1 file ending with 'R' in {folder}; missing forward .ab1 file ending with 'F'."
)
if len(forward) != 1 or len(reverse) != 1:
raise ValueError(
"Expected exactly one forward .ab1 file ending with 'F' and one reverse .ab1 file ending with 'R' "
f"in {folder}."
)
return forward[0], reverse[0]
def generate_consensus_outputs(
folder: Path,
folder_name: str,
fwd_trim: Read,
rev_rc_trim: Read,
fwd: Read,
rev_rc_full: Read,
fwd_trace: AbiTrace,
rev_rc_trace: AbiTrace,
fwd_path: Path,
rev_path: Path,
min_overlap: int,
use_paired_mixture: bool,
use_single_mixture: str,
detect_single_strand_mixture: bool,
min_phred_score_per_base: tuple[int, int],
min_phred_score_for_paired_base: int,
min_peak_ratio: float,
min_secondary_snr: float,
noise_window_radius: int,
noise_window_exclude_radius: int,
high_phred_quality: int,
high_peak_ratio: float,
high_secondary_snr: float,
reference_nucleotide_fasta: Path | None = None,
banner_message: str | None = None,
) -> Tuple[Path, Path, Path, Path]:
(
forward_min_phred_score_per_base,
reverse_min_phred_score_per_base,
) = min_phred_score_per_base
forward_out = folder / "forward_trimmed.fasta"
reverse_out = folder / "reverse_rc_trimmed.fasta"
consensus_out = folder / f"{folder_name}.fasta"
amino_acid_alignment_out = folder / f"{folder_name}_aa_alignment.fasta"
alignment_html_out = folder / f"{folder_name}_alignment.html"
forward_mixture_rows = None
reverse_mixture_rows = None
forward_mixture_header_text = None
reverse_mixture_header_text = None
forward_mixture_name = None
reverse_mixture_name = None
single_mixture_parameters = None
reference_aa_alignment_payload = None
forward_single_mixture_map = None
reverse_single_mixture_map = None
should_detect_single_mixture = detect_single_strand_mixture or bool(use_single_mixture)
if should_detect_single_mixture:
forward_mixture_calls = detect_single_strand_mixtures(
seq=fwd_trace.seq,