-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
361 lines (326 loc) · 11.7 KB
/
main.py
File metadata and controls
361 lines (326 loc) · 11.7 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
#!/usr/bin/env python3
"""Batch-run folder-based AB1 assembly across all subfolders of a parent folder."""
import argparse
from multiprocessing import get_context
from pathlib import Path
import re
import sys
from openpyxl import load_workbook
from assemble import cleanup_folder_outputs, run_folder_assembly
def load_header_mapping(xlsx_path: Path) -> list[tuple[str, str]]:
workbook = load_workbook(xlsx_path, read_only=True, data_only=True)
worksheet = workbook.active
mapping: list[tuple[str, str]] = []
for row in worksheet.iter_rows(values_only=True):
if row is None or len(row) < 2:
continue
sample_id, sample_name = row[0], row[1]
if sample_id is None or sample_name is None:
continue
mapping.append((str(sample_name).strip(), str(sample_id).strip()))
workbook.close()
mapping.sort(key=lambda item: len(item[0]), reverse=True)
return mapping
def remap_header(header: str, header_mapping: list[tuple[str, str]] | None) -> str:
if not header_mapping:
return header
for sample_name, sample_id in header_mapping:
if sample_name and sample_name in header:
return header.replace(sample_name, sample_id, 1)
return header
def combine_consensus_fastas(
folder: Path,
consensus_paths: list[Path],
header_mapping: list[tuple[str, str]] | None = None,
) -> Path:
combined_fasta = folder / f"{folder.name}_combined.fasta"
with combined_fasta.open("w") as out_handle:
for consensus_path in consensus_paths:
with consensus_path.open() as in_handle:
for line in in_handle:
if line.startswith(">"):
header = line[1:].strip()
out_handle.write(f">{remap_header(header, header_mapping)}\n")
else:
out_handle.write(line)
print(combined_fasta)
return combined_fasta
def warning_category_from_file(warning_path: Path) -> str:
content = warning_path.read_text(errors="ignore")
match = re.search(r"<h1>(.*?)</h1>", content, flags=re.IGNORECASE | re.DOTALL)
if match:
category = re.sub(r"\s+", " ", match.group(1)).strip()
if category:
return category
return "Other Warning"
def slugify_warning_category(category: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "_", category.lower()).strip("_")
return slug or "other_warning"
def build_warning_index_html(folder: Path, warning_paths: list[Path], title: str) -> str:
sections = "\n".join(
(
f' <section class="warning-item">\n'
f' <h2><a href="{warning_path.relative_to(folder).as_posix()}">{warning_path.relative_to(folder).as_posix()}</a></h2>\n'
f' <iframe src="{warning_path.relative_to(folder).as_posix()}" loading="lazy"></iframe>\n'
f' </section>'
)
for warning_path in warning_paths
)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
body {{
margin: 0;
padding: 24px;
font-family: sans-serif;
background: #f5f5f5;
color: #222;
}}
h1 {{
margin-top: 0;
}}
.warning-item {{
margin-bottom: 24px;
padding: 16px;
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
}}
.warning-item h2 {{
margin-top: 0;
font-size: 1rem;
word-break: break-all;
}}
.warning-item iframe {{
width: 100%;
min-height: 420px;
border: 1px solid #ccc;
border-radius: 6px;
background: #fff;
}}
</style>
</head>
<body>
<h1>{title}</h1>
<p>Total warnings: {len(warning_paths)}</p>
{sections}
</body>
</html>
"""
def write_warning_paths(folder: Path, warning_paths: list[Path]) -> list[Path]:
grouped_paths: dict[str, list[Path]] = {}
for warning_path in warning_paths:
category = warning_category_from_file(warning_path)
grouped_paths.setdefault(category, []).append(warning_path)
output_paths: list[Path] = []
for category, paths in sorted(grouped_paths.items()):
warning_list_path = (
folder / f"{folder.name}_{slugify_warning_category(category)}.html"
)
warning_html = build_warning_index_html(
folder=folder,
warning_paths=sorted(paths),
title=f"{category} Files",
)
with warning_list_path.open("w") as handle:
handle.write(warning_html)
output_paths.append(warning_list_path)
return output_paths
def render_progress(completed: int, total: int, width: int = 32) -> None:
if total <= 0:
return
filled = int(width * completed / total)
bar = "#" * filled + "-" * (width - filled)
print(
f"\rProgress [{bar}] {completed}/{total}",
end="" if completed < total else "\n",
file=sys.stderr,
flush=True,
)
def process_sample(
task: tuple[Path, bool, bool, str, bool, str, int, int, int, bool]
) -> tuple[str, bool, bool]:
(
subfolder,
clean,
use_paired_mixture,
use_single_mixture,
allow_single_strand,
min_phred_score_per_base,
min_phred_score_for_paired_base,
min_consecutive_high_quality_bases,
min_overlap,
detect_single_strand_mixture,
) = task
cleanup_folder_outputs(subfolder)
if not clean:
run_folder_assembly(
folder=subfolder.resolve(),
use_paired_mixture=use_paired_mixture,
use_single_mixture=use_single_mixture,
allow_single_strand=allow_single_strand,
min_phred_score_per_base=min_phred_score_per_base,
min_phred_score_for_paired_base=min_phred_score_for_paired_base,
min_consecutive_high_quality_bases=min_consecutive_high_quality_bases,
min_overlap=min_overlap,
detect_single_strand_mixture=detect_single_strand_mixture,
)
consensus_path = subfolder / f"{subfolder.name}.fasta"
warning_path = subfolder / "Warning.html"
return subfolder.name, consensus_path.is_file(), warning_path.is_file()
def batch_assembly(
folder: Path,
clean: bool,
use_paired_mixture: bool,
use_single_mixture: str,
allow_single_strand: bool,
min_phred_score_per_base: str,
min_phred_score_for_paired_base: int,
min_consecutive_high_quality_bases: int,
min_overlap: int,
detect_single_strand_mixture: bool,
mapping_xlsx: Path | None,
processes: int,
) -> None:
subfolders = sorted(path for path in folder.iterdir() if path.is_dir())
if not subfolders:
raise ValueError(f"No subfolders found in: {folder}")
header_mapping = (
load_header_mapping(mapping_xlsx) if mapping_xlsx is not None else None
)
consensus_paths: list[Path] = []
warning_paths: list[Path] = []
tasks = [
(
subfolder,
clean,
use_paired_mixture,
use_single_mixture,
allow_single_strand,
min_phred_score_per_base,
min_phred_score_for_paired_base,
min_consecutive_high_quality_bases,
min_overlap,
detect_single_strand_mixture,
)
for subfolder in subfolders
]
worker_count = max(1, processes)
render_progress(0, len(tasks))
with get_context("spawn").Pool(processes=worker_count) as pool:
for completed, (sample_name, has_consensus, has_warning) in enumerate(
pool.imap_unordered(process_sample, tasks),
start=1,
):
render_progress(completed, len(tasks))
sample_folder = folder / sample_name
if has_consensus:
consensus_paths.append(sample_folder / f"{sample_name}.fasta")
elif has_warning:
warning_paths.append(sample_folder / "Warning.html")
if consensus_paths:
combine_consensus_fastas(folder, consensus_paths, header_mapping=header_mapping)
if warning_paths:
write_warning_paths(folder, sorted(warning_paths))
print(f"Consensus ready: {len(consensus_paths)}/{len(subfolders)}")
print(f"Warning: {len(warning_paths)}")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run folder-based AB1 assembly for each subfolder in a parent folder."
)
parser.add_argument(
"folder", type=Path, help="Parent folder containing sample subfolders"
)
parser.add_argument(
"--clean",
action="store_true",
help="Remove all non-.ab1 files in each sample folder before assembly",
)
parser.add_argument(
"--use-paired-mixture",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable two-strand mixture calling for high-quality disagreements (default: enabled)",
)
parser.add_argument(
"--use-single-mixture",
choices=["high", "medium"],
default="",
help="Apply single-strand candidate mixtures back onto the trimmed reads before consensus calling: high=use only high confidence, medium=use both high and medium",
)
parser.add_argument(
"--allow-single-strand",
action="store_true",
help="Allow a single forward-only or reverse-only .ab1 file and mirror it into the missing strand",
)
parser.add_argument(
"--min-phred-score-per-base",
default="20:20",
help="Minimum per-base Phred score in forward_phred:reverse_phred format (default: 20:20)",
)
parser.add_argument(
"--min-phred-score-for-paired-base",
type=int,
default=10,
help="Minimum Phred score accepted when both strands agree on the same base (default: 10)",
)
parser.add_argument(
"--min-consecutive-high-quality-bases",
type=int,
default=10,
help="Minimum consecutive high-quality bases required to keep a trimmed region",
)
parser.add_argument(
"--min-overlap",
type=int,
default=40,
help="Minimum overlap required after alignment (default: 40)",
)
parser.add_argument(
"--detect-single-strand-mixture",
action="store_true",
default=True,
help="Enable single-strand candidate mixture detection reports (default: enabled)",
)
parser.add_argument(
"--mapping-xlsx",
type=Path,
help="XLSX file where column 1 is ID and column 2 is Name for combined FASTA header remapping",
)
parser.add_argument(
"--processes",
type=int,
default=8,
help="Number of worker processes used for batch assembly (default: 8)",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
folder = args.folder.expanduser().resolve()
if not folder.is_dir():
raise ValueError(f"Not a folder: {folder}")
mapping_xlsx = (
args.mapping_xlsx.expanduser().resolve() if args.mapping_xlsx else None
)
if mapping_xlsx is not None and not mapping_xlsx.is_file():
raise ValueError(f"Not an XLSX file: {mapping_xlsx}")
batch_assembly(
folder=folder,
clean=args.clean,
use_paired_mixture=args.use_paired_mixture,
use_single_mixture=args.use_single_mixture,
allow_single_strand=args.allow_single_strand,
min_phred_score_per_base=args.min_phred_score_per_base,
min_phred_score_for_paired_base=args.min_phred_score_for_paired_base,
min_consecutive_high_quality_bases=args.min_consecutive_high_quality_bases,
min_overlap=args.min_overlap,
detect_single_strand_mixture=args.detect_single_strand_mixture,
mapping_xlsx=mapping_xlsx,
processes=args.processes,
)
if __name__ == "__main__":
main()