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,294 @@
|
|
|
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
|
+
Function and classes for defining the best
|
|
12
|
+
"""
|
|
13
|
+
from collections import deque
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from itertools import chain, product
|
|
16
|
+
from typing import Self
|
|
17
|
+
from intervaltree import Interval, IntervalTree
|
|
18
|
+
|
|
19
|
+
from exon_intron import IntervalGraph, Exon
|
|
20
|
+
|
|
21
|
+
# =======================================================================================
|
|
22
|
+
# FUNCTIONS
|
|
23
|
+
# =======================================================================================
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def fuse_intervals(intervals: list[Interval]) -> Interval:
|
|
27
|
+
"""Fuse several Interval objects into a single Interval.
|
|
28
|
+
data attributes are fused into a single list, lower and higher bounds
|
|
29
|
+
are set to min and max values respectively."""
|
|
30
|
+
min_value = sorted(intervals, key=lambda i: i.begin)[0].begin
|
|
31
|
+
max_value = sorted(intervals, key=lambda i: i.end)[-1].end
|
|
32
|
+
data = list(chain(*[x.data for x in intervals]))
|
|
33
|
+
return Interval(min_value, max_value, data)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def correctly_ordered(
|
|
37
|
+
interval_0: tuple[Interval, str], interval_1: tuple[Interval, str]
|
|
38
|
+
) -> bool:
|
|
39
|
+
"""
|
|
40
|
+
Interval_0 and interval_1 are tuples of interval and 'start'/'stop'.
|
|
41
|
+
Check that two consecutive intervals are correctly ordered, which mean
|
|
42
|
+
checking that if they contain the same name, the second idx cannot larger than the first one.
|
|
43
|
+
"""
|
|
44
|
+
# two consecutive starts or stops
|
|
45
|
+
if interval_0[1] == interval_1[1]:
|
|
46
|
+
return True
|
|
47
|
+
sequence_0_dict = {endpt.name: endpt.idx for endpt in interval_0[0].data}
|
|
48
|
+
sequence_1_dict = {endpt.name: endpt.idx for endpt in interval_1[0].data}
|
|
49
|
+
common_names = set(sequence_0_dict) & set(sequence_1_dict)
|
|
50
|
+
if not common_names:
|
|
51
|
+
return True
|
|
52
|
+
if interval_0[1] == "stop":
|
|
53
|
+
return False
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def process_it(intervals: list[Interval]) -> IntervalTree:
|
|
58
|
+
"""
|
|
59
|
+
Cluster overlapping Intervals using an interval tree.
|
|
60
|
+
The data field of intervals is made out of a list of EndPoint objects.
|
|
61
|
+
"""
|
|
62
|
+
it = IntervalTree.from_tuples(intervals)
|
|
63
|
+
used_idxs = []
|
|
64
|
+
for interval in intervals:
|
|
65
|
+
idx = interval.data[0].idx
|
|
66
|
+
if idx in used_idxs:
|
|
67
|
+
continue
|
|
68
|
+
centered_intervals = sorted(it[idx])
|
|
69
|
+
new_interval = fuse_intervals(centered_intervals)
|
|
70
|
+
del it[idx]
|
|
71
|
+
it.add(new_interval)
|
|
72
|
+
used_idxs.extend(x.idx for x in new_interval.data)
|
|
73
|
+
return it
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_longest_exon_stretch(
|
|
77
|
+
putative_exons: list["PutativeExon"], expansion_interval: int = 0
|
|
78
|
+
) -> list["Exon"]:
|
|
79
|
+
"""
|
|
80
|
+
Arrange the putative exons to find the longest exon stretch.
|
|
81
|
+
The search if done with and IntervalGraph structure.
|
|
82
|
+
-expansion_interval: number of AAs to substract from the start of the exon, to decide if it overlaps with the end.
|
|
83
|
+
"""
|
|
84
|
+
possible_exons = []
|
|
85
|
+
for putative_exon in putative_exons:
|
|
86
|
+
start_points = set([endpt.idx for endpt in putative_exon.start_sequences])
|
|
87
|
+
end_points = set([endpt.idx for endpt in putative_exon.end_sequences])
|
|
88
|
+
valid_combinations = [
|
|
89
|
+
x
|
|
90
|
+
for x in product(start_points, end_points)
|
|
91
|
+
if x[0] - expansion_interval < x[1]
|
|
92
|
+
]
|
|
93
|
+
for combination in valid_combinations:
|
|
94
|
+
possible_exons.append(Exon(*combination))
|
|
95
|
+
IG = IntervalGraph(possible_exons)
|
|
96
|
+
return IG.get_best_path().path
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class PutativeExon:
|
|
101
|
+
"""
|
|
102
|
+
Keep the information about the actual sequence starting and ending points.
|
|
103
|
+
Unlike the Exon object, here the start and end are a list of all empirical coordinates that are deemed
|
|
104
|
+
to correspond to the same biological exon.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
__slots__ = ["start_sequences", "end_sequences"]
|
|
108
|
+
start_sequences: list[str]
|
|
109
|
+
end_sequences: list[str]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass
|
|
113
|
+
class EndPoint:
|
|
114
|
+
"""
|
|
115
|
+
Container for start or end of an exon.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
__slots__ = ["idx", "name"]
|
|
119
|
+
idx: int
|
|
120
|
+
name: str
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass
|
|
124
|
+
class DiscoverExons:
|
|
125
|
+
"""
|
|
126
|
+
Data structure for selecting the most common exon boundaries
|
|
127
|
+
Attributes
|
|
128
|
+
----------
|
|
129
|
+
-exon_intervals: list of exon intervals found by miniprot boundary scorer for the scaffolds.
|
|
130
|
+
-expansion_threshold: length proportion of the exon that are expanded around the exons endpoints in oder
|
|
131
|
+
to form an interval. Start/stop intervals are then compared between putative exons.
|
|
132
|
+
Post Init
|
|
133
|
+
-starts: for each start point, the expansion produces an interval.
|
|
134
|
+
-ends: for each end point, the expansion produces an interval.
|
|
135
|
+
-exons: list of Exon objects.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
exon_intervals: list[Interval]
|
|
139
|
+
expansion_threshold: float = field(default=0.1)
|
|
140
|
+
starts: list[Interval] = field(default_factory=list, init=False, repr=True)
|
|
141
|
+
ends: list[Interval] = field(default_factory=list, init=False, repr=True)
|
|
142
|
+
exons: list[Exon] = field(default_factory=list, init=False, repr=True)
|
|
143
|
+
|
|
144
|
+
def __post_init__(self):
|
|
145
|
+
self._get_starts_ends()
|
|
146
|
+
self._find_exons()
|
|
147
|
+
|
|
148
|
+
def get_exons(self) -> list[Exon]:
|
|
149
|
+
return self.exons
|
|
150
|
+
|
|
151
|
+
def _get_starts_ends(self) -> Self:
|
|
152
|
+
"""
|
|
153
|
+
Populate the starts and ends attributes.
|
|
154
|
+
MAX_EXPANSION_INTERVAL is the range in AA over an index that can encompass a second index.
|
|
155
|
+
"""
|
|
156
|
+
MAX_EXPANSION_INTERVAL = 10
|
|
157
|
+
for elt in self.exon_intervals:
|
|
158
|
+
# Remove the shortest exons
|
|
159
|
+
if elt.end - elt.begin <= MAX_EXPANSION_INTERVAL:
|
|
160
|
+
continue
|
|
161
|
+
expansion = max(
|
|
162
|
+
MAX_EXPANSION_INTERVAL,
|
|
163
|
+
int((elt.end - elt.begin) * self.expansion_threshold),
|
|
164
|
+
)
|
|
165
|
+
start_min, start_max = max(elt.begin - expansion, 0), elt.begin + expansion
|
|
166
|
+
end_min, end_max = elt.end - expansion, elt.end + expansion
|
|
167
|
+
self.starts.append(
|
|
168
|
+
Interval(start_min, start_max, [EndPoint(elt.begin, elt.data)])
|
|
169
|
+
)
|
|
170
|
+
self.ends.append(Interval(end_min, end_max, [EndPoint(elt.end, elt.data)]))
|
|
171
|
+
return self
|
|
172
|
+
|
|
173
|
+
def _find_exons(self) -> Self:
|
|
174
|
+
"""
|
|
175
|
+
Populate the exon attribute.
|
|
176
|
+
"""
|
|
177
|
+
# Fuse overlapping intervals for start and end points of exon intervals using interval tree.
|
|
178
|
+
intervals_start = sorted(process_it(self.starts), key=lambda i: i.begin)
|
|
179
|
+
intervals_end = sorted(process_it(self.ends), key=lambda i: i.end)
|
|
180
|
+
# Process the sorted list of start and end intervals.
|
|
181
|
+
all_intervals = []
|
|
182
|
+
all_intervals.extend((interval, "start") for interval in intervals_start)
|
|
183
|
+
all_intervals.extend((interval, "stop") for interval in intervals_end)
|
|
184
|
+
tmp_sorted_intervals = deque(sorted(all_intervals, key=lambda x: x[0].begin))
|
|
185
|
+
first_interval = tmp_sorted_intervals.popleft()
|
|
186
|
+
sorted_intervals = [first_interval]
|
|
187
|
+
# Reorder the intervals
|
|
188
|
+
while tmp_sorted_intervals:
|
|
189
|
+
second_interval = tmp_sorted_intervals.popleft()
|
|
190
|
+
if not correctly_ordered(first_interval, second_interval):
|
|
191
|
+
sorted_intervals.pop()
|
|
192
|
+
sorted_intervals.extend([second_interval, first_interval])
|
|
193
|
+
else:
|
|
194
|
+
sorted_intervals.append(second_interval)
|
|
195
|
+
first_interval = second_interval
|
|
196
|
+
|
|
197
|
+
print("sorted intervals", sorted_intervals)
|
|
198
|
+
putative_exons = []
|
|
199
|
+
start = sorted_intervals[0]
|
|
200
|
+
start_interval = start[0]
|
|
201
|
+
current_color = start[1]
|
|
202
|
+
stop_interval = None
|
|
203
|
+
queue = deque(sorted_intervals[1:])
|
|
204
|
+
while queue:
|
|
205
|
+
print(f"{start_interval=}, {stop_interval=}, {current_color=}")
|
|
206
|
+
elt = queue.popleft()
|
|
207
|
+
# print("length of queue:", len(queue))
|
|
208
|
+
elt_interval = elt[0]
|
|
209
|
+
elt_color = elt[1]
|
|
210
|
+
# print(f"new elm {elt}")
|
|
211
|
+
if current_color == "start":
|
|
212
|
+
if elt_color == "start":
|
|
213
|
+
if len(elt_interval.data) > len(start_interval.data):
|
|
214
|
+
start_interval = elt_interval
|
|
215
|
+
if len(elt) == 0:
|
|
216
|
+
# Something went wrong and the last colour is not "stop"
|
|
217
|
+
break
|
|
218
|
+
elif elt_color == "stop":
|
|
219
|
+
current_color = "stop"
|
|
220
|
+
stop_interval = elt_interval
|
|
221
|
+
# End of list
|
|
222
|
+
if len(elt) == 0:
|
|
223
|
+
# print("appending")
|
|
224
|
+
putative_exons.append(
|
|
225
|
+
PutativeExon(start_interval.data, stop_interval.data)
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
elif current_color == "stop":
|
|
229
|
+
if elt_color == "start":
|
|
230
|
+
# print("appending")
|
|
231
|
+
putative_exons.append(
|
|
232
|
+
PutativeExon(start_interval.data, stop_interval.data)
|
|
233
|
+
)
|
|
234
|
+
start_interval = elt_interval
|
|
235
|
+
current_color = "start"
|
|
236
|
+
stop_interval = None
|
|
237
|
+
elif elt_color == "stop":
|
|
238
|
+
# switch to this new stop if there are more sequences that support this stop
|
|
239
|
+
# or if there are the same number but contain at least one common sequence withthe start.
|
|
240
|
+
|
|
241
|
+
if len(elt_interval.data) > len(stop_interval.data):
|
|
242
|
+
stop_interval = elt_interval
|
|
243
|
+
elif len(elt_interval.data) == len(stop_interval.data):
|
|
244
|
+
if {d.name for d in elt_interval.data} & {
|
|
245
|
+
d.name for d in stop_interval.data
|
|
246
|
+
}:
|
|
247
|
+
stop_interval = elt_interval
|
|
248
|
+
if len(queue) == 0:
|
|
249
|
+
# print("appending")
|
|
250
|
+
putative_exons.append(
|
|
251
|
+
PutativeExon(start_interval.data, stop_interval.data)
|
|
252
|
+
)
|
|
253
|
+
longest_stretch_exons = find_longest_exon_stretch(putative_exons)
|
|
254
|
+
if not longest_stretch_exons:
|
|
255
|
+
return self
|
|
256
|
+
# The boundaries need to be adjusted
|
|
257
|
+
queue = deque(longest_stretch_exons)
|
|
258
|
+
query = queue.popleft()
|
|
259
|
+
self.exons.append(query)
|
|
260
|
+
while queue:
|
|
261
|
+
target = queue.popleft()
|
|
262
|
+
if query.end != target.start:
|
|
263
|
+
self.exons.append(target)
|
|
264
|
+
else:
|
|
265
|
+
self.exons.append(Exon(target.start + 1, target.end))
|
|
266
|
+
query = target
|
|
267
|
+
return self
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
if __name__ == "__main__":
|
|
271
|
+
|
|
272
|
+
inputs = [
|
|
273
|
+
(40, 70, "x"),
|
|
274
|
+
(40, 70, "a"),
|
|
275
|
+
(50, 70, "b"),
|
|
276
|
+
(70, 140, "c"),
|
|
277
|
+
(71, 110, "a"),
|
|
278
|
+
(107, 142, "b"),
|
|
279
|
+
(112, 142, "a"),
|
|
280
|
+
(143, 178, "a"),
|
|
281
|
+
(143, 170, "b"),
|
|
282
|
+
(112, 191, "d"),
|
|
283
|
+
]
|
|
284
|
+
|
|
285
|
+
inputs = [
|
|
286
|
+
(86, 180, "a"),
|
|
287
|
+
(89, 142, "b"),
|
|
288
|
+
(91, 191, "c"),
|
|
289
|
+
(93, 191, "d"),
|
|
290
|
+
]
|
|
291
|
+
|
|
292
|
+
input_intervals = [Interval(*x) for x in inputs]
|
|
293
|
+
disco = DiscoverExons(input_intervals)
|
|
294
|
+
print("putative exons", disco.exons)
|
|
@@ -0,0 +1,197 @@
|
|
|
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
|
+
__version__ = "0.1"
|
|
12
|
+
|
|
13
|
+
# =======================================================================================
|
|
14
|
+
# IMPORTS
|
|
15
|
+
# =======================================================================================
|
|
16
|
+
from collections import namedtuple
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Optional, Self
|
|
19
|
+
|
|
20
|
+
# Named tuple that keeps the nodes in a path either as their suffixes or their cds and the sum of their length.
|
|
21
|
+
GraphPath = namedtuple("GraphPath", ["path", "length"])
|
|
22
|
+
|
|
23
|
+
# =======================================================================================
|
|
24
|
+
# FUNCTIONS
|
|
25
|
+
# =======================================================================================
|
|
26
|
+
|
|
27
|
+
# =======================================================================================
|
|
28
|
+
# CLASSES
|
|
29
|
+
# =======================================================================================
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Exon:
|
|
34
|
+
__slots__ = ["start", "end"]
|
|
35
|
+
start: int
|
|
36
|
+
end: int
|
|
37
|
+
|
|
38
|
+
def overlaps(self, other: "Exon") -> bool:
|
|
39
|
+
first, second = sorted([self, other], key=lambda x: x.start)
|
|
40
|
+
if first.end > second.start:
|
|
41
|
+
return True
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Node:
|
|
47
|
+
key: int | str
|
|
48
|
+
interval: Exon = field(repr=True)
|
|
49
|
+
children: list["Node"] = field(init=False, default_factory=list)
|
|
50
|
+
root: bool = field(init=False, default=True)
|
|
51
|
+
|
|
52
|
+
def get_key(self):
|
|
53
|
+
return self.key
|
|
54
|
+
|
|
55
|
+
def overlap(self, other: "Node") -> bool:
|
|
56
|
+
if self.interval.overlaps(other.interval):
|
|
57
|
+
return True
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
def add_child(self, child: "Node") -> Self:
|
|
61
|
+
self.children.append(child)
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def not_root(self) -> Self:
|
|
65
|
+
self.root = False
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
def is_root(self) -> bool:
|
|
69
|
+
return self.root
|
|
70
|
+
|
|
71
|
+
def has_children(self) -> bool:
|
|
72
|
+
if self.children:
|
|
73
|
+
return True
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
def get_length(self) -> int:
|
|
77
|
+
return self.interval.end - self.interval.start
|
|
78
|
+
|
|
79
|
+
def get_children(self) -> list["Node"]:
|
|
80
|
+
return self.children
|
|
81
|
+
|
|
82
|
+
def get_interval(self) -> Exon:
|
|
83
|
+
return self.interval
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class IntervalGraph:
|
|
88
|
+
"""
|
|
89
|
+
Data structure that create a graph of non overlapping intervals (nodes).
|
|
90
|
+
Intervals are ordered by starting position. Starting with each target interval, we iterate over the rest
|
|
91
|
+
of the intervals that start at greater position. If these interval don't overlap with the target
|
|
92
|
+
we draw an edge, otherwise we skip the interval. Once the graph is constructed, we get the starting nodes
|
|
93
|
+
as those that do not have preceding intervals (i.e. no parent node). Finding the longest path of non-overlapping
|
|
94
|
+
intervals requires a DSF from each starting node.
|
|
95
|
+
Attributes
|
|
96
|
+
----------
|
|
97
|
+
-interval_list: a list of Cds objects.
|
|
98
|
+
-nodes: a list of Node objects.
|
|
99
|
+
-node_dict: a dictionary of Node objects as value and cds suffix number as key.
|
|
100
|
+
-root_nodes: starting node that do not have parents.
|
|
101
|
+
-all_graph_path: all possible paths from a root_node to a leaf node.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
interval_list: list[Exon]
|
|
105
|
+
nodes: list[Node] = field(init=False, default_factory=list)
|
|
106
|
+
node_dict: dict[int, Node] = field(init=False, default_factory=dict)
|
|
107
|
+
root_nodes: list[int] = field(init=False, default_factory=list)
|
|
108
|
+
all_graph_path: list[GraphPath] = field(init=False, default_factory=list)
|
|
109
|
+
|
|
110
|
+
def __post_init__(self):
|
|
111
|
+
self._create_nodes()
|
|
112
|
+
self._create_edges()
|
|
113
|
+
self._find_roots()
|
|
114
|
+
self._explore_graph()
|
|
115
|
+
|
|
116
|
+
def _create_nodes(self) -> Self:
|
|
117
|
+
nodes = []
|
|
118
|
+
for idx, interval in enumerate(self.interval_list):
|
|
119
|
+
node = Node(idx, interval)
|
|
120
|
+
nodes.append(node)
|
|
121
|
+
self.nodes = sorted(nodes, key=lambda n: n.interval.start)
|
|
122
|
+
return self
|
|
123
|
+
|
|
124
|
+
def _create_edges(self) -> Self:
|
|
125
|
+
"""Connect the node to all other nodes whose cds is left of the current node cds and whose sequences
|
|
126
|
+
do not overlap"""
|
|
127
|
+
self.node_dict = {node.get_key(): node for node in self.nodes}
|
|
128
|
+
for idx, node in enumerate(self.nodes):
|
|
129
|
+
for other_node in self.nodes[idx + 1 :]:
|
|
130
|
+
if node.overlap(other_node):
|
|
131
|
+
continue
|
|
132
|
+
node.add_child(other_node)
|
|
133
|
+
other_node.not_root()
|
|
134
|
+
return self
|
|
135
|
+
|
|
136
|
+
def _find_roots(self) -> Self:
|
|
137
|
+
"""
|
|
138
|
+
A root note has no parent node. Non-root nodes were tagged during graph construction.
|
|
139
|
+
"""
|
|
140
|
+
self.root_nodes = [node.get_key() for node in self.nodes if node.is_root()]
|
|
141
|
+
return self
|
|
142
|
+
|
|
143
|
+
def _explore_graph(self) -> Self:
|
|
144
|
+
"""
|
|
145
|
+
Find all paths between root nodes (nodes without parent) and leaf nodes (nodes without children).
|
|
146
|
+
:return:
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
def dfs_util(
|
|
150
|
+
current_node: Node, current_path: list[Node] = [], current_length: int = 0
|
|
151
|
+
) -> GraphPath:
|
|
152
|
+
current_path_copy = current_path.copy()
|
|
153
|
+
current_length_copy = current_length
|
|
154
|
+
current_path_copy.append(current_node)
|
|
155
|
+
current_length_copy += current_node.get_length()
|
|
156
|
+
if not current_node.has_children():
|
|
157
|
+
new_path = GraphPath(
|
|
158
|
+
[node.get_key() for node in current_path_copy],
|
|
159
|
+
current_length_copy,
|
|
160
|
+
)
|
|
161
|
+
self.all_graph_path.append(new_path)
|
|
162
|
+
return
|
|
163
|
+
else:
|
|
164
|
+
for child in current_node.get_children():
|
|
165
|
+
dfs_util(child, current_path_copy, current_length_copy)
|
|
166
|
+
|
|
167
|
+
for key in self.root_nodes:
|
|
168
|
+
root = self.node_dict[key]
|
|
169
|
+
dfs_util(root)
|
|
170
|
+
return self
|
|
171
|
+
|
|
172
|
+
def get_best_path(self) -> Optional[GraphPath]:
|
|
173
|
+
"""Out of all the path found with the DFS, select the longest"""
|
|
174
|
+
if not self.all_graph_path:
|
|
175
|
+
return
|
|
176
|
+
paths = sorted(self.all_graph_path, key=lambda x: x.length, reverse=True)
|
|
177
|
+
best = paths[0]
|
|
178
|
+
interval_path = [self.node_dict[node].get_interval() for node in best.path]
|
|
179
|
+
return GraphPath(interval_path, best.length)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
inputs = [
|
|
184
|
+
(143, 178),
|
|
185
|
+
(107, 142),
|
|
186
|
+
(50, 70),
|
|
187
|
+
(60, 80),
|
|
188
|
+
(71, 110),
|
|
189
|
+
(111, 142),
|
|
190
|
+
(40, 70),
|
|
191
|
+
(150, 170),
|
|
192
|
+
(190, 191),
|
|
193
|
+
]
|
|
194
|
+
interval_list = [Exon(*x) for x in inputs]
|
|
195
|
+
print(interval_list)
|
|
196
|
+
IG = IntervalGraph(interval_list)
|
|
197
|
+
print(IG.get_best_path())
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
"""Fix Saute sequences headers by updating the length and cov values and adding the sample name"""
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1"
|
|
13
|
+
|
|
14
|
+
# =======================================================================================
|
|
15
|
+
# IMPORTS
|
|
16
|
+
# =======================================================================================
|
|
17
|
+
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from itertools import pairwise
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
from Bio import SeqIO
|
|
24
|
+
from Bio.SeqRecord import SeqRecord
|
|
25
|
+
from more_itertools import interleave_longest
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# =============================================================================
|
|
29
|
+
# FUNCTIONS
|
|
30
|
+
# =============================================================================
|
|
31
|
+
|
|
32
|
+
SAUTE_PAT = r"^(?P<sample>.*?)-(?P<probe>.*?)_EDGE_(?P<seed_id>\d+)_length_(?P<len>\d+)_cov_(?P<cov>[\w.]+):[^ ]+:(?P<kmers>\d+)$"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def update_specs(rec: SeqRecord, pat: re.Pattern) -> SeqRecord:
|
|
36
|
+
"""Mach the record name with the provided pattern and replace
|
|
37
|
+
the length and cov matching groups.
|
|
38
|
+
|
|
39
|
+
The pattern must have len, cov and kmers as capture groups.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
if (match := pat.search(rec.id)) is None:
|
|
43
|
+
raise ValueError(f"{rec.id} does not match {pat.pattern}")
|
|
44
|
+
|
|
45
|
+
info = match.groupdict()
|
|
46
|
+
info["len"] = str(len(rec))
|
|
47
|
+
info["cov"] = str(round(int(info["kmers"]) / len(rec), 4))
|
|
48
|
+
|
|
49
|
+
prefix = rec.id[0 : match.regs[1][0]]
|
|
50
|
+
suffix = rec.id[match.regs[-1][1] : len(rec.id)]
|
|
51
|
+
|
|
52
|
+
gaps = [rec.id[a:b] for (_, a), (b, _) in pairwise(match.regs[1:])]
|
|
53
|
+
name = prefix + "".join(interleave_longest(info.values(), gaps)) + suffix
|
|
54
|
+
|
|
55
|
+
rec.name = rec.description = ""
|
|
56
|
+
rec.id = name
|
|
57
|
+
return rec
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def fix_saute_headers(
|
|
61
|
+
recs: list[SeqRecord], sample: str, pattern: str
|
|
62
|
+
) -> list[SeqRecord]:
|
|
63
|
+
"""Given a Saute assembly, fix the sequence headers by prepending the
|
|
64
|
+
provided sample to the name, updating the specs (length, cov) and
|
|
65
|
+
removing the "Contig_" at the start.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
pat = re.compile(pattern, re.VERBOSE)
|
|
69
|
+
new_recs = []
|
|
70
|
+
for rec in recs:
|
|
71
|
+
new_rec = update_specs(rec, pat)
|
|
72
|
+
new_rec.id = f"{sample}|{new_rec.id.removeprefix("Contig_")}"
|
|
73
|
+
new_recs.append(new_rec)
|
|
74
|
+
|
|
75
|
+
return new_recs
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def snakemake_call(snakemake):
|
|
79
|
+
records_path = Path(snakemake.input[0])
|
|
80
|
+
out_path = Path(snakemake.output[0])
|
|
81
|
+
sample = snakemake.params.sample
|
|
82
|
+
pattern = snakemake.params.get("pattern", SAUTE_PAT)
|
|
83
|
+
|
|
84
|
+
recs = SeqIO.parse(records_path, "fasta")
|
|
85
|
+
new_recs = fix_saute_headers(recs, sample, pattern)
|
|
86
|
+
SeqIO.write(new_recs, out_path, "fasta")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def main():
|
|
90
|
+
if len(sys.argv) != 4:
|
|
91
|
+
print("Usage: python fix_headers.py <saute_asm.fasta> <output.fasta> <sample>")
|
|
92
|
+
sys.exit(1)
|
|
93
|
+
|
|
94
|
+
records_path = Path(sys.argv[1])
|
|
95
|
+
out_path = Path(sys.argv[2])
|
|
96
|
+
sample = sys.argv[3]
|
|
97
|
+
|
|
98
|
+
recs = SeqIO.parse(records_path, "fasta")
|
|
99
|
+
new_recs = fix_saute_headers(recs, sample, SAUTE_PAT)
|
|
100
|
+
SeqIO.write(new_recs, out_path, "fasta")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
if "snakemake" in globals():
|
|
105
|
+
snakemake_call(snakemake)
|
|
106
|
+
else:
|
|
107
|
+
main()
|
|
@@ -0,0 +1,71 @@
|
|
|
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
|
+
"""Simple script to retrieve the paths of an assembly graph and output it as sequences in
|
|
12
|
+
fasta format. The functions are tested to work for standard De Brujn graphs, and assume a
|
|
13
|
+
constant overlap between segments. Heterogeneous overlaps are supported in J-lines.
|
|
14
|
+
Blunted graphs (e.g. variation graphs) should work too, but have not been tested.
|
|
15
|
+
|
|
16
|
+
#Usage example:
|
|
17
|
+
gfa_file = Path("path/to/my_graph.gfa")
|
|
18
|
+
out_fasta = Path("my_path_sequences.fasta")
|
|
19
|
+
paths2fasta(gfa_file, out_fasta)
|
|
20
|
+
|
|
21
|
+
The headers of the sequences in the fasta files correspond to the names in the P lines.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1"
|
|
25
|
+
|
|
26
|
+
# =======================================================================================
|
|
27
|
+
# IMPORTS
|
|
28
|
+
# =======================================================================================
|
|
29
|
+
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
import sys
|
|
32
|
+
|
|
33
|
+
from Bio import SeqIO
|
|
34
|
+
from gfa_graph import Assembly_graph
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# =============================================================================
|
|
38
|
+
# FUNCTIONS
|
|
39
|
+
# =============================================================================
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def paths2fasta(graph_path: Path, output_path: Path) -> None:
|
|
43
|
+
"""Retrieve the paths from the assembly graph and write them to
|
|
44
|
+
the specified output file in fasta format."""
|
|
45
|
+
|
|
46
|
+
graph = Assembly_graph(graph_path)
|
|
47
|
+
recs = (graph.retrieve_path(path) for path in graph.paths.values())
|
|
48
|
+
SeqIO.write(recs, output_path, "fasta")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def snakemake_call(snakemake):
|
|
52
|
+
graph_path = Path(snakemake.input[0])
|
|
53
|
+
output_path = Path(snakemake.output[0])
|
|
54
|
+
paths2fasta(graph_path, output_path)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def main():
|
|
58
|
+
if len(sys.argv) != 3:
|
|
59
|
+
print("Usage: python gfa2fasta.py <graph.gfa> <output.fasta>")
|
|
60
|
+
sys.exit(1)
|
|
61
|
+
|
|
62
|
+
graph_path = Path(sys.argv[1])
|
|
63
|
+
output_path = Path(sys.argv[2])
|
|
64
|
+
paths2fasta(graph_path, output_path)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
if "snakemake" in globals():
|
|
69
|
+
snakemake_call(snakemake)
|
|
70
|
+
else:
|
|
71
|
+
main()
|