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,1008 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2025
|
|
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
|
+
Functions and classes for running miniprot.
|
|
12
|
+
|
|
13
|
+
The class OverlappingCds is used after the vsearch clustering of SAUTE scaffolds and consensus estimation.
|
|
14
|
+
It maps all probe versions against the consensus sequences of vsearch clusters. It seeks
|
|
15
|
+
to find the best mapping probe version over all the consensus sequences and use it as
|
|
16
|
+
a common reference in order to determine which sequences are not overlapping.
|
|
17
|
+
Strictly non-overlapping sequences (there are no bridging scaffolds) are saved in separate files.
|
|
18
|
+
Sequences that do not meet miniprot length and similarity thresholds are discarded.
|
|
19
|
+
Exon-intron boundaries are then inferred with miniprot-boundary-scored (https://anaconda.org/bioconda/miniprot-boundary-scorer)
|
|
20
|
+
that rely on a AA substitution matrix.
|
|
21
|
+
The minimum similarity information for miniprot to keep a scaffold is passed via a dictionary with accession names
|
|
22
|
+
as keys and similarity thresholds as values.
|
|
23
|
+
# Usage example:
|
|
24
|
+
probe_fasta = ".../test_data/test_clustering/probe_3_aa.fasta"
|
|
25
|
+
consensus_contig_fasta = "../test_data/test_clustering/gene_3_consensus.fasta"
|
|
26
|
+
matrix = "../test_data/test_paralogy_2/blosum62.csv"
|
|
27
|
+
thresholds_dict = {"accession_0":0.8, accession_1":0.9, "accession_2":0.75, "accession_3":0.65}}
|
|
28
|
+
parameters = [8, 0.1, 10, 0.7] # See attribute definitions in the MiniprotInit class.
|
|
29
|
+
# load the data, perform the computation in order to separate non-overlapping sequences:
|
|
30
|
+
olc = OverlappingCds(probe_fasta, consensus_contig_fasta, matrix, thresholds_dict, *parameters)
|
|
31
|
+
# Non overlapping sets of sequences are saved in a separate file.
|
|
32
|
+
out_dir = "../test_data/test_clustering/nonoverlapping"
|
|
33
|
+
min_exon_length = 10
|
|
34
|
+
olc.save_records(out_dir, 10)
|
|
35
|
+
# save the sequence of the best overall mapping probe.
|
|
36
|
+
olc.save_best_probe("../test_data/test_clustering/gene_3_best_probe.fasta")
|
|
37
|
+
|
|
38
|
+
TODO: refactor find_global_boundaries() so that the alignments limits are inferred from the column's occupancy
|
|
39
|
+
instead of the exon's boundaries.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1"
|
|
43
|
+
|
|
44
|
+
# =======================================================================================
|
|
45
|
+
# IMPORTS
|
|
46
|
+
# =======================================================================================
|
|
47
|
+
|
|
48
|
+
from dataclasses import dataclass, field
|
|
49
|
+
from collections import defaultdict, namedtuple
|
|
50
|
+
from io import StringIO
|
|
51
|
+
import json
|
|
52
|
+
from operator import attrgetter, add, itemgetter
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
import re
|
|
55
|
+
import subprocess
|
|
56
|
+
import sys
|
|
57
|
+
import tempfile
|
|
58
|
+
from typing import Optional, Self, Literal
|
|
59
|
+
|
|
60
|
+
from Bio.SeqRecord import SeqRecord
|
|
61
|
+
from Bio import SeqIO
|
|
62
|
+
from Bio.Seq import Seq
|
|
63
|
+
from intervaltree import Interval, IntervalTree
|
|
64
|
+
import polars as pl
|
|
65
|
+
|
|
66
|
+
from gff_parser import Cds
|
|
67
|
+
from exon_intron import Exon
|
|
68
|
+
|
|
69
|
+
Region = namedtuple("Region", ["start", "end"])
|
|
70
|
+
|
|
71
|
+
MAX_EXPANSION_INTERVAL = (
|
|
72
|
+
10 # on scaffold size of flanking region on each side of the probe hits,
|
|
73
|
+
)
|
|
74
|
+
# used to find the common region that matches a given probe across multiple scaffolds.
|
|
75
|
+
SCF_PATTERN = r"^(?P<sample1>.*?)\|(?P<sample2>.*?)-(?P<probe>.*?)_EDGE_(?P<seed_id>\d+)_length_(?P<len>\d+)_cov_(?P<cov>[\w.]+):(?P<comp>\d+):(?P<ctg1>\d+):(?P<ctg2>\d+):(?P<kmers>\d+)$"
|
|
76
|
+
TRIB_ATTS = ("probe", "sample2", "seed_id", "comp", "sample1")
|
|
77
|
+
|
|
78
|
+
# =======================================================================================
|
|
79
|
+
# FUNCTIONS
|
|
80
|
+
# =======================================================================================
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def cluster_intervals(intervals: list[Interval]) -> list[Interval]:
|
|
84
|
+
"""
|
|
85
|
+
Cluster overlapping Intervals using an interval tree.
|
|
86
|
+
The data field of intervals is made out of a list of EndPoint objects.
|
|
87
|
+
"""
|
|
88
|
+
it = IntervalTree.from_tuples(intervals)
|
|
89
|
+
it.merge_overlaps(strict=True, data_reducer=add)
|
|
90
|
+
return it
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def select_best_limit(
|
|
94
|
+
intervals: list[Interval], direction: Literal["left", "right"]
|
|
95
|
+
) -> int:
|
|
96
|
+
"""
|
|
97
|
+
Select the interval that has the most number of sequences supporting it.
|
|
98
|
+
If several scaffolds share this limit, return either the smallest if 'left' is set otherwise the largest.
|
|
99
|
+
"""
|
|
100
|
+
sorted_intervals = (
|
|
101
|
+
sorted(intervals, key=lambda i: i.begin)
|
|
102
|
+
if direction == "left"
|
|
103
|
+
else sorted(intervals, key=lambda i: i.begin, reverse=True)
|
|
104
|
+
)
|
|
105
|
+
best_limit = sorted_intervals[0]
|
|
106
|
+
covered_sequences = len(best_limit.data)
|
|
107
|
+
for interval in sorted_intervals[1:]:
|
|
108
|
+
if covered_sequences > 3:
|
|
109
|
+
break
|
|
110
|
+
covered_sequences += len(interval.data)
|
|
111
|
+
best_limit = interval
|
|
112
|
+
else:
|
|
113
|
+
best_limit = sorted_intervals[0]
|
|
114
|
+
if direction == "left":
|
|
115
|
+
return sorted(best_limit.data, key=lambda i: i.idx)[0].idx
|
|
116
|
+
return sorted(best_limit.data, key=lambda i: i.idx)[-1].idx
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def merge_intervals(arr: list["OverlappingSeqs"]) -> list["OverlappingSeqs"]:
|
|
120
|
+
"""
|
|
121
|
+
Combine overlapping intervals of sequences and cluster their names.
|
|
122
|
+
We can thus separate the group of sequences according to non-overlapping intervals.
|
|
123
|
+
Used to cluster overlapping Exons from different scaffolds.
|
|
124
|
+
"""
|
|
125
|
+
# Sorting based on the increasing order of the start intervals
|
|
126
|
+
arr.sort(key=attrgetter("probe_start"))
|
|
127
|
+
index = 0
|
|
128
|
+
index_to_del = []
|
|
129
|
+
for i in range(1, len(arr)):
|
|
130
|
+
if arr[index].probe_end > arr[i].probe_start:
|
|
131
|
+
arr[index].probe_end = max(arr[index].probe_end, arr[i].probe_end)
|
|
132
|
+
arr[index].combine(arr[i].seq_names)
|
|
133
|
+
index_to_del.append(i)
|
|
134
|
+
else:
|
|
135
|
+
index += 1
|
|
136
|
+
arr[index] = arr[i]
|
|
137
|
+
return [arr[index] for index in range(len(arr)) if index not in index_to_del]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def remove_gff(miniprot_out) -> bytes:
|
|
141
|
+
"""
|
|
142
|
+
Transform a PAF file generated by 'miniprot --gff --aln' that is used to create Cds objects,
|
|
143
|
+
into a file that would be obtained with the option 'miniprot --aln' that can be used as
|
|
144
|
+
input for 'miniprot --gff --aln'.
|
|
145
|
+
"""
|
|
146
|
+
new_lines = []
|
|
147
|
+
for line in miniprot_out:
|
|
148
|
+
if line.startswith("##PAF"):
|
|
149
|
+
new_lines.append(line.replace("##PAF ", ""))
|
|
150
|
+
if (
|
|
151
|
+
line.startswith("##ATN")
|
|
152
|
+
or line.startswith("##ATA")
|
|
153
|
+
or line.startswith("##AAS")
|
|
154
|
+
or line.startswith("##AQA")
|
|
155
|
+
):
|
|
156
|
+
new_lines.append(line)
|
|
157
|
+
return "".join(new_lines).encode()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def run_miniprot(
|
|
161
|
+
probe_path: Path,
|
|
162
|
+
scaffold_path: Path,
|
|
163
|
+
threads=2,
|
|
164
|
+
min_coverage=0.01,
|
|
165
|
+
) -> StringIO:
|
|
166
|
+
"""
|
|
167
|
+
Wrapper for running miniprot.
|
|
168
|
+
:return:
|
|
169
|
+
"""
|
|
170
|
+
miniprot_cmd = f"miniprot -t {threads} --gff --aln --outn 1 -J 50 -E 3 --outc {min_coverage} {scaffold_path} {probe_path}".split()
|
|
171
|
+
try:
|
|
172
|
+
miniprot = subprocess.run(
|
|
173
|
+
miniprot_cmd,
|
|
174
|
+
timeout=1000,
|
|
175
|
+
check=True,
|
|
176
|
+
capture_output=True,
|
|
177
|
+
encoding="utf-8",
|
|
178
|
+
)
|
|
179
|
+
except FileNotFoundError as exc:
|
|
180
|
+
print(f"Process failed because the executable could not be found.\n{exc}")
|
|
181
|
+
raise
|
|
182
|
+
except subprocess.CalledProcessError as exc:
|
|
183
|
+
print(
|
|
184
|
+
f"Process failed because did not return a successful return code. "
|
|
185
|
+
f"Returned {exc.returncode}\n{exc}"
|
|
186
|
+
)
|
|
187
|
+
raise
|
|
188
|
+
except subprocess.TimeoutExpired as exc:
|
|
189
|
+
print(f"Process timed out.\n{exc}")
|
|
190
|
+
raise
|
|
191
|
+
return StringIO(miniprot.stdout)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def run_miniprot_boundary_scorer(
|
|
195
|
+
miniprot: bytes, boundary_scorer_out: Path, matrix_path: Path
|
|
196
|
+
):
|
|
197
|
+
"""
|
|
198
|
+
Wrapper for running miniprot_boundary_scorer.
|
|
199
|
+
:return:
|
|
200
|
+
"""
|
|
201
|
+
boundary_scorer_cmd = (
|
|
202
|
+
f"miniprot_boundary_scorer -o '{boundary_scorer_out}' -s {matrix_path}"
|
|
203
|
+
)
|
|
204
|
+
try:
|
|
205
|
+
subprocess.run(
|
|
206
|
+
boundary_scorer_cmd,
|
|
207
|
+
timeout=1000,
|
|
208
|
+
shell=True,
|
|
209
|
+
input=miniprot,
|
|
210
|
+
)
|
|
211
|
+
except FileNotFoundError as exc:
|
|
212
|
+
print(f"Process failed because the executable could not be found.\n{exc}")
|
|
213
|
+
raise
|
|
214
|
+
except subprocess.CalledProcessError as exc:
|
|
215
|
+
print(
|
|
216
|
+
f"Process failed because did not return a successful return code. "
|
|
217
|
+
f"Returned {exc.returncode}\n{exc}"
|
|
218
|
+
)
|
|
219
|
+
raise
|
|
220
|
+
except subprocess.TimeoutExpired as exc:
|
|
221
|
+
print(f"Process timed out.\n{exc}")
|
|
222
|
+
raise
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# =======================================================================================
|
|
226
|
+
# CLASSES
|
|
227
|
+
# =======================================================================================
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass
|
|
231
|
+
class RankCoverage:
|
|
232
|
+
"""
|
|
233
|
+
Container for keeping track of the rank of a given probe out of all probes ranks.
|
|
234
|
+
Probes are ranked by similarity to the scaffolds. The most similar is ranked first, the second most similar
|
|
235
|
+
second, etc. The sum of ranks over all scaffolds gives the final rank.
|
|
236
|
+
Attributes
|
|
237
|
+
----------
|
|
238
|
+
-rank_score: list of ranks. Each int represents how a well given probe aligns to a scaffolds
|
|
239
|
+
compared to the other probes. Smaller ranks denote better mapping.
|
|
240
|
+
-coverage: list of scaffolds to which this probe aligns.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
rank_score: list[int] = field(default_factory=list)
|
|
244
|
+
coverage: list[str] = field(default_factory=list)
|
|
245
|
+
|
|
246
|
+
def append_to(self, item_0, item_1):
|
|
247
|
+
self.rank_score.append(item_0)
|
|
248
|
+
self.coverage.append(item_1)
|
|
249
|
+
|
|
250
|
+
def get_mean_score(self, nbr_scaffolds: int):
|
|
251
|
+
"""The score used for the global ranking is based on probe positions, the total number of
|
|
252
|
+
scaffolds and the scaffolds without a match.
|
|
253
|
+
-nbr_scaffolds: the total number of scaffolds that are subjected to miniprot.
|
|
254
|
+
Missing matches get a penalty equal to the maximum rank,
|
|
255
|
+
e.g. rank_score=[0, 3, 1, 0], coverage=['contig_0', 'contig_1', 'contig_2', 'contig_3']
|
|
256
|
+
and nbr_contigs=6 (i.e. missing 'contig_4', 'contig_6') produces a score of (3+1+6+6)/6
|
|
257
|
+
"""
|
|
258
|
+
nbr_missing_scaffolds = nbr_scaffolds - len(self.coverage)
|
|
259
|
+
missing_scores = [nbr_scaffolds] * nbr_missing_scaffolds
|
|
260
|
+
return (sum(self.rank_score) + sum(missing_scores)) / nbr_scaffolds
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@dataclass(frozen=True, slots=True)
|
|
264
|
+
class ExonCorrespondence:
|
|
265
|
+
"""
|
|
266
|
+
Probe to scaffold coordinates
|
|
267
|
+
Attributes
|
|
268
|
+
----------
|
|
269
|
+
exon_probe: start-end coordinates on the probe.
|
|
270
|
+
exon_scaffold: start-end coordinates on the scaffold.
|
|
271
|
+
length_on_scaffold: nbr of AAs that are aligned between the probe and the scaffold.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
exon_probe: Exon
|
|
275
|
+
exon_scaffold: Exon
|
|
276
|
+
length_on_scaffold: int
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@dataclass(slots=True)
|
|
280
|
+
class Boundary:
|
|
281
|
+
"""
|
|
282
|
+
coordinate on scaffold
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
scaffold_name: str
|
|
286
|
+
scaffold_start: int
|
|
287
|
+
scaffold_end: int
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@dataclass(slots=True)
|
|
291
|
+
class EndPoint:
|
|
292
|
+
"""
|
|
293
|
+
Container for start or end of an exon.
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
idx: int
|
|
297
|
+
name: str
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@dataclass
|
|
301
|
+
class ExtendedCds(Cds):
|
|
302
|
+
"""
|
|
303
|
+
Cds object with additional features to handle paralogy information
|
|
304
|
+
Post Init
|
|
305
|
+
-correspondence: scaffold coordinates to probe coordinates
|
|
306
|
+
-rev_correspondence: probe coordinates to scaffold coordinates
|
|
307
|
+
-exon_correspondences: list of ExonCorrespondence(exon_probe=Exon(start=71, end=110),
|
|
308
|
+
exon_scaffold=Exon(start=17, end=132), length_on_scaffold=115) that contains the
|
|
309
|
+
coordinates of exons on probe and scaffolds.
|
|
310
|
+
#-accepted_exons: Most common exons as identified on the probes.
|
|
311
|
+
"""
|
|
312
|
+
|
|
313
|
+
correspondence: dict[int, int] = field(default_factory=dict, init=False, repr=True)
|
|
314
|
+
rev_correspondence: dict[int, int] = field(
|
|
315
|
+
default_factory=dict, init=False, repr=True
|
|
316
|
+
)
|
|
317
|
+
exon_correspondences: list[ExonCorrespondence] = field(
|
|
318
|
+
default_factory=list, init=False, repr=True
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
def __post_init__(self):
|
|
322
|
+
super().__post_init__()
|
|
323
|
+
self._reverse_correspondence()
|
|
324
|
+
|
|
325
|
+
def _reverse_correspondence(self) -> Self:
|
|
326
|
+
"""
|
|
327
|
+
Populate the correspondence, rev_correspondence, start_on_probe and end_on_probe attributes.
|
|
328
|
+
"""
|
|
329
|
+
for fragment in self.fragments:
|
|
330
|
+
for k, v in fragment.correspondence.items():
|
|
331
|
+
self.correspondence[k] = v
|
|
332
|
+
self.rev_correspondence[v] = k
|
|
333
|
+
self.start_on_probe = min(self.rev_correspondence)
|
|
334
|
+
self.end_on_probe = max(self.rev_correspondence)
|
|
335
|
+
return self
|
|
336
|
+
|
|
337
|
+
def _find_probe_exons(self, scaff_exons: list[Exon]) -> Self:
|
|
338
|
+
"""
|
|
339
|
+
Find coordinates pairs on the probe where exons are located from scaffold coordinates.
|
|
340
|
+
Because there might be boundaries slight variation due to miniprot alignment,
|
|
341
|
+
we search a few AA around the probe edge to find a correspondence on the scaffold.
|
|
342
|
+
"""
|
|
343
|
+
for scaff_exon in scaff_exons:
|
|
344
|
+
probe_start = None
|
|
345
|
+
probe_end = None
|
|
346
|
+
for idx in [0, 1, -1, 2, -2]:
|
|
347
|
+
if (
|
|
348
|
+
probe_start := self.rev_correspondence.get(scaff_exon.start + idx)
|
|
349
|
+
) is not None:
|
|
350
|
+
break
|
|
351
|
+
for idx in [0, 1, -1, 2, -2]:
|
|
352
|
+
if (
|
|
353
|
+
probe_end := self.rev_correspondence.get(scaff_exon.end + idx)
|
|
354
|
+
) is not None:
|
|
355
|
+
break
|
|
356
|
+
if None not in [probe_start, probe_end]:
|
|
357
|
+
probe_exon = Exon(probe_start, probe_end)
|
|
358
|
+
length = scaff_exon.end - scaff_exon.start
|
|
359
|
+
self.exon_correspondences.append(
|
|
360
|
+
ExonCorrespondence(probe_exon, scaff_exon, length)
|
|
361
|
+
)
|
|
362
|
+
return self
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
@dataclass
|
|
366
|
+
class OverlappingSeqs:
|
|
367
|
+
"""
|
|
368
|
+
Container for groups of sequences that overlap a common region of the probe.
|
|
369
|
+
Attributes
|
|
370
|
+
----------
|
|
371
|
+
-probe_start: the smallest index on the probe (AA space) that has a matching sequence.
|
|
372
|
+
-probe_end: the largest index on the probe (AA space) that has a matching sequence.
|
|
373
|
+
-seq_names: a list of sequence names that overlap this region.
|
|
374
|
+
-cds_dict
|
|
375
|
+
-common_exons: exons found in a majority of scaffolds
|
|
376
|
+
-paralogs: list of scaffolds that are deemed to be paralogs.
|
|
377
|
+
To do: in the final paralog selection add the sequences that are present in OverlappingCds.cds_dict
|
|
378
|
+
but disappear in filtered_cds_dict.
|
|
379
|
+
-scaffold_exons: for each exon region keep a list of scaffold Boundaries that correspond to this exon.
|
|
380
|
+
-scaffold_introns: for each intron region keep a list of scaffold Boundaries that correspond to this intron.
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
probe_start: int
|
|
384
|
+
probe_end: int
|
|
385
|
+
seq_names: list[str]
|
|
386
|
+
extended_cds_dict: dict[str, ExtendedCds] = field(
|
|
387
|
+
init=False, repr=False, default_factory=dict
|
|
388
|
+
)
|
|
389
|
+
global_start: Optional[int] = field(init=False)
|
|
390
|
+
global_end: Optional[int] = field(init=False)
|
|
391
|
+
|
|
392
|
+
def find_global_boundaries(self):
|
|
393
|
+
"""
|
|
394
|
+
For each non overlapping object, find the most common endpoint at the 5' and 3'
|
|
395
|
+
exon endpoints.
|
|
396
|
+
"""
|
|
397
|
+
start_intervals = []
|
|
398
|
+
end_intervals = []
|
|
399
|
+
if not self.extended_cds_dict:
|
|
400
|
+
self.global_start, self.global_end = None, None
|
|
401
|
+
return
|
|
402
|
+
for scaffold_name, cds in self.extended_cds_dict.items():
|
|
403
|
+
start_intervals.append(
|
|
404
|
+
Interval(
|
|
405
|
+
cds.probe_start - MAX_EXPANSION_INTERVAL,
|
|
406
|
+
cds.probe_start + MAX_EXPANSION_INTERVAL,
|
|
407
|
+
[EndPoint(cds.probe_start, scaffold_name)],
|
|
408
|
+
)
|
|
409
|
+
)
|
|
410
|
+
end_intervals.append(
|
|
411
|
+
Interval(
|
|
412
|
+
cds.probe_end - MAX_EXPANSION_INTERVAL,
|
|
413
|
+
cds.probe_end + MAX_EXPANSION_INTERVAL,
|
|
414
|
+
[EndPoint(cds.probe_end, scaffold_name)],
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
self.global_start = select_best_limit(
|
|
418
|
+
cluster_intervals(start_intervals), "left"
|
|
419
|
+
)
|
|
420
|
+
self.global_end = select_best_limit(cluster_intervals(end_intervals), "right")
|
|
421
|
+
print(f"{self.global_start=}\t{self.global_end =}")
|
|
422
|
+
|
|
423
|
+
def combine(self, other: list[str]) -> Self:
|
|
424
|
+
"""
|
|
425
|
+
Add items to seq_names
|
|
426
|
+
"""
|
|
427
|
+
self.seq_names.extend(other)
|
|
428
|
+
return self
|
|
429
|
+
|
|
430
|
+
def __repr__(self):
|
|
431
|
+
return (
|
|
432
|
+
f"probe_start={self.probe_start}, probe_end={self.probe_end},"
|
|
433
|
+
f"{sorted(self.seq_names)}"
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
@dataclass
|
|
438
|
+
class MiniprotInit:
|
|
439
|
+
"""
|
|
440
|
+
Base class for miniprot initialization.
|
|
441
|
+
Attributes
|
|
442
|
+
----------
|
|
443
|
+
-probes_fasta: path to the amino acid probes fasta file (multiprobe)
|
|
444
|
+
-scaffold_fasta: path to the nucleotide scaffold fasta file.
|
|
445
|
+
-threads: for miniprot.
|
|
446
|
+
-min_fragment_cov: fraction of the probe covered by a contig for miniprot.
|
|
447
|
+
-min_exonic_length: minimum length of concatenated exons after trimming used for saving.
|
|
448
|
+
|
|
449
|
+
Post Init
|
|
450
|
+
-probes_path: probe_fasta string converted to Path.
|
|
451
|
+
-scaffold_path: scaffold_fasta string converted to Path.
|
|
452
|
+
-probes_dict: dict of probe name as key and SeqRecord as value.
|
|
453
|
+
-scaffold_dict: dict of scaffold name as key and SeqRecord as value.
|
|
454
|
+
|
|
455
|
+
"""
|
|
456
|
+
|
|
457
|
+
probes_fasta: str
|
|
458
|
+
scaffold_fasta: str
|
|
459
|
+
substitution_matrix: str
|
|
460
|
+
threads: int = field(default=8)
|
|
461
|
+
min_fragment_cov: float = field(default=0.05)
|
|
462
|
+
min_exonic_length: int = field(default=200)
|
|
463
|
+
probes_path: Path = field(init=False, repr=False)
|
|
464
|
+
scaffold_path: Path = field(init=False, repr=False)
|
|
465
|
+
probes_dict: dict[str, SeqRecord] = field(
|
|
466
|
+
init=False, repr=False, default_factory=dict
|
|
467
|
+
)
|
|
468
|
+
scaffold_dict: dict[str, SeqRecord] = field(
|
|
469
|
+
init=False, repr=False, default_factory=dict
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
def __post_init__(self):
|
|
473
|
+
self.probes_path = Path(self.probes_fasta)
|
|
474
|
+
self.scaffold_path = Path(self.scaffold_fasta)
|
|
475
|
+
self.substitution_matrix_path = Path(self.substitution_matrix)
|
|
476
|
+
assert self.probes_path.exists(), f"{self.probes_fasta} does not exist"
|
|
477
|
+
assert self.scaffold_path.exists(), f"{self.scaffold_fasta} does not exist"
|
|
478
|
+
assert (
|
|
479
|
+
self.substitution_matrix_path.exists()
|
|
480
|
+
), f"{self.substitution_matrix} does not exist"
|
|
481
|
+
self._parse_fasta()
|
|
482
|
+
|
|
483
|
+
def _parse_fasta(self) -> None:
|
|
484
|
+
"""
|
|
485
|
+
Load the probe fasta file and the contig fasta file.
|
|
486
|
+
:return:
|
|
487
|
+
"""
|
|
488
|
+
try:
|
|
489
|
+
self.probes_dict = SeqIO.to_dict(SeqIO.parse(self.probes_path, "fasta"))
|
|
490
|
+
except Exception as err:
|
|
491
|
+
sys.exit(f"[ERROR] {err}")
|
|
492
|
+
try:
|
|
493
|
+
self.scaffold_dict = SeqIO.to_dict(SeqIO.parse(self.scaffold_path, "fasta"))
|
|
494
|
+
except Exception as err:
|
|
495
|
+
sys.exit(f"[ERROR] {err}")
|
|
496
|
+
|
|
497
|
+
def _run_miniprot(
|
|
498
|
+
self, record, probe_path_temp, scaffold_path_temp, exon_scorer=False
|
|
499
|
+
) -> StringIO:
|
|
500
|
+
SeqIO.write(record, scaffold_path_temp, "fasta")
|
|
501
|
+
miniprot_out = run_miniprot(
|
|
502
|
+
probe_path_temp,
|
|
503
|
+
scaffold_path_temp,
|
|
504
|
+
self.threads,
|
|
505
|
+
self.min_fragment_cov,
|
|
506
|
+
)
|
|
507
|
+
return miniprot_out
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
@dataclass
|
|
511
|
+
class OverlappingCds(MiniprotInit):
|
|
512
|
+
"""
|
|
513
|
+
Data structure for selecting the best probe over the entire set of scaffolds.
|
|
514
|
+
The probe is then used as reference for separating non overlapping scaffolds.
|
|
515
|
+
Attributes
|
|
516
|
+
----------
|
|
517
|
+
-user_probe: if specified, the probe with the best matching score to the scaffold is not computed with miniprot.
|
|
518
|
+
-min_global_identity_dict: per sample dictionary of identity thresholds to filter scaffolds, using
|
|
519
|
+
the global identity found over several fragments.
|
|
520
|
+
-min_global_identity: identity value to use if sample is not present in min_global_identity_dict
|
|
521
|
+
-max_intron_dict: dictionary with per sample values for maximum intron length allowed to keep a scaffold.
|
|
522
|
+
-max_intron_length: max intron length to use if a sample is not present in max_intron_dict.
|
|
523
|
+
#-min_overlapping: proportion of the exon length that is used to find an overlap with another exon.
|
|
524
|
+
The length that is explored on each endpoint of the exon is capped with hard coded boundary.
|
|
525
|
+
Post Init
|
|
526
|
+
-cds_dict: dict of contig name as key and list of Cds object as value.
|
|
527
|
+
-filtered_cds_dict: dict of scaffolds names as key and the Cds that corresponds to the best overall probe,
|
|
528
|
+
discarding sequences without matches
|
|
529
|
+
-non_overlapping: list of OverlappingSeqs objects that keep track of overlapping sequences and position on probe.
|
|
530
|
+
-best_probe: name of the probe version that has the overall best mapping score.
|
|
531
|
+
-tribble_set: set with information about the tribble components of samples, expected as ("probe", "seed_sample2", "seed_id", "comp", "sample1").
|
|
532
|
+
"""
|
|
533
|
+
|
|
534
|
+
user_probe: str = field(default=None)
|
|
535
|
+
min_global_identity_dict: dict[str:float] = field(default_factory=dict)
|
|
536
|
+
min_global_identity: float = field(default=0.85)
|
|
537
|
+
max_intron_length: int = field(default=1000)
|
|
538
|
+
max_intron_dict: dict[str, int] = field(default_factory=dict)
|
|
539
|
+
tribble_set: set[str] = field(default_factory=set)
|
|
540
|
+
|
|
541
|
+
miniprot_out: Optional[defaultdict[str, dict[str, StringIO]]] = field(
|
|
542
|
+
init=False, repr=False, default_factory=lambda: defaultdict(dict)
|
|
543
|
+
)
|
|
544
|
+
cds_dict: Optional[defaultdict[str, list[Cds]]] = field(
|
|
545
|
+
init=False, repr=False, default_factory=lambda: defaultdict(list)
|
|
546
|
+
)
|
|
547
|
+
filtered_cds_dict: dict[str, Cds] = field(
|
|
548
|
+
init=False, repr=False, default_factory=dict
|
|
549
|
+
)
|
|
550
|
+
non_overlapping: list[OverlappingSeqs] = field(init=False, default_factory=list)
|
|
551
|
+
best_probe: str = field(init=False, default=None)
|
|
552
|
+
|
|
553
|
+
def __post_init__(self):
|
|
554
|
+
super().__post_init__()
|
|
555
|
+
# run miniprot on each scaffold/probe combination
|
|
556
|
+
print(f"{self.user_probe=}")
|
|
557
|
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
|
558
|
+
tmp_probe_paths = {}
|
|
559
|
+
# write all probe records in separate file
|
|
560
|
+
if (
|
|
561
|
+
self.user_probe is not None
|
|
562
|
+
and self.user_probe in self.probes_dict.keys()
|
|
563
|
+
):
|
|
564
|
+
print(f"User selected probe is {self.user_probe}")
|
|
565
|
+
fasta_name = f"{self.user_probe}.fas"
|
|
566
|
+
probe_fasta = Path(tmpdirname) / fasta_name
|
|
567
|
+
SeqIO.write(self.probes_dict[self.user_probe], probe_fasta, "fasta")
|
|
568
|
+
tmp_probe_paths[self.user_probe] = probe_fasta
|
|
569
|
+
|
|
570
|
+
else:
|
|
571
|
+
print("creating probe list")
|
|
572
|
+
for probe_name, record in list(self.probes_dict.items())[:]:
|
|
573
|
+
fasta_name = f"{probe_name}.fas"
|
|
574
|
+
probe_fasta = Path(tmpdirname) / fasta_name
|
|
575
|
+
SeqIO.write(record, probe_fasta, "fasta")
|
|
576
|
+
tmp_probe_paths[probe_name] = probe_fasta
|
|
577
|
+
for scaffold, record in self.scaffold_dict.items():
|
|
578
|
+
accession = scaffold.split("|")[0]
|
|
579
|
+
|
|
580
|
+
print(f"working on scaffold {scaffold}")
|
|
581
|
+
for probe_name, probe_path in tmp_probe_paths.items():
|
|
582
|
+
print(f"working on probe {probe_name}")
|
|
583
|
+
fasta_name = f"{scaffold}.fas"
|
|
584
|
+
scaffold_path = Path(tmpdirname) / fasta_name
|
|
585
|
+
miniprot_result = self._run_miniprot(
|
|
586
|
+
record, probe_path, scaffold_path
|
|
587
|
+
)
|
|
588
|
+
if scaffold in self.miniprot_out:
|
|
589
|
+
self.miniprot_out[scaffold].update(
|
|
590
|
+
{probe_name: miniprot_result}
|
|
591
|
+
)
|
|
592
|
+
else:
|
|
593
|
+
self.miniprot_out[scaffold] = {probe_name: miniprot_result}
|
|
594
|
+
cds = Cds(miniprot_result)
|
|
595
|
+
cds.probe_name = probe_name
|
|
596
|
+
# print(f"{accession=} with identity {self.min_global_identity_dict.get(accession, 0.85)}")
|
|
597
|
+
if (
|
|
598
|
+
not cds.is_empty()
|
|
599
|
+
and cds.global_identity
|
|
600
|
+
>= self.min_global_identity_dict.get(
|
|
601
|
+
accession, self.min_global_identity
|
|
602
|
+
)
|
|
603
|
+
and cds.get_longest_intron()
|
|
604
|
+
< self.max_intron_dict.get(accession, self.max_intron_length)
|
|
605
|
+
):
|
|
606
|
+
self.cds_dict[scaffold].append(cds)
|
|
607
|
+
print("cds", self.cds_dict.get(scaffold))
|
|
608
|
+
scaffold_with_cds = sorted(
|
|
609
|
+
[
|
|
610
|
+
scf
|
|
611
|
+
for scf in self.scaffold_dict
|
|
612
|
+
if self.cds_dict.get(scf) is not None
|
|
613
|
+
],
|
|
614
|
+
)
|
|
615
|
+
scaffold_without_cds = sorted(
|
|
616
|
+
[scf for scf in self.scaffold_dict if scf not in scaffold_with_cds]
|
|
617
|
+
)
|
|
618
|
+
print(f"scaffold with cds:\n{"\n".join(scaffold_with_cds)}")
|
|
619
|
+
print(f"scaffold without cds:\n{"\n".join(scaffold_without_cds)}")
|
|
620
|
+
print("computing rank score")
|
|
621
|
+
self._compute_rank_score()
|
|
622
|
+
print("initial sequences:", len(self.cds_dict))
|
|
623
|
+
print("filtered sequences:", len(self.filtered_cds_dict))
|
|
624
|
+
print("sorting overlapping")
|
|
625
|
+
self._sorting_overlapping()
|
|
626
|
+
print("done sorting overlapping")
|
|
627
|
+
print("exon search")
|
|
628
|
+
self._exon_search()
|
|
629
|
+
print("exon extraction")
|
|
630
|
+
# free memory
|
|
631
|
+
self.miniprot_out = None
|
|
632
|
+
self.cds_dict = None
|
|
633
|
+
|
|
634
|
+
def _compute_rank_score(self) -> Self:
|
|
635
|
+
"""
|
|
636
|
+
Find the probe that has the best overall match using the miniprot score.
|
|
637
|
+
Populate the 'best_probe' attribute.
|
|
638
|
+
"""
|
|
639
|
+
if not self.cds_dict.values():
|
|
640
|
+
return self
|
|
641
|
+
probe_ranks = defaultdict(RankCoverage) # score per contig
|
|
642
|
+
for scaffold, list_cds in self.cds_dict.items():
|
|
643
|
+
probe_scores = sorted(
|
|
644
|
+
[(cds.probe_name, cds.get_global_score()) for cds in list_cds],
|
|
645
|
+
key=lambda x: x[1],
|
|
646
|
+
reverse=True,
|
|
647
|
+
)
|
|
648
|
+
for idx, probe_score in enumerate(probe_scores):
|
|
649
|
+
probe_name = probe_score[0]
|
|
650
|
+
probe_ranks[probe_name].append_to(idx, scaffold)
|
|
651
|
+
|
|
652
|
+
best_combination = sorted(
|
|
653
|
+
probe_ranks.items(), key=lambda x: x[1].get_mean_score(len(self.cds_dict))
|
|
654
|
+
)[0]
|
|
655
|
+
|
|
656
|
+
self.best_probe = best_combination[0]
|
|
657
|
+
print(f"Best overall probe: {self.best_probe}")
|
|
658
|
+
# Keep only scaffolds that are covered by the best probe
|
|
659
|
+
for scaffold in best_combination[1].coverage:
|
|
660
|
+
self.filtered_cds_dict[scaffold] = [
|
|
661
|
+
cds
|
|
662
|
+
for cds in self.cds_dict[scaffold]
|
|
663
|
+
if cds.probe_name == self.best_probe
|
|
664
|
+
][0]
|
|
665
|
+
return self
|
|
666
|
+
|
|
667
|
+
def _sorting_overlapping(self) -> Self:
|
|
668
|
+
"""
|
|
669
|
+
Separate the Cds by overlap with the probe sequence.
|
|
670
|
+
Populate the non_overlapping attribute
|
|
671
|
+
"""
|
|
672
|
+
interval_list = []
|
|
673
|
+
for scaffold, cds in self.filtered_cds_dict.items():
|
|
674
|
+
if cds.is_empty():
|
|
675
|
+
continue
|
|
676
|
+
start = cds.probe_start
|
|
677
|
+
end = cds.probe_end
|
|
678
|
+
interval_list.append(OverlappingSeqs(start, end, [scaffold]))
|
|
679
|
+
self.non_overlapping = merge_intervals(interval_list)
|
|
680
|
+
return self
|
|
681
|
+
|
|
682
|
+
def _boundary_scorer_parser(self, boundary_scorer_path: Path) -> list[Exon]:
|
|
683
|
+
"""
|
|
684
|
+
Parser of the miniprot_boundary_scorer output.
|
|
685
|
+
Create for each record a list of Exon objects.
|
|
686
|
+
"""
|
|
687
|
+
lines = boundary_scorer_path.read_text().split("\n")
|
|
688
|
+
exons = []
|
|
689
|
+
for line in lines:
|
|
690
|
+
if not line:
|
|
691
|
+
continue
|
|
692
|
+
splt = line.split("\t")
|
|
693
|
+
if splt[2] == "CDS" and splt[6] == "+":
|
|
694
|
+
exons.append(Exon(int(splt[3]) - 1, int(splt[4]) - 3))
|
|
695
|
+
return exons
|
|
696
|
+
|
|
697
|
+
def _exon_search(self):
|
|
698
|
+
"""run miniprot boundary scorer"""
|
|
699
|
+
if not self.non_overlapping:
|
|
700
|
+
print("No overlapping group")
|
|
701
|
+
return
|
|
702
|
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
|
703
|
+
for overlapping_gp in self.non_overlapping:
|
|
704
|
+
for scaffold_name in overlapping_gp.seq_names:
|
|
705
|
+
miniprot_result = self.miniprot_out[scaffold_name][self.best_probe]
|
|
706
|
+
miniprot_result.seek(0)
|
|
707
|
+
cds = ExtendedCds(miniprot_result)
|
|
708
|
+
boundary_scorer_out = (
|
|
709
|
+
Path(tmpdirname) / f"{scaffold_name}_boundary.gfa"
|
|
710
|
+
)
|
|
711
|
+
miniprot_result.seek(0)
|
|
712
|
+
# run miniprot_boundary scorer
|
|
713
|
+
try:
|
|
714
|
+
run_miniprot_boundary_scorer(
|
|
715
|
+
remove_gff(miniprot_result),
|
|
716
|
+
boundary_scorer_out,
|
|
717
|
+
self.substitution_matrix_path,
|
|
718
|
+
)
|
|
719
|
+
except:
|
|
720
|
+
continue
|
|
721
|
+
cds._find_probe_exons(
|
|
722
|
+
self._boundary_scorer_parser(boundary_scorer_out)
|
|
723
|
+
)
|
|
724
|
+
if not cds.exon_correspondences:
|
|
725
|
+
print(
|
|
726
|
+
f"Something went terribly wrong with {scaffold_name} as no Exon was inferred"
|
|
727
|
+
)
|
|
728
|
+
continue
|
|
729
|
+
overlapping_gp.extended_cds_dict[scaffold_name] = cds
|
|
730
|
+
overlapping_gp.find_global_boundaries()
|
|
731
|
+
|
|
732
|
+
def save_records(self, outdir: Path, min_exon_size: int) -> None:
|
|
733
|
+
"""
|
|
734
|
+
Save exonic regions, supercontigs (the whole scaffold), and genetigs that include the sequence
|
|
735
|
+
within the probe boundaries.
|
|
736
|
+
"""
|
|
737
|
+
stem_name = self.probes_path.stem
|
|
738
|
+
print(f"saving {stem_name}")
|
|
739
|
+
for overlapping_gp in self.non_overlapping:
|
|
740
|
+
prefix = (
|
|
741
|
+
f"{stem_name}_{overlapping_gp.probe_start}_{overlapping_gp.probe_end:}"
|
|
742
|
+
)
|
|
743
|
+
|
|
744
|
+
if overlapping_gp.extended_cds_dict:
|
|
745
|
+
if not overlapping_gp.global_start and not overlapping_gp.global_end:
|
|
746
|
+
sys.exit("[ERROR] 'global_start' and 'global_end' are undefined")
|
|
747
|
+
|
|
748
|
+
def _build_description() -> dict:
|
|
749
|
+
"""
|
|
750
|
+
Building the description part of the header, inspired by the way captus reports the information.
|
|
751
|
+
"""
|
|
752
|
+
name_description_dict = {}
|
|
753
|
+
for (
|
|
754
|
+
scaffold_name,
|
|
755
|
+
extended_cds,
|
|
756
|
+
) in overlapping_gp.extended_cds_dict.items():
|
|
757
|
+
probe_cov = sum(
|
|
758
|
+
[
|
|
759
|
+
frag.query_end - frag.query_start
|
|
760
|
+
for frag in extended_cds.fragments
|
|
761
|
+
]
|
|
762
|
+
)
|
|
763
|
+
probe_length = len(self.probes_dict[self.best_probe].seq)
|
|
764
|
+
identity = extended_cds.global_identity
|
|
765
|
+
score = extended_cds.get_global_score()
|
|
766
|
+
description = f"[query={self.best_probe}] [cover={probe_cov/probe_length:.2f}] [ident={identity}] [score={score}]"
|
|
767
|
+
if "SCF_PATTERN" in globals():
|
|
768
|
+
get_comp = itemgetter(*TRIB_ATTS)
|
|
769
|
+
scf_pat = re.compile(SCF_PATTERN)
|
|
770
|
+
tag = (
|
|
771
|
+
"positive"
|
|
772
|
+
if get_comp(scf_pat.search(scaffold_name))
|
|
773
|
+
in self.tribble_set
|
|
774
|
+
else "negative"
|
|
775
|
+
)
|
|
776
|
+
description += f" [tribble={tag}]"
|
|
777
|
+
|
|
778
|
+
print(
|
|
779
|
+
f"{scaffold_name}, {probe_cov/probe_length} {identity} {score}"
|
|
780
|
+
)
|
|
781
|
+
name_description_dict[scaffold_name] = description
|
|
782
|
+
return name_description_dict
|
|
783
|
+
|
|
784
|
+
# Save exons
|
|
785
|
+
name = f"{prefix}_exons.fasta"
|
|
786
|
+
out_path_exon = outdir / name
|
|
787
|
+
global_start = overlapping_gp.global_start
|
|
788
|
+
global_end = overlapping_gp.global_end
|
|
789
|
+
exon_records: list[SeqRecord] = []
|
|
790
|
+
description_dict = _build_description()
|
|
791
|
+
|
|
792
|
+
for (
|
|
793
|
+
scaffold_name,
|
|
794
|
+
extended_cds,
|
|
795
|
+
) in overlapping_gp.extended_cds_dict.items():
|
|
796
|
+
seq = str(self.scaffold_dict[scaffold_name].seq)
|
|
797
|
+
new_seq = ""
|
|
798
|
+
for exon_correspondence in extended_cds.exon_correspondences:
|
|
799
|
+
probe_start = exon_correspondence.exon_probe.start
|
|
800
|
+
probe_end = exon_correspondence.exon_probe.end
|
|
801
|
+
exon_start = exon_correspondence.exon_scaffold.start
|
|
802
|
+
exon_end = exon_correspondence.exon_scaffold.end
|
|
803
|
+
# Adjusting the exon boundaries in order to match the most common exon
|
|
804
|
+
if global_start > probe_start:
|
|
805
|
+
for idx in [0, 1, -1, 2, -2]:
|
|
806
|
+
if (
|
|
807
|
+
tmp_start := extended_cds.correspondence.get(
|
|
808
|
+
global_start + idx
|
|
809
|
+
)
|
|
810
|
+
) is not None:
|
|
811
|
+
exon_start = tmp_start
|
|
812
|
+
break
|
|
813
|
+
if probe_end > global_end:
|
|
814
|
+
for idx in [0, -1, 1, -2, 2]:
|
|
815
|
+
if (
|
|
816
|
+
tmp_end := extended_cds.correspondence.get(
|
|
817
|
+
global_end + idx
|
|
818
|
+
)
|
|
819
|
+
) is not None:
|
|
820
|
+
exon_end = tmp_end
|
|
821
|
+
break
|
|
822
|
+
new_seq += seq[exon_start:exon_end]
|
|
823
|
+
if len(new_seq) > min_exon_size:
|
|
824
|
+
exon_records.append(
|
|
825
|
+
SeqRecord(
|
|
826
|
+
Seq(new_seq),
|
|
827
|
+
name="",
|
|
828
|
+
description=description_dict[scaffold_name]
|
|
829
|
+
+ f" [length={len(new_seq)}]",
|
|
830
|
+
id=scaffold_name,
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
SeqIO.write(
|
|
834
|
+
sorted(exon_records, key=lambda x: x.id),
|
|
835
|
+
out_path_exon,
|
|
836
|
+
"fasta",
|
|
837
|
+
)
|
|
838
|
+
# Save supercontigs
|
|
839
|
+
super_name = f"{prefix}_supercontigs.fasta"
|
|
840
|
+
out_path_supercontigs = outdir / super_name
|
|
841
|
+
super_records = []
|
|
842
|
+
for scaffold_name in overlapping_gp.extended_cds_dict:
|
|
843
|
+
record = self.scaffold_dict[scaffold_name]
|
|
844
|
+
record.description = (
|
|
845
|
+
description_dict[scaffold_name] + f" [length={len(record.seq)}]"
|
|
846
|
+
)
|
|
847
|
+
super_records.append(record)
|
|
848
|
+
|
|
849
|
+
if super_records:
|
|
850
|
+
SeqIO.write(
|
|
851
|
+
sorted(super_records, key=lambda x: x.id),
|
|
852
|
+
out_path_supercontigs,
|
|
853
|
+
"fasta",
|
|
854
|
+
)
|
|
855
|
+
# save genetigs
|
|
856
|
+
genetigs_name = f"{prefix}_genetigs.fasta"
|
|
857
|
+
out_path_genetigs = outdir / genetigs_name
|
|
858
|
+
genetigs_records = []
|
|
859
|
+
|
|
860
|
+
for (
|
|
861
|
+
scaffold_name,
|
|
862
|
+
extended_cds,
|
|
863
|
+
) in overlapping_gp.extended_cds_dict.items():
|
|
864
|
+
seq = str(self.scaffold_dict[scaffold_name].seq)
|
|
865
|
+
new_scaffold = ""
|
|
866
|
+
first_exon = extended_cds.exon_correspondences[0]
|
|
867
|
+
probe_start = first_exon.exon_probe.start
|
|
868
|
+
scaffold_start = first_exon.exon_scaffold.start
|
|
869
|
+
last_exon = extended_cds.exon_correspondences[-1]
|
|
870
|
+
probe_end = last_exon.exon_probe.end
|
|
871
|
+
scaffold_end = last_exon.exon_scaffold.end
|
|
872
|
+
if global_start > probe_start:
|
|
873
|
+
for idx in [0, 1, -1, 2, -2]:
|
|
874
|
+
if (
|
|
875
|
+
tmp_start := extended_cds.correspondence.get(
|
|
876
|
+
global_start + idx
|
|
877
|
+
)
|
|
878
|
+
) is not None:
|
|
879
|
+
scaffold_start = tmp_start
|
|
880
|
+
break
|
|
881
|
+
if probe_end > global_end:
|
|
882
|
+
for idx in [0, -1, 1, -2, 2]:
|
|
883
|
+
if (
|
|
884
|
+
tmp_end := extended_cds.correspondence.get(
|
|
885
|
+
global_end + idx
|
|
886
|
+
)
|
|
887
|
+
) is not None:
|
|
888
|
+
scaffold_end = tmp_end
|
|
889
|
+
break
|
|
890
|
+
new_scaffold += seq[scaffold_start:scaffold_end]
|
|
891
|
+
if len(new_scaffold) > min_exon_size:
|
|
892
|
+
genetigs_records.append(
|
|
893
|
+
SeqRecord(
|
|
894
|
+
Seq(new_scaffold),
|
|
895
|
+
name="",
|
|
896
|
+
description=description_dict[scaffold_name]
|
|
897
|
+
+ f" [length={len(new_scaffold)}]",
|
|
898
|
+
id=scaffold_name,
|
|
899
|
+
)
|
|
900
|
+
)
|
|
901
|
+
|
|
902
|
+
if genetigs_records:
|
|
903
|
+
SeqIO.write(
|
|
904
|
+
sorted(genetigs_records, key=lambda x: x.id),
|
|
905
|
+
out_path_genetigs,
|
|
906
|
+
"fasta",
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
def save_best_probe(self, fasta_path: Path) -> None:
|
|
910
|
+
fasta_path.parent.mkdir(parents=True, exist_ok=True)
|
|
911
|
+
if not self.best_probe:
|
|
912
|
+
return
|
|
913
|
+
print(f"Saving best probe to fasta file {fasta_path}")
|
|
914
|
+
SeqIO.write([self.probes_dict[self.best_probe]], fasta_path, "fasta")
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def snakemake_call(snakemake):
|
|
918
|
+
with open(snakemake.log[0], "w") as outlog:
|
|
919
|
+
sys.stdout = sys.stderr = outlog
|
|
920
|
+
|
|
921
|
+
threads = snakemake.threads
|
|
922
|
+
outdir = Path(snakemake.output[0])
|
|
923
|
+
scfs = Path(snakemake.input.scfs)
|
|
924
|
+
probes = Path(snakemake.input.probes)
|
|
925
|
+
tribbles = snakemake.input.get("tribbles")
|
|
926
|
+
params_dict = dict(snakemake.params)
|
|
927
|
+
probes_outdir = params_dict.pop("probes_outdir")
|
|
928
|
+
|
|
929
|
+
## The divergence map is ignored if desired, falling back to a global idt threhold.
|
|
930
|
+
div_map = (
|
|
931
|
+
dict()
|
|
932
|
+
if params_dict.pop("force_global_idt")
|
|
933
|
+
else json.loads(Path(snakemake.input.div_map).read_bytes())
|
|
934
|
+
)
|
|
935
|
+
max_intron_map = json.loads(Path(snakemake.input.max_intron_map).read_bytes())
|
|
936
|
+
|
|
937
|
+
if tribbles:
|
|
938
|
+
tribble_set = set(
|
|
939
|
+
pl.read_csv(tribbles, separator="\t").cast(str).iter_rows()
|
|
940
|
+
)
|
|
941
|
+
|
|
942
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
943
|
+
if scfs.stat().st_size > 0:
|
|
944
|
+
olc = OverlappingCds(
|
|
945
|
+
probes,
|
|
946
|
+
scfs,
|
|
947
|
+
min_global_identity_dict=div_map,
|
|
948
|
+
max_intron_dict=max_intron_map,
|
|
949
|
+
threads=threads,
|
|
950
|
+
tribble_set=tribble_set if tribbles else set(),
|
|
951
|
+
**params_dict,
|
|
952
|
+
)
|
|
953
|
+
|
|
954
|
+
## Save scfs
|
|
955
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
956
|
+
olc.save_records(outdir, snakemake.params.min_exonic_length)
|
|
957
|
+
|
|
958
|
+
## Save Probes
|
|
959
|
+
if probes_outdir:
|
|
960
|
+
olc.save_best_probe(probes_outdir / probes.name)
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def main():
|
|
964
|
+
|
|
965
|
+
if len(sys.argv) != 8:
|
|
966
|
+
print(
|
|
967
|
+
"Usage: python miniprot.py <probes.fasta> <scfs.fasta> <matrix.csv> <div_map.json> <intron_map.json> <outdir> <miniprot.log>"
|
|
968
|
+
)
|
|
969
|
+
sys.exit(1)
|
|
970
|
+
|
|
971
|
+
class Run:
|
|
972
|
+
def __init__(self, **kwargs):
|
|
973
|
+
setattr(self, "_dict", kwargs)
|
|
974
|
+
for key, val in kwargs.items():
|
|
975
|
+
setattr(self, key, val)
|
|
976
|
+
|
|
977
|
+
def keys(self):
|
|
978
|
+
return self._dict.keys()
|
|
979
|
+
|
|
980
|
+
def __getitem__(self, key):
|
|
981
|
+
return self._dict[key]
|
|
982
|
+
|
|
983
|
+
# Mock the snakemake object
|
|
984
|
+
snakemake = Run(
|
|
985
|
+
input=Run(
|
|
986
|
+
probes=sys.argv[1],
|
|
987
|
+
scfs=sys.argv[2],
|
|
988
|
+
div_map=sys.argv[4],
|
|
989
|
+
max_intron_map=sys.argv[5],
|
|
990
|
+
),
|
|
991
|
+
output=[sys.argv[6]],
|
|
992
|
+
log=[sys.argv[7]],
|
|
993
|
+
threads=1,
|
|
994
|
+
params=Run(
|
|
995
|
+
substitution_matrix=sys.argv[3],
|
|
996
|
+
min_fragment_cov=0.1,
|
|
997
|
+
min_exonic_length=10,
|
|
998
|
+
),
|
|
999
|
+
)
|
|
1000
|
+
|
|
1001
|
+
snakemake_call(snakemake)
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
if __name__ == "__main__":
|
|
1005
|
+
if "snakemake" in globals():
|
|
1006
|
+
snakemake_call(snakemake)
|
|
1007
|
+
else:
|
|
1008
|
+
main()
|