NextPyper 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nextpyper/__init__.py +0 -0
- nextpyper/__main__.py +429 -0
- nextpyper/config/config.yaml +80 -0
- nextpyper/config/rich_config.yaml +54 -0
- nextpyper/config/system_config.yaml +10 -0
- nextpyper/data/blosum62.csv +32 -0
- nextpyper/data/cps_seqids.csv +674 -0
- nextpyper/data/mock/mock_args.yaml +17 -0
- nextpyper/data/mock/probes.fasta +56 -0
- nextpyper/data/mock/reads/sample1_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample1_R2.fastq +20 -0
- nextpyper/data/mock/reads/sample2_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample2_R2.fastq +20 -0
- nextpyper/data/mock/reads/sample3_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample3_R2.fastq +20 -0
- nextpyper/data/mock/sample.tsv +4 -0
- nextpyper/nextpyper.CITATION +9 -0
- nextpyper/nextpyper.LICENSE +19 -0
- nextpyper/nextpyper.VERSION +1 -0
- nextpyper/src/divergence_estimation.py +131 -0
- nextpyper/src/diversity.py +93 -0
- nextpyper/src/exon_discovery.py +294 -0
- nextpyper/src/exon_intron.py +197 -0
- nextpyper/src/fix_headers.py +107 -0
- nextpyper/src/gfa2fasta.py +71 -0
- nextpyper/src/gfa_graph.py +1245 -0
- nextpyper/src/gff_parser.py +344 -0
- nextpyper/src/graph_utils.py +201 -0
- nextpyper/src/homolog_filtering.py +411 -0
- nextpyper/src/miniprot.py +1008 -0
- nextpyper/src/multi_seq_probes.py +292 -0
- nextpyper/src/run_orfipy.py +493 -0
- nextpyper/src/sample_table.py +63 -0
- nextpyper/src/seeds_collection.py +387 -0
- nextpyper/src/summarize_results.py +507 -0
- nextpyper/src/union_find.py +65 -0
- nextpyper/src/var_asm_parser.py +229 -0
- nextpyper/test/.gitkeep +0 -0
- nextpyper/workflow/Snakefile +62 -0
- nextpyper/workflow/envs/alignment.yaml +7 -0
- nextpyper/workflow/envs/assembly.yaml +8 -0
- nextpyper/workflow/envs/clustering.yaml +9 -0
- nextpyper/workflow/envs/matching.yaml +8 -0
- nextpyper/workflow/envs/preprocessing.yaml +11 -0
- nextpyper/workflow/envs/saute.yaml +7 -0
- nextpyper/workflow/envs/translating.yaml +8 -0
- nextpyper/workflow/rules/0_preprocessing/0.1_reads.smk +90 -0
- nextpyper/workflow/rules/0_preprocessing/0.2_probes.smk +16 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.1_assembly_spades.smk +48 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.2_seeds_extension.smk +90 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.3_seeds_filtering.smk +64 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.4_seeds_clustering.smk +73 -0
- nextpyper/workflow/rules/2_homologs_assembly/2.1_saute_assembly.smk +228 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.1_allele_collapsing.smk +23 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.2_homologs_filtering.smk +76 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.3_region_separation.smk +189 -0
- nextpyper/workflow/rules/common.smk +160 -0
- nextpyper/workflow/schemas/probes.yaml +12 -0
- nextpyper/workflow/schemas/sample_table.yaml +29 -0
- nextpyper/workflow/scripts/bench_busco.py +572 -0
- nextpyper/workflow/scripts/categories_bench.sh +92 -0
- nextpyper/workflow/scripts/end_recs_parser.py +146 -0
- nextpyper/workflow/scripts/tribble_stats.py +131 -0
- nextpyper-0.1.0.dist-info/METADATA +231 -0
- nextpyper-0.1.0.dist-info/RECORD +69 -0
- nextpyper-0.1.0.dist-info/WHEEL +5 -0
- nextpyper-0.1.0.dist-info/entry_points.txt +3 -0
- nextpyper-0.1.0.dist-info/licenses/nextpyper/nextpyper.LICENSE +19 -0
- nextpyper-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2024
|
|
6
|
+
# Simón Villanueva CORRALES: simon.corrales@ibot.cas.cz
|
|
7
|
+
# Yann J.K. BERTRAND: yjk_bertrand@ybertrand.org
|
|
8
|
+
#
|
|
9
|
+
# All rights reserved.
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
Computes target-centric categories for a sample based on magicblast hits from a given assembly
|
|
13
|
+
and the reference targets, and vsearch chimera detection tables.
|
|
14
|
+
|
|
15
|
+
If batch mode is enabled, the script expects the hits, chimeras and targets
|
|
16
|
+
to be folders containing files with the same names, which will be processed as separate samples,
|
|
17
|
+
and will output a unified table with the categories for all samples.
|
|
18
|
+
|
|
19
|
+
Category codes are defined as:
|
|
20
|
+
|
|
21
|
+
0: Complete single copy
|
|
22
|
+
1: Complete and duplicated
|
|
23
|
+
2: Fragmented (single or multiple copies all fragmented)
|
|
24
|
+
3: Missing
|
|
25
|
+
4: Recovered chimera (The query is chimeric but still meets acceptance criteria)
|
|
26
|
+
|
|
27
|
+
Additional Assembly-centric metrics are computed:
|
|
28
|
+
- Chimeras (Number of chimeric sequences found)
|
|
29
|
+
- Noise sequences (count of all the query sequences that were not matched to any targets)
|
|
30
|
+
- Total number of sequences in the assembly
|
|
31
|
+
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
# =======================================================================================
|
|
35
|
+
# IMPORTS
|
|
36
|
+
# =======================================================================================
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
from collections import Counter
|
|
40
|
+
from itertools import chain, groupby, pairwise
|
|
41
|
+
from operator import itemgetter
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
import sys
|
|
44
|
+
from typing import NamedTuple
|
|
45
|
+
import argparse
|
|
46
|
+
|
|
47
|
+
from intervaltree import Interval, IntervalTree
|
|
48
|
+
import polars as pl
|
|
49
|
+
from Bio import SeqIO
|
|
50
|
+
from Bio.SeqRecord import SeqRecord
|
|
51
|
+
|
|
52
|
+
# =======================================================================================
|
|
53
|
+
# CONSTANTS
|
|
54
|
+
# =======================================================================================
|
|
55
|
+
|
|
56
|
+
# Columns parsed from magicblast output table
|
|
57
|
+
MAGIC_COLS = {
|
|
58
|
+
"# Fields: query acc.": "query",
|
|
59
|
+
"reference acc.": "target",
|
|
60
|
+
"% identity": "fident",
|
|
61
|
+
"query start": "qstart",
|
|
62
|
+
"query end": "qend",
|
|
63
|
+
"reference start": "tstart",
|
|
64
|
+
"reference end": "tend",
|
|
65
|
+
"score": "score",
|
|
66
|
+
"query length": "qlen",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
# Columns used for building the target trees
|
|
70
|
+
TREE_COLS = [
|
|
71
|
+
"query",
|
|
72
|
+
"target",
|
|
73
|
+
"tstart",
|
|
74
|
+
"tend",
|
|
75
|
+
"fident",
|
|
76
|
+
"qlen",
|
|
77
|
+
"qcov",
|
|
78
|
+
"tlen",
|
|
79
|
+
"tcov",
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
# =======================================================================================
|
|
83
|
+
# CLASSES
|
|
84
|
+
# =======================================================================================
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class QueryHit(NamedTuple):
|
|
88
|
+
query: str
|
|
89
|
+
idt: float
|
|
90
|
+
qlen: int
|
|
91
|
+
qcov: float
|
|
92
|
+
tlen: int
|
|
93
|
+
tcov: float
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class LongestPath:
|
|
97
|
+
"""Result of the get_longest_path recursion"""
|
|
98
|
+
|
|
99
|
+
path: list[Interval]
|
|
100
|
+
|
|
101
|
+
def __init__(self, *args: Interval):
|
|
102
|
+
self.path = list(args)
|
|
103
|
+
|
|
104
|
+
def __getitem__(
|
|
105
|
+
self, index: int | slice | list[int | slice]
|
|
106
|
+
) -> Interval | LongestPath:
|
|
107
|
+
match index:
|
|
108
|
+
case int():
|
|
109
|
+
return self.path[index]
|
|
110
|
+
case slice():
|
|
111
|
+
return LongestPath(*self.path[index])
|
|
112
|
+
case [*idxs] if all(isinstance(idx, (int, slice)) for idx in idxs):
|
|
113
|
+
return LongestPath(*chain.from_iterable(self.path[sli] for sli in idxs))
|
|
114
|
+
case _:
|
|
115
|
+
raise NotImplementedError(f"Given {index}")
|
|
116
|
+
|
|
117
|
+
def append(self, inter: Interval) -> None:
|
|
118
|
+
self.path.append(inter)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def path_length(self) -> int:
|
|
122
|
+
return sum(inter.length() for inter in self.path) - sum(
|
|
123
|
+
left.overlap_size(right) for left, right in pairwise(self.path)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def global_idt(self) -> float:
|
|
128
|
+
"""Calculate weighted average identity based on interval coverage.""" # ToDo: Correct for the idt of overlaps
|
|
129
|
+
|
|
130
|
+
if not self.path:
|
|
131
|
+
return 0.0
|
|
132
|
+
|
|
133
|
+
return (
|
|
134
|
+
sum(inter.data.idt * inter.length() for inter in self.path)
|
|
135
|
+
/ self.path_length
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# =======================================================================================
|
|
140
|
+
# CLASSES
|
|
141
|
+
# =======================================================================================
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def build_target_trees(
|
|
145
|
+
df: pl.DataFrame, min_idt: float = 0.7
|
|
146
|
+
) -> dict[str, IntervalTree]:
|
|
147
|
+
"""Given a Dataframe of target hits, for each target build a target tree with the
|
|
148
|
+
coverage of all the hits, while keeping only the best hit in each region. Hits
|
|
149
|
+
with similarity below min_idt are ignored.
|
|
150
|
+
Returns a dict mapping target names to IntervalTrees."""
|
|
151
|
+
|
|
152
|
+
target_hits = df.sort("target").select(TREE_COLS)
|
|
153
|
+
|
|
154
|
+
target_trees = {}
|
|
155
|
+
for target, phits in groupby(target_hits.iter_rows(), itemgetter(1)):
|
|
156
|
+
target_trees[target] = IntervalTree(
|
|
157
|
+
(
|
|
158
|
+
Interval(tstart - 1, tend, info)
|
|
159
|
+
if tstart < tend
|
|
160
|
+
else Interval(tend - 1, tstart, info)
|
|
161
|
+
)
|
|
162
|
+
for query, _, tstart, tend, idt, qlen, qcov, tlen, tcov in phits
|
|
163
|
+
if (info := QueryHit(query, idt, qlen, qcov, tlen, tcov)).idt >= min_idt
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return target_trees
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def get_longest_path(itree: IntervalTree, max_ovlp: int, min_idt: float = 0.0) -> int:
|
|
170
|
+
"""
|
|
171
|
+
Perform a dfs on the interval in order to find the combination that yields the longest path
|
|
172
|
+
Parameters
|
|
173
|
+
----------
|
|
174
|
+
itree
|
|
175
|
+
max_ovlp: max overlap in nucleotides allowed between two fragments to fuse the paths
|
|
176
|
+
|
|
177
|
+
Returns the length of the longest path
|
|
178
|
+
-------
|
|
179
|
+
|
|
180
|
+
"""
|
|
181
|
+
longest_path = LongestPath()
|
|
182
|
+
|
|
183
|
+
def dfs_util(
|
|
184
|
+
current_fragment: Interval,
|
|
185
|
+
remaining_fragments: list[Interval],
|
|
186
|
+
longest_path: LongestPath,
|
|
187
|
+
current_path: LongestPath,
|
|
188
|
+
) -> None:
|
|
189
|
+
|
|
190
|
+
if (
|
|
191
|
+
current_path.path_length > longest_path.path_length
|
|
192
|
+
and current_path.global_idt >= min_idt
|
|
193
|
+
):
|
|
194
|
+
longest_path.path = current_path.path
|
|
195
|
+
|
|
196
|
+
for next_fragment in remaining_fragments:
|
|
197
|
+
if current_fragment.overlap_size(next_fragment) <= max_ovlp:
|
|
198
|
+
current_path.append(next_fragment)
|
|
199
|
+
|
|
200
|
+
no_ovlp_fragments = sorted(
|
|
201
|
+
set(itree)
|
|
202
|
+
- set(itree.overlap(0 + max_ovlp, next_fragment.end - max_ovlp))
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
dfs_util(
|
|
206
|
+
next_fragment,
|
|
207
|
+
no_ovlp_fragments,
|
|
208
|
+
longest_path,
|
|
209
|
+
current_path[:],
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
for start_frg in sorted(itree):
|
|
213
|
+
remaining_fragments = sorted(
|
|
214
|
+
set(itree) - set(itree.overlap(0 + max_ovlp, start_frg.end - max_ovlp))
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
dfs_util(
|
|
218
|
+
start_frg,
|
|
219
|
+
remaining_fragments,
|
|
220
|
+
longest_path,
|
|
221
|
+
LongestPath(start_frg),
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
return longest_path.path_length
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def find_busco_category(
|
|
228
|
+
itree: IntervalTree,
|
|
229
|
+
min_length_percent: float,
|
|
230
|
+
max_overlap_percent: float = 0,
|
|
231
|
+
min_idt: float = 0.0,
|
|
232
|
+
) -> int:
|
|
233
|
+
"""
|
|
234
|
+
Category codes are defined as:
|
|
235
|
+
0: Complete single copy
|
|
236
|
+
1: Complete and duplicated
|
|
237
|
+
2: Fragmented success (single or multiple copies all fragmented, fulfill acceptance criteria)
|
|
238
|
+
3: Fragmented failure (single or multiple fragments detected, that do not fulfill acceptance criteria)
|
|
239
|
+
4: Missing
|
|
240
|
+
Parameters
|
|
241
|
+
----------
|
|
242
|
+
itree: intput interval tree
|
|
243
|
+
min_length_percent: percentage of the target length covered by the query to qualify for completeness
|
|
244
|
+
max_overlap_percent: percentage of the target overlap covered by the query allowed during fragment fusion
|
|
245
|
+
----------
|
|
246
|
+
Returns the category code
|
|
247
|
+
-------
|
|
248
|
+
|
|
249
|
+
"""
|
|
250
|
+
itree = itree.copy() # avoid modifying the original tree
|
|
251
|
+
if itree.is_empty():
|
|
252
|
+
return 4
|
|
253
|
+
|
|
254
|
+
interval_0 = list(itree.all_intervals)[0]
|
|
255
|
+
length_threshold = interval_0.data.tlen * min_length_percent
|
|
256
|
+
overlap_threshold = interval_0.data.qlen * max_overlap_percent
|
|
257
|
+
|
|
258
|
+
# Case complete single copy
|
|
259
|
+
if len(itree) == 1:
|
|
260
|
+
if (
|
|
261
|
+
interval_0.data.tcov >= min_length_percent
|
|
262
|
+
and interval_0.data.idt >= min_idt
|
|
263
|
+
):
|
|
264
|
+
return 0
|
|
265
|
+
return 3
|
|
266
|
+
|
|
267
|
+
longest = max(itree, key=lambda i: (i.data.tcov, i.data.idt))
|
|
268
|
+
|
|
269
|
+
# Case either complete single copy or multiple copies
|
|
270
|
+
if longest.data.tcov >= min_length_percent and longest.data.idt >= min_idt:
|
|
271
|
+
itree.remove(longest)
|
|
272
|
+
if get_longest_path(itree, overlap_threshold, min_idt) >= length_threshold:
|
|
273
|
+
return 1
|
|
274
|
+
return 0
|
|
275
|
+
|
|
276
|
+
# Case check for fragmented
|
|
277
|
+
if get_longest_path(itree, overlap_threshold, min_idt) >= length_threshold:
|
|
278
|
+
return 2
|
|
279
|
+
|
|
280
|
+
return 3
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def compute_target_covs(target_trees: dict[str, IntervalTree]) -> pl.DataFrame:
|
|
284
|
+
"""Compute the covered bases of the targets based on their interval trees."""
|
|
285
|
+
|
|
286
|
+
def tcov(tree: IntervalTree) -> int:
|
|
287
|
+
t = tree.copy()
|
|
288
|
+
t.merge_overlaps()
|
|
289
|
+
return sum(inter.length() for inter in t)
|
|
290
|
+
|
|
291
|
+
return pl.DataFrame(
|
|
292
|
+
[(probe, tcov(tree)) for probe, tree in target_trees.items()],
|
|
293
|
+
{"target": str, "cov": int},
|
|
294
|
+
orient="row",
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def categorize_sample(
|
|
299
|
+
hits: pl.DataFrame,
|
|
300
|
+
chimera_df: pl.DataFrame,
|
|
301
|
+
targets: dict[str, SeqRecord],
|
|
302
|
+
min_hit_tcov: float = 0.0,
|
|
303
|
+
min_length_cov: float = 0.7,
|
|
304
|
+
min_idt: float = 0.99,
|
|
305
|
+
include_borderline: bool = False,
|
|
306
|
+
) -> tuple[dict[str, int], int, int, pl.DataFrame]:
|
|
307
|
+
"""
|
|
308
|
+
Computes target-centric categories for a sample based on magicblast hits from a given assembly
|
|
309
|
+
and the reference targets.
|
|
310
|
+
|
|
311
|
+
Category codes are defined as:
|
|
312
|
+
0: Complete single copy
|
|
313
|
+
1: Complete and duplicated
|
|
314
|
+
2: Fragmented success (single or multiple copies all fragmented)
|
|
315
|
+
3: Fragmented failure (single or multiple fragments detected, that do not fulfill acceptance criteria)
|
|
316
|
+
4: Missing
|
|
317
|
+
|
|
318
|
+
Assembly-centric categories are also computed: Number of chimeric sequences found by
|
|
319
|
+
vsearch and the number of noise sequences (sequences that do not hit any target or do not meet the idt criteria).
|
|
320
|
+
|
|
321
|
+
Parameters
|
|
322
|
+
----------
|
|
323
|
+
hits: mmseqs hits dataframe.
|
|
324
|
+
chimera_df: dataframe with vsearch chimeric results.
|
|
325
|
+
targets: list of all the targets (including the missing ones).
|
|
326
|
+
min_hit_tcov: minimum target coverage of the QUERY to consider a hit.
|
|
327
|
+
min_idt: minimum identity of the hits on the target to accept it.
|
|
328
|
+
min_length_cov: minimum total (considering multiple hits if needed) target coverage to consider the target recovered.
|
|
329
|
+
include_borderline: whether to include borderline chimeric cases as chimeras (see vsearch documentation)
|
|
330
|
+
----------
|
|
331
|
+
Returns the category code dictionary, number of chimeras and number of noise sequences.
|
|
332
|
+
-------
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
# Get the length of the targets
|
|
336
|
+
target_lens = pl.DataFrame(
|
|
337
|
+
[(target, len(rec)) for target, rec in targets.items()],
|
|
338
|
+
{"target": str, "tlen": int},
|
|
339
|
+
orient="row",
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
# Add tlen, tcov and qcov to the hits table
|
|
343
|
+
predf = (
|
|
344
|
+
hits.select(*MAGIC_COLS.keys())
|
|
345
|
+
.rename(MAGIC_COLS)
|
|
346
|
+
.join(target_lens, on="target")
|
|
347
|
+
.with_columns(
|
|
348
|
+
fident=pl.col("fident") / 100,
|
|
349
|
+
tcov=(pl.col("tend") - pl.col("tstart")).abs() / pl.col("tlen"),
|
|
350
|
+
qcov=(pl.col("qend") - pl.col("qstart")).abs() / pl.col("qlen"),
|
|
351
|
+
)
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
df2 = predf.filter(pl.col("tcov") >= min_hit_tcov).filter(
|
|
355
|
+
pl.col("score") == pl.col("score").max().over("query")
|
|
356
|
+
)
|
|
357
|
+
chimera_subset_df = chimera_df.select(
|
|
358
|
+
pl.col("column_2"), pl.col("column_18")
|
|
359
|
+
).rename({"column_2": "query", "column_18": "chimera"})
|
|
360
|
+
|
|
361
|
+
if include_borderline:
|
|
362
|
+
final_chimera_df = chimera_subset_df.with_columns_seq(
|
|
363
|
+
chimera=pl.col("chimera") != "N"
|
|
364
|
+
).filter(pl.col("chimera"))
|
|
365
|
+
else:
|
|
366
|
+
final_chimera_df = chimera_subset_df.with_columns_seq(
|
|
367
|
+
chimera=pl.col("chimera") == "Y"
|
|
368
|
+
).filter(pl.col("chimera"))
|
|
369
|
+
|
|
370
|
+
df3 = df2.join(final_chimera_df, on="query", how="anti")
|
|
371
|
+
n_chimeras = len(final_chimera_df)
|
|
372
|
+
|
|
373
|
+
# Build target trees with and without chimeras
|
|
374
|
+
no_chim_trees = build_target_trees(df3, 0.0)
|
|
375
|
+
|
|
376
|
+
# Compute the number of "noise" sequences
|
|
377
|
+
# All unaligned sequences count
|
|
378
|
+
noise = len(hits[:, 0].unique()) - len(predf["query"].unique())
|
|
379
|
+
# Add sequences that won't be assigned to any target tree
|
|
380
|
+
noise += len(df3.filter(pl.col("fident") < 0.0))
|
|
381
|
+
|
|
382
|
+
# Compute the categories from the trees
|
|
383
|
+
no_chim_cat_dict = {
|
|
384
|
+
target: find_busco_category(tree, min_length_cov, 0, min_idt)
|
|
385
|
+
for target, tree in no_chim_trees.items()
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
final_cat = {target: no_chim_cat_dict.get(target, 4) for target in targets}
|
|
389
|
+
|
|
390
|
+
cov_df = compute_target_covs(no_chim_trees)
|
|
391
|
+
final_cov_df = target_lens.join(cov_df, on="target", how="left").fill_null(0)
|
|
392
|
+
final_cov_df = final_cov_df.select(pl.sum("tlen"), pl.sum("cov")).with_columns(
|
|
393
|
+
tcov=pl.col("cov") / pl.col("tlen")
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
return final_cat, n_chimeras, noise, final_cov_df
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def parse_args():
|
|
400
|
+
parser = argparse.ArgumentParser(description="Target benchmarking script")
|
|
401
|
+
parser.add_argument("hits", type=Path, help="Path to MMseqs hits table (.tsv)")
|
|
402
|
+
parser.add_argument(
|
|
403
|
+
"chimeras", type=Path, help="Path to vsearch chimera table (.tsv)"
|
|
404
|
+
)
|
|
405
|
+
parser.add_argument("targets", type=Path, help="Path to targets (.fasta)")
|
|
406
|
+
parser.add_argument(
|
|
407
|
+
"prefix", type=Path, help="Prefix for output tables (categories and coverages)"
|
|
408
|
+
)
|
|
409
|
+
parser.add_argument(
|
|
410
|
+
"--min_tcov",
|
|
411
|
+
type=float,
|
|
412
|
+
default=0.0,
|
|
413
|
+
help="Minimum target coverage of the query to consider a hit (default: 0.0)",
|
|
414
|
+
)
|
|
415
|
+
parser.add_argument(
|
|
416
|
+
"--min_tot_cov",
|
|
417
|
+
type=float,
|
|
418
|
+
default=0.7,
|
|
419
|
+
help="Minimum total target coverage to consider the target recovered (default: 0.7)",
|
|
420
|
+
)
|
|
421
|
+
parser.add_argument(
|
|
422
|
+
"--min_idt",
|
|
423
|
+
type=float,
|
|
424
|
+
default=0.99,
|
|
425
|
+
help="Minimum identity of the hits on the target to accept it (default: 0.99)",
|
|
426
|
+
)
|
|
427
|
+
parser.add_argument(
|
|
428
|
+
"--include_borderline",
|
|
429
|
+
action="store_true",
|
|
430
|
+
help="Include borderline chimeric cases as chimeras (see vsearch documentation)",
|
|
431
|
+
)
|
|
432
|
+
parser.add_argument(
|
|
433
|
+
"--batch",
|
|
434
|
+
action="store_true",
|
|
435
|
+
help="Process a batch of samples. Inputs (hits, chimeras, targets) are expected to be folders containing files with the same names.",
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
return parser.parse_args()
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def main():
|
|
442
|
+
args = parse_args()
|
|
443
|
+
|
|
444
|
+
hits_path = args.hits
|
|
445
|
+
chimera_path = args.chimeras
|
|
446
|
+
targets_path = args.targets
|
|
447
|
+
prefix = args.prefix
|
|
448
|
+
|
|
449
|
+
output_path = prefix.with_stem(f"{prefix.stem}_cat.tsv")
|
|
450
|
+
cov_path = prefix.with_stem(f"{prefix.stem}_cov.tsv")
|
|
451
|
+
|
|
452
|
+
min_tcov = args.min_tcov
|
|
453
|
+
min_tot_cov = args.min_tot_cov
|
|
454
|
+
min_idt = args.min_idt
|
|
455
|
+
include_borderline = args.include_borderline
|
|
456
|
+
batch = args.batch
|
|
457
|
+
|
|
458
|
+
if not hits_path.exists() or not chimera_path.exists() or not targets_path.exists():
|
|
459
|
+
print("One or more input files do not exist.")
|
|
460
|
+
sys.exit(1)
|
|
461
|
+
|
|
462
|
+
# Single sample processing
|
|
463
|
+
if not batch:
|
|
464
|
+
if (
|
|
465
|
+
not hits_path.is_file()
|
|
466
|
+
or not chimera_path.is_file()
|
|
467
|
+
or not targets_path.is_file()
|
|
468
|
+
):
|
|
469
|
+
print("One or more input paths are not files.")
|
|
470
|
+
sys.exit(1)
|
|
471
|
+
if not output_path.parent.exists():
|
|
472
|
+
output_path.parent.mkdir(parents=True)
|
|
473
|
+
|
|
474
|
+
df = pl.read_csv(
|
|
475
|
+
hits_path,
|
|
476
|
+
separator="\t",
|
|
477
|
+
has_header=True,
|
|
478
|
+
skip_rows=2,
|
|
479
|
+
schema_overrides={"% identity": pl.Float64},
|
|
480
|
+
infer_schema_length=10000,
|
|
481
|
+
)
|
|
482
|
+
chimera_df = pl.read_csv(
|
|
483
|
+
chimera_path, separator="\t", has_header=False, infer_schema_length=10000
|
|
484
|
+
)
|
|
485
|
+
targets = SeqIO.to_dict(SeqIO.parse(targets_path, "fasta"))
|
|
486
|
+
categories, n_chimeras, noise, cov_df = categorize_sample(
|
|
487
|
+
df,
|
|
488
|
+
chimera_df,
|
|
489
|
+
targets,
|
|
490
|
+
min_hit_tcov=min_tcov,
|
|
491
|
+
min_length_cov=min_tot_cov,
|
|
492
|
+
min_idt=min_idt,
|
|
493
|
+
include_borderline=include_borderline,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
with open(output_path, "w") as out_file:
|
|
497
|
+
out_file.write("target\tcategory\n")
|
|
498
|
+
for target, category in categories.items():
|
|
499
|
+
out_file.write(f"{target}\t{category}\n")
|
|
500
|
+
|
|
501
|
+
# Batch processing (unified table)
|
|
502
|
+
else:
|
|
503
|
+
if (
|
|
504
|
+
not hits_path.is_dir()
|
|
505
|
+
or not chimera_path.is_dir()
|
|
506
|
+
or not targets_path.is_dir()
|
|
507
|
+
):
|
|
508
|
+
print("One or more input paths are not directories.")
|
|
509
|
+
sys.exit(1)
|
|
510
|
+
|
|
511
|
+
with open(output_path, "w") as out_file, open(cov_path, "w") as cov_out:
|
|
512
|
+
for targets_file in sorted(targets_path.glob("*.fasta")):
|
|
513
|
+
sample_name = targets_file.stem
|
|
514
|
+
hits_file = hits_path / f"{sample_name}.tsv"
|
|
515
|
+
chimera_file = chimera_path / f"{sample_name}.tsv"
|
|
516
|
+
|
|
517
|
+
if not hits_file.exists() or not chimera_file.exists():
|
|
518
|
+
print(f"Missing files for sample {sample_name}. Skipping.")
|
|
519
|
+
continue
|
|
520
|
+
|
|
521
|
+
df = pl.read_csv(
|
|
522
|
+
hits_file,
|
|
523
|
+
separator="\t",
|
|
524
|
+
has_header=True,
|
|
525
|
+
skip_rows=2,
|
|
526
|
+
schema_overrides={"% identity": pl.Float64},
|
|
527
|
+
infer_schema_length=10000,
|
|
528
|
+
)
|
|
529
|
+
chimera_df = pl.read_csv(
|
|
530
|
+
chimera_file,
|
|
531
|
+
separator="\t",
|
|
532
|
+
has_header=False,
|
|
533
|
+
infer_schema_length=10000,
|
|
534
|
+
)
|
|
535
|
+
targets = SeqIO.to_dict(SeqIO.parse(targets_file, "fasta"))
|
|
536
|
+
categories, n_chimeras, noise, cov_df = categorize_sample(
|
|
537
|
+
df,
|
|
538
|
+
chimera_df,
|
|
539
|
+
targets,
|
|
540
|
+
min_hit_tcov=min_tcov,
|
|
541
|
+
min_length_cov=min_tot_cov,
|
|
542
|
+
min_idt=min_idt,
|
|
543
|
+
include_borderline=include_borderline,
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
# Summarize categories and write to output
|
|
547
|
+
category_counts = Counter(categories.values())
|
|
548
|
+
|
|
549
|
+
# Add number of chimeras as extra assembly-centric category
|
|
550
|
+
category_counts[5] = n_chimeras
|
|
551
|
+
|
|
552
|
+
# Add a last noise assembly-centric category with the counts of
|
|
553
|
+
# extra sequences that do not hit any target or meet idt criteria.
|
|
554
|
+
category_counts[6] = noise
|
|
555
|
+
|
|
556
|
+
# Finally, add the total number of sequences in the assembly
|
|
557
|
+
category_counts[7] = len(chimera_df)
|
|
558
|
+
|
|
559
|
+
categories = "\t".join(
|
|
560
|
+
str(category_counts.get(i, 0))
|
|
561
|
+
for i in range(max(category_counts) + 1)
|
|
562
|
+
)
|
|
563
|
+
out_file.write(f"{sample_name}\t{categories}\n")
|
|
564
|
+
|
|
565
|
+
# If requested, write also the length based recovery
|
|
566
|
+
cov_df.insert_column(0, pl.lit(sample_name)).write_csv(
|
|
567
|
+
cov_out, separator="\t", include_header=False, float_precision=5
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
if __name__ == "__main__":
|
|
572
|
+
main()
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
set -euo pipefail
|
|
3
|
+
IFS=$'\n\t'
|
|
4
|
+
|
|
5
|
+
## DESCRIPTION:
|
|
6
|
+
## This script computes the categories benchmark for a run comparing a set of queries
|
|
7
|
+
## (a program output) and a set of targets (a gold standard). The categorization is further
|
|
8
|
+
## explained in bench_busco.py.
|
|
9
|
+
|
|
10
|
+
## REQUIREMENTS:
|
|
11
|
+
## Magicblast, Vsearch, GNU parallel, python>=3.10 (with Biopython, polars and intervaltree)
|
|
12
|
+
## should be available in the PATH. bench_busco.py should be in the same directory as this script.
|
|
13
|
+
## The script will create a blast database for the targets if it does not exist.
|
|
14
|
+
|
|
15
|
+
## POSITIONAL COMMAND LINE ARGUMENTS:
|
|
16
|
+
## 1. Targets directory - gold standard targets in a single folder.
|
|
17
|
+
## 2. Queries directory - Sequence samples to be evaluated (in fasta format).
|
|
18
|
+
## 3. Tables directory - Path to write the output tables
|
|
19
|
+
## 4. Max threads to use (the number of concurrent jobs will threads/4)
|
|
20
|
+
|
|
21
|
+
## EXAMPLE OF USAGE:
|
|
22
|
+
## categories_bench.sh <targets_dir> <queries_dir> <tables_dir> <max_threads>
|
|
23
|
+
|
|
24
|
+
targets_dir=$1
|
|
25
|
+
queries_dir=$2
|
|
26
|
+
tables_dir=$3
|
|
27
|
+
max_threads=$4
|
|
28
|
+
jobs=$((max_threads / 4))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
function blast_create_db {
|
|
32
|
+
local targets=$1
|
|
33
|
+
local db_name=$2
|
|
34
|
+
makeblastdb -dbtype nucl -parse_seqids -in "${targets}" -out "${db_name}"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function magicblast_match {
|
|
38
|
+
## POSITIONAL COMMAND LINE ARGUMENTS:
|
|
39
|
+
## 1. Targets db - targets as a blast database.
|
|
40
|
+
## 2. Path to assembled sequences (query) - in fasta format.
|
|
41
|
+
## 3. Path to write the output table
|
|
42
|
+
## 4. Threads to use
|
|
43
|
+
|
|
44
|
+
local targets=$1
|
|
45
|
+
local asm=$2
|
|
46
|
+
local out_table=$3
|
|
47
|
+
local threads=$4
|
|
48
|
+
|
|
49
|
+
magicblast -splice F -outfmt "tabular" \
|
|
50
|
+
-num_threads "${threads}" \
|
|
51
|
+
-query "${asm}" \
|
|
52
|
+
-db "${targets}" \
|
|
53
|
+
-out "${out_table}"
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function vsearch_chimera {
|
|
57
|
+
## Run reference-based chimera detection with vsearch
|
|
58
|
+
|
|
59
|
+
local asm=$1
|
|
60
|
+
local targets=$2
|
|
61
|
+
local out_table=$3
|
|
62
|
+
local threads=$4
|
|
63
|
+
vsearch --db "${targets}" --uchime_ref "$asm" --uchimeout "${out_table}" --threads "${threads}"
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
export -f blast_create_db
|
|
68
|
+
export -f magicblast_match
|
|
69
|
+
export -f vsearch_chimera
|
|
70
|
+
|
|
71
|
+
mkdir -p "${tables_dir}/matches"
|
|
72
|
+
mkdir -p "${tables_dir}/vsearch"
|
|
73
|
+
|
|
74
|
+
# Check if we have to create the blast databases for the targets
|
|
75
|
+
orig_targets_dir="${targets_dir}"
|
|
76
|
+
array=($(find ${targets_dir} -mindepth 1 -maxdepth 1 -type f -name "*.ndb"))
|
|
77
|
+
if [ "${#array[@]}" -eq 0 ]; then
|
|
78
|
+
# We need to created the dbs
|
|
79
|
+
mkdir -p "${targets_dir}_dbs"
|
|
80
|
+
|
|
81
|
+
array=($(find ${targets_dir}_dbs -mindepth 1 -maxdepth 1 -type f -name "*.ndb"))
|
|
82
|
+
if [ "${#array[@]}" -eq 0 ]; then
|
|
83
|
+
# The dbs really do not exist
|
|
84
|
+
parallel "blast_create_db {} {//}_dbs/{/.}" ::: "${targets_dir}"/*.fasta
|
|
85
|
+
fi
|
|
86
|
+
|
|
87
|
+
targets_dir="${targets_dir}_dbs"
|
|
88
|
+
fi
|
|
89
|
+
|
|
90
|
+
parallel --jobs "${jobs}" magicblast_match "${targets_dir}/{/.} {} ${tables_dir}/matches/{/.}.tsv 4" ::: "${queries_dir}"/*.fasta
|
|
91
|
+
parallel --jobs "${jobs}" vsearch_chimera {} "${orig_targets_dir}/{/} ${tables_dir}/vsearch/{/.}.tsv 4" ::: "${queries_dir}"/*.fasta
|
|
92
|
+
python "$(dirname $0)/bench_busco.py" --min_idt 0.97 --batch "${tables_dir}/matches" "${tables_dir}/vsearch" "${orig_targets_dir}" "${tables_dir}/results"
|