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,344 @@
|
|
|
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 dataclasses import dataclass, field, fields
|
|
17
|
+
from io import StringIO
|
|
18
|
+
from typing import Optional, Literal
|
|
19
|
+
|
|
20
|
+
AAs = (
|
|
21
|
+
"A",
|
|
22
|
+
"R",
|
|
23
|
+
"N",
|
|
24
|
+
"D",
|
|
25
|
+
"C",
|
|
26
|
+
"E",
|
|
27
|
+
"Q",
|
|
28
|
+
"G",
|
|
29
|
+
"H",
|
|
30
|
+
"I",
|
|
31
|
+
"L",
|
|
32
|
+
"K",
|
|
33
|
+
"M",
|
|
34
|
+
"F",
|
|
35
|
+
"P",
|
|
36
|
+
"S",
|
|
37
|
+
"T",
|
|
38
|
+
"W",
|
|
39
|
+
"Y",
|
|
40
|
+
"V",
|
|
41
|
+
"X",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Fragment:
|
|
47
|
+
"""
|
|
48
|
+
Data structure for the fragment object produced by the parsing of the miniprot output.
|
|
49
|
+
Each fragment is one exon.
|
|
50
|
+
Attributes
|
|
51
|
+
----------
|
|
52
|
+
-contig_name: the name of the target of miniprot.
|
|
53
|
+
-probe_name: the name of the query of miniprot.
|
|
54
|
+
-target_start: in nucleotide space (start index at 0), start precedes end.
|
|
55
|
+
-target_end: in nucleotide space (start index at 0).
|
|
56
|
+
-query_start: in protein space (start index at 1), start precedes end.
|
|
57
|
+
-query_end: in protein space (start index at 1).
|
|
58
|
+
-score: alignment score.
|
|
59
|
+
-strand of the contig.
|
|
60
|
+
-frame of the contig.
|
|
61
|
+
-identity: aa identity from miniprot.
|
|
62
|
+
Post Init
|
|
63
|
+
-correspondence: dictionary with keys as position on the query probe protein and values
|
|
64
|
+
nucleotide positions on the contig. Difference in value between two consecutive keys should be at least 3.
|
|
65
|
+
The index starts index at 0.
|
|
66
|
+
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
contig_name: str
|
|
70
|
+
probe_name: str
|
|
71
|
+
target_start: int
|
|
72
|
+
target_end: int
|
|
73
|
+
query_start: int
|
|
74
|
+
query_end: int # in protein space
|
|
75
|
+
score: int
|
|
76
|
+
strand: Literal[-1, 1]
|
|
77
|
+
frame: Literal[0, 1, 2]
|
|
78
|
+
identity: float
|
|
79
|
+
correspondence: dict[int, int] = field(default_factory=dict, init=False)
|
|
80
|
+
|
|
81
|
+
def get_correspondence(self) -> dict[int, int]:
|
|
82
|
+
"""
|
|
83
|
+
:return:
|
|
84
|
+
"""
|
|
85
|
+
return self.correspondence
|
|
86
|
+
|
|
87
|
+
def get_contig_name(self) -> str:
|
|
88
|
+
return self.contig_name
|
|
89
|
+
|
|
90
|
+
def get_strand(self) -> Literal[-1, 1]:
|
|
91
|
+
return self.strand
|
|
92
|
+
|
|
93
|
+
def __repr__(self):
|
|
94
|
+
try:
|
|
95
|
+
description = (
|
|
96
|
+
f"Fragment({self.contig_name}, {self.probe_name}, {self.target_start=}"
|
|
97
|
+
)
|
|
98
|
+
f" {self.target_end=}, {self.query_start=}, {self.query_end=},"
|
|
99
|
+
f" {self.score=}, {self.strand=}, {self.frame=}, {self.identity=},"
|
|
100
|
+
f" [{list(self.correspondence.items())[0]}-{list(self.correspondence.items())[-1]}]"
|
|
101
|
+
return description
|
|
102
|
+
except IndexError:
|
|
103
|
+
return (
|
|
104
|
+
f"Fragment({self.contig_name}, {self.probe_name}, {self.target_start=}"
|
|
105
|
+
f" {self.target_end=}, {self.query_start=}, {self.query_end=},"
|
|
106
|
+
f" {self.score=}, {self.strand=}, {self.frame=}, {self.identity=},"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Cds:
|
|
112
|
+
"""
|
|
113
|
+
Data structure in charge of the parsing of the miniprot output.
|
|
114
|
+
Attributes
|
|
115
|
+
----------
|
|
116
|
+
-miniprot_output: lines of the miniprot output.
|
|
117
|
+
Post Init
|
|
118
|
+
-data: intermediate object that holds the output of the parsing.
|
|
119
|
+
-fragments: list of Fragment objects. In theory miniprot should produce a single Fragment object.
|
|
120
|
+
-scaffold_start: index of the start of the scaffold sequence (nucleotide space), start precedes end.
|
|
121
|
+
-scaffold_end: index of the end of the scaffold sequence (nucleotide space).
|
|
122
|
+
-probe_start: index of the start of the query (protein space), start precedes end.
|
|
123
|
+
-probe_end: index of the end of the query (protein space).
|
|
124
|
+
-target_nucleotides: sequence of the matching target (i.e. contig) in nucleotides.
|
|
125
|
+
-target_AAs: sequence of the matching target (i.e. contig) in AAs.
|
|
126
|
+
-query_AAs: sequence of the matching query (i.e. probe) in AAs.
|
|
127
|
+
-global_identity: aa identity from miniprot over all exons (fragments).
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
miniprot_output: StringIO = field(repr=False)
|
|
131
|
+
data: dict[str, list] = field(default_factory=dict, init=False, repr=False)
|
|
132
|
+
fragments: list[Fragment] = field(default_factory=list, init=False, repr=False)
|
|
133
|
+
scaffold_start: int = field(init=False)
|
|
134
|
+
scaffold_end: int = field(init=False)
|
|
135
|
+
probe_start: int = field(init=False)
|
|
136
|
+
probe_end: int = field(init=False)
|
|
137
|
+
target_nucleotides: str = field(
|
|
138
|
+
init=False, repr=False
|
|
139
|
+
) # target sequence in nucleotides
|
|
140
|
+
target_AAs: str = field(init=False, repr=False) # target sequence in aa
|
|
141
|
+
query_AAs: str = field(init=False, repr=False) # query sequence in aa
|
|
142
|
+
global_identity: float = field(init=False)
|
|
143
|
+
|
|
144
|
+
def __repr__(self):
|
|
145
|
+
if self.fragments:
|
|
146
|
+
return (
|
|
147
|
+
f"Cds({self.scaffold_start=},{self.scaffold_end=},{self.probe_start=},{self.probe_end=},{self.global_identity=},"
|
|
148
|
+
f"strand={self.fragments[0].get_strand()}, contig={self.fragments[0].get_contig_name()}, global_score={self.get_global_score()})"
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
return "Cds()"
|
|
152
|
+
|
|
153
|
+
def __post_init__(self):
|
|
154
|
+
self._parse_gff()
|
|
155
|
+
# If the data is not empty
|
|
156
|
+
if list(self.data.keys()):
|
|
157
|
+
self._find_correspondences()
|
|
158
|
+
# Ensure that all variables have been set
|
|
159
|
+
for elmt in fields(self):
|
|
160
|
+
if elmt.name not in vars(self):
|
|
161
|
+
raise AttributeError(f"Field {elmt.name} has no attribute")
|
|
162
|
+
assert (
|
|
163
|
+
len(self.target_nucleotides)
|
|
164
|
+
== len(self.target_AAs)
|
|
165
|
+
== len(self.query_AAs)
|
|
166
|
+
), f"length of target_nucleotides ({self.target_nucleotides}), target_AAs ({self.target_AAs}) and query_AAs ({(self.query_AAs)}) do not match"
|
|
167
|
+
|
|
168
|
+
def has_empty_cds(self) -> bool:
|
|
169
|
+
"""
|
|
170
|
+
True if there is no match with a probe
|
|
171
|
+
:return:
|
|
172
|
+
"""
|
|
173
|
+
return not bool(self.fragments)
|
|
174
|
+
|
|
175
|
+
def _parse_gff(self):
|
|
176
|
+
for line in self.miniprot_output:
|
|
177
|
+
if (
|
|
178
|
+
line.startswith("##gff")
|
|
179
|
+
or line.startswith("##PAF")
|
|
180
|
+
or line.startswith("##AAS")
|
|
181
|
+
):
|
|
182
|
+
continue
|
|
183
|
+
# target (scaffold) nucleotides
|
|
184
|
+
if line.startswith("##ATN"):
|
|
185
|
+
self.target_nucleotides = line.removeprefix("##ATN\t").replace("\n", "")
|
|
186
|
+
continue
|
|
187
|
+
# target (scaffold) amino acids
|
|
188
|
+
if line.startswith("##ATA"):
|
|
189
|
+
self.target_AAs = line.removeprefix("##ATA\t").replace("\n", "")
|
|
190
|
+
continue
|
|
191
|
+
# query (probe) amino acids
|
|
192
|
+
if line.startswith("##AQA"):
|
|
193
|
+
self.query_AAs = line.removeprefix("##AQA\t").replace("\n", "")
|
|
194
|
+
continue
|
|
195
|
+
# scaffold & CDS lines
|
|
196
|
+
record = line.strip().split("\t")
|
|
197
|
+
sequence_name = record[0]
|
|
198
|
+
source = record[1]
|
|
199
|
+
feature = record[2]
|
|
200
|
+
start = int(record[3])
|
|
201
|
+
end = int(record[4])
|
|
202
|
+
if record[5] != ".":
|
|
203
|
+
score = record[5]
|
|
204
|
+
else:
|
|
205
|
+
score = None
|
|
206
|
+
if record[6] == "+":
|
|
207
|
+
strand = 1
|
|
208
|
+
else:
|
|
209
|
+
strand = -1
|
|
210
|
+
if record[7] != ".":
|
|
211
|
+
frame = record[7]
|
|
212
|
+
else:
|
|
213
|
+
frame = None
|
|
214
|
+
attributes = record[8].split(";")
|
|
215
|
+
attributes = {
|
|
216
|
+
x.split("=")[0]: x.split("=")[1] for x in attributes if "=" in x
|
|
217
|
+
}
|
|
218
|
+
if sequence_name not in self.data:
|
|
219
|
+
self.data[sequence_name] = []
|
|
220
|
+
alpha = {
|
|
221
|
+
"source": source,
|
|
222
|
+
"feature": feature,
|
|
223
|
+
"start": int(start),
|
|
224
|
+
"end": int(end),
|
|
225
|
+
"score": int(score),
|
|
226
|
+
"strand": strand,
|
|
227
|
+
"frame": int(frame) if frame is not None else None,
|
|
228
|
+
}
|
|
229
|
+
for k, v in attributes.items():
|
|
230
|
+
alpha[k] = v
|
|
231
|
+
self.data[sequence_name].append(alpha)
|
|
232
|
+
contigs = list(self.data.keys())
|
|
233
|
+
# If the file is empty stop here
|
|
234
|
+
if not contigs:
|
|
235
|
+
return
|
|
236
|
+
# Miniprot should map to a single location
|
|
237
|
+
assert len(contigs) == 1, "more than one contig is present"
|
|
238
|
+
contig = contigs[0]
|
|
239
|
+
for item in self.data[contig]:
|
|
240
|
+
if item.get("Target") is None:
|
|
241
|
+
continue
|
|
242
|
+
target_splt = item["Target"].split() ###error
|
|
243
|
+
probe_name = target_splt[0]
|
|
244
|
+
query_start = int(target_splt[1])
|
|
245
|
+
query_end = int(target_splt[2])
|
|
246
|
+
if item["feature"] == "CDS":
|
|
247
|
+
fragment = Fragment(
|
|
248
|
+
contig,
|
|
249
|
+
probe_name,
|
|
250
|
+
item["start"] - 1,
|
|
251
|
+
item["end"] - 1,
|
|
252
|
+
# query_start,
|
|
253
|
+
query_start,
|
|
254
|
+
# query_end - 1,
|
|
255
|
+
query_end,
|
|
256
|
+
int(item["score"]),
|
|
257
|
+
item["strand"],
|
|
258
|
+
item["frame"],
|
|
259
|
+
float(item["Identity"]),
|
|
260
|
+
)
|
|
261
|
+
self.fragments.append(fragment)
|
|
262
|
+
else:
|
|
263
|
+
self.scaffold_start = item["start"] - 1
|
|
264
|
+
self.scaffold_end = item["end"] - 1
|
|
265
|
+
self.probe_start = int(target_splt[1]) - 1
|
|
266
|
+
self.probe_end = int(target_splt[2]) - 1
|
|
267
|
+
self.global_identity = float(item["Identity"])
|
|
268
|
+
|
|
269
|
+
def _find_correspondences(self):
|
|
270
|
+
frg_idx = 0
|
|
271
|
+
fragment = self.fragments[frg_idx]
|
|
272
|
+
frg_limit = fragment.query_end
|
|
273
|
+
idx = 0
|
|
274
|
+
nuc_idx = self.scaffold_start if fragment.strand == 1 else self.scaffold_end
|
|
275
|
+
query_AA_idx = self.probe_start
|
|
276
|
+
probe_nucl_cor = {}
|
|
277
|
+
while idx < len(self.target_nucleotides) + 1:
|
|
278
|
+
try:
|
|
279
|
+
target_nuc = self.target_nucleotides[idx]
|
|
280
|
+
except:
|
|
281
|
+
fragment.correspondence = probe_nucl_cor
|
|
282
|
+
break
|
|
283
|
+
target_AA = self.target_AAs[idx]
|
|
284
|
+
query_AA = self.query_AAs[idx]
|
|
285
|
+
if query_AA in AAs:
|
|
286
|
+
query_AA_idx += 1
|
|
287
|
+
if target_nuc == "-":
|
|
288
|
+
idx += 1
|
|
289
|
+
continue
|
|
290
|
+
if target_AA in AAs and query_AA in AAs:
|
|
291
|
+
probe_nucl_cor[query_AA_idx] = nuc_idx
|
|
292
|
+
idx += 1
|
|
293
|
+
nuc_idx += 1 * fragment.strand
|
|
294
|
+
if query_AA_idx > frg_limit:
|
|
295
|
+
fragment.correspondence = probe_nucl_cor
|
|
296
|
+
probe_nucl_cor = {}
|
|
297
|
+
frg_idx += 1
|
|
298
|
+
if frg_idx == len(self.fragments):
|
|
299
|
+
break
|
|
300
|
+
fragment = self.fragments[frg_idx]
|
|
301
|
+
frg_limit = fragment.query_end
|
|
302
|
+
|
|
303
|
+
def get_fragments(self) -> Optional[list[Fragment]]:
|
|
304
|
+
if not self.data.keys():
|
|
305
|
+
return None
|
|
306
|
+
return self.fragments
|
|
307
|
+
|
|
308
|
+
def get_global_sim(self):
|
|
309
|
+
return self.global_identity
|
|
310
|
+
|
|
311
|
+
def is_empty(self):
|
|
312
|
+
return not bool(self.data)
|
|
313
|
+
|
|
314
|
+
def get_global_score(self) -> int:
|
|
315
|
+
"""Compute the alignment score as the sum of the fragment scores."""
|
|
316
|
+
return sum([fragment.score for fragment in self.fragments])
|
|
317
|
+
|
|
318
|
+
def get_longest_intron(self):
|
|
319
|
+
"""Retrieve the length of the longest intron"""
|
|
320
|
+
sorted_fragments = sorted(self.fragments, key=lambda x: x.target_start)
|
|
321
|
+
if len(self.fragments) == 0:
|
|
322
|
+
return 0
|
|
323
|
+
maximum = 0
|
|
324
|
+
end = sorted_fragments[0].target_end
|
|
325
|
+
for fragment in sorted_fragments[1:]:
|
|
326
|
+
intron_length = abs(fragment.target_start - end)
|
|
327
|
+
if intron_length > maximum:
|
|
328
|
+
maximum = intron_length
|
|
329
|
+
end=fragment.target_end
|
|
330
|
+
return maximum
|
|
331
|
+
|
|
332
|
+
def debug():
|
|
333
|
+
from pathlib import Path
|
|
334
|
+
from io import StringIO
|
|
335
|
+
miniprot_test = Path('../data/test_data/miniprot/miniprot.paf')
|
|
336
|
+
miniprot_out = list((line for line in open(miniprot_test)))
|
|
337
|
+
print(Cds(miniprot_out).get_longest_intron())
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
if __name__ == "__main__":
|
|
343
|
+
debug()
|
|
344
|
+
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
Utility functions to support graph operations, coloring, extensions, filtering, etc.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# =============================================================================
|
|
18
|
+
# CLASSES
|
|
19
|
+
# =============================================================================
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
from itertools import groupby
|
|
23
|
+
from operator import add, attrgetter, itemgetter
|
|
24
|
+
import re
|
|
25
|
+
from typing import Literal, NamedTuple, TYPE_CHECKING
|
|
26
|
+
from fractions import Fraction
|
|
27
|
+
|
|
28
|
+
from more_itertools import split_when
|
|
29
|
+
import polars as pl
|
|
30
|
+
from intervaltree import IntervalTree, Interval
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from gfa_graph import Assembly_graph
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class OrientedEdge(NamedTuple):
|
|
37
|
+
id: str
|
|
38
|
+
orientation: Literal["+", "-"]
|
|
39
|
+
jump: bool = False
|
|
40
|
+
|
|
41
|
+
def __eq__(self, _other: "OrientedEdge"):
|
|
42
|
+
if not isinstance(_other, OrientedEdge):
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
return self.id == _other.id and self.orientation == _other.orientation
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_seg(cls, seg: str) -> "OrientedEdge":
|
|
49
|
+
if match := re.match(r",|;", seg):
|
|
50
|
+
return cls(seg[1:-1], seg[-1], match[0] == ";")
|
|
51
|
+
else:
|
|
52
|
+
return cls(seg[:-1], seg[-1])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# Maybe move it
|
|
56
|
+
class ColorInfo(NamedTuple):
|
|
57
|
+
probe: str
|
|
58
|
+
tlen: int
|
|
59
|
+
cis: bool
|
|
60
|
+
matches: int
|
|
61
|
+
mismatches: int
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def idt(self) -> Fraction:
|
|
65
|
+
return Fraction(self.matches, (self.matches + self.mismatches))
|
|
66
|
+
|
|
67
|
+
def __add__(self, other: "ColorInfo") -> "ColorInfo":
|
|
68
|
+
if self.probe != other.probe:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
"Cannot merge intervals of different probes: {self} and {other} )"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
matches = self.matches + other.matches
|
|
74
|
+
mismatches = self.mismatches + other.mismatches
|
|
75
|
+
|
|
76
|
+
return ColorInfo(self.probe, self.tlen, self.cis, matches, mismatches)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# =============================================================================
|
|
80
|
+
# FUNCTIONS
|
|
81
|
+
# =============================================================================
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def probe_cov(
|
|
85
|
+
path: list[OrientedEdge],
|
|
86
|
+
graph: "Assembly_graph",
|
|
87
|
+
no_reduce: bool = False,
|
|
88
|
+
) -> float | dict[str, float]:
|
|
89
|
+
"""Given a path and a colored graph, compute the probe coverages the path reaches.
|
|
90
|
+
The result is a dictionary of coverage for each probe touch by the path.
|
|
91
|
+
|
|
92
|
+
The default behaviour is to return the coverage of the probe most covered (max)."""
|
|
93
|
+
|
|
94
|
+
edges = [graph.edge_dict[edge.id] for edge in path]
|
|
95
|
+
probes = {probe for edge in edges for probe in edge.get_colors()}
|
|
96
|
+
|
|
97
|
+
if len(probes) == 0:
|
|
98
|
+
return 0.0
|
|
99
|
+
|
|
100
|
+
probe_covs = {}
|
|
101
|
+
for probe in probes:
|
|
102
|
+
tree = IntervalTree(
|
|
103
|
+
inter for edge in edges for inter in edge.matching_exons[probe]
|
|
104
|
+
)
|
|
105
|
+
if tree.is_empty():
|
|
106
|
+
probe_covs[probe] = 0.0
|
|
107
|
+
else:
|
|
108
|
+
tree.merge_overlaps(data_reducer=add)
|
|
109
|
+
cov_bases = sum(interval.length() for interval in tree)
|
|
110
|
+
tlen = next(iter(tree)).data.tlen
|
|
111
|
+
probe_covs[probe] = cov_bases / tlen
|
|
112
|
+
|
|
113
|
+
if no_reduce:
|
|
114
|
+
return probe_covs
|
|
115
|
+
else:
|
|
116
|
+
return max(probe_covs.values())
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def effective_cov(probe_tree: IntervalTree, colored_intervals: bool = False) -> int:
|
|
120
|
+
"Compute the total number of matches on a probe tree."
|
|
121
|
+
if colored_intervals:
|
|
122
|
+
return round(sum(inter.length() * inter.data.idt for inter in probe_tree))
|
|
123
|
+
else:
|
|
124
|
+
return round(sum(inter.length() * inter.data for inter in probe_tree))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def merge_hits(hits: list[Interval]) -> Interval:
|
|
128
|
+
"Given two mergeable hits, return a single Merged interval."
|
|
129
|
+
return Interval(hits[0].begin, hits[-1].end, hits[0].data)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def not_mergeable(hit1: Interval, hit2: Interval) -> bool:
|
|
133
|
+
"Return whether to hits are compatible for merging (adjacent and same identity)"
|
|
134
|
+
return hit1.distance_to(hit2) != 0 or hit1.data != hit2.data
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def build_probe_trees(
|
|
138
|
+
df: pl.DataFrame, min_idt: float = 0.7
|
|
139
|
+
) -> dict[str, IntervalTree]:
|
|
140
|
+
"""Given a Dataframe of probe hits, for each probe build a probe tree with the
|
|
141
|
+
coverage of all the hits, while keeping only the best hit in each region. Hits
|
|
142
|
+
with similarity below min_idt are ignored."""
|
|
143
|
+
|
|
144
|
+
TREE_COLS = ["theader", "tstart", "tend", "nident", "mismatch"]
|
|
145
|
+
probe_hits = df.sort("theader").select(TREE_COLS)
|
|
146
|
+
|
|
147
|
+
probe_trees = {}
|
|
148
|
+
for probe, phits in groupby(probe_hits.iter_rows(), itemgetter(0)):
|
|
149
|
+
tree = IntervalTree(
|
|
150
|
+
Interval(tstart, tend, idt)
|
|
151
|
+
for _, tstart, tend, n, m in phits
|
|
152
|
+
if (idt := Fraction(n, n + m)) >= min_idt
|
|
153
|
+
)
|
|
154
|
+
tree.split_overlaps()
|
|
155
|
+
|
|
156
|
+
best_hits = [
|
|
157
|
+
max(homologous_hits, key=attrgetter("data"))
|
|
158
|
+
for _, homologous_hits in groupby(sorted(tree), key=attrgetter("begin"))
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
probe_trees[probe] = IntervalTree(
|
|
162
|
+
map(merge_hits, split_when(best_hits, not_mergeable))
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
return probe_trees
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def filt_probe_hits(
|
|
169
|
+
df: pl.DataFrame, probe_trees: dict[str, IntervalTree]
|
|
170
|
+
) -> pl.DataFrame:
|
|
171
|
+
"""Compute the effective coverage (matches) on the probes and pick
|
|
172
|
+
the best probe based on it.
|
|
173
|
+
|
|
174
|
+
Return a filtered dataframe with only the hits of the best probe.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
PROBE_COLS = ["theader", "tprobe", "tlen"]
|
|
178
|
+
|
|
179
|
+
# Compute the "Effective coverage" on the probes
|
|
180
|
+
probes_cov = (
|
|
181
|
+
df.select(PROBE_COLS)
|
|
182
|
+
.unique()
|
|
183
|
+
.with_columns(
|
|
184
|
+
glob_eff_cov=pl.col("theader").map_elements(
|
|
185
|
+
lambda probe: effective_cov(probe_trees[probe]),
|
|
186
|
+
return_dtype=pl.Int64,
|
|
187
|
+
),
|
|
188
|
+
glob_cov=pl.col("theader").map_elements(
|
|
189
|
+
lambda probe: sum(inter.length() for inter in probe_trees[probe]),
|
|
190
|
+
return_dtype=pl.Int64,
|
|
191
|
+
),
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# Pick the best probe version
|
|
196
|
+
best_probe_ver = probes_cov.group_by("tprobe").agg(
|
|
197
|
+
pl.all().sort_by(["tprobe", "glob_eff_cov"], descending=True).first()
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# Keep only the hits of the best probes
|
|
201
|
+
return df.join(best_probe_ver, on=["theader", "tprobe", "tlen"])
|