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.
Files changed (69) hide show
  1. nextpyper/__init__.py +0 -0
  2. nextpyper/__main__.py +429 -0
  3. nextpyper/config/config.yaml +80 -0
  4. nextpyper/config/rich_config.yaml +54 -0
  5. nextpyper/config/system_config.yaml +10 -0
  6. nextpyper/data/blosum62.csv +32 -0
  7. nextpyper/data/cps_seqids.csv +674 -0
  8. nextpyper/data/mock/mock_args.yaml +17 -0
  9. nextpyper/data/mock/probes.fasta +56 -0
  10. nextpyper/data/mock/reads/sample1_R1.fastq +20 -0
  11. nextpyper/data/mock/reads/sample1_R2.fastq +20 -0
  12. nextpyper/data/mock/reads/sample2_R1.fastq +20 -0
  13. nextpyper/data/mock/reads/sample2_R2.fastq +20 -0
  14. nextpyper/data/mock/reads/sample3_R1.fastq +20 -0
  15. nextpyper/data/mock/reads/sample3_R2.fastq +20 -0
  16. nextpyper/data/mock/sample.tsv +4 -0
  17. nextpyper/nextpyper.CITATION +9 -0
  18. nextpyper/nextpyper.LICENSE +19 -0
  19. nextpyper/nextpyper.VERSION +1 -0
  20. nextpyper/src/divergence_estimation.py +131 -0
  21. nextpyper/src/diversity.py +93 -0
  22. nextpyper/src/exon_discovery.py +294 -0
  23. nextpyper/src/exon_intron.py +197 -0
  24. nextpyper/src/fix_headers.py +107 -0
  25. nextpyper/src/gfa2fasta.py +71 -0
  26. nextpyper/src/gfa_graph.py +1245 -0
  27. nextpyper/src/gff_parser.py +344 -0
  28. nextpyper/src/graph_utils.py +201 -0
  29. nextpyper/src/homolog_filtering.py +411 -0
  30. nextpyper/src/miniprot.py +1008 -0
  31. nextpyper/src/multi_seq_probes.py +292 -0
  32. nextpyper/src/run_orfipy.py +493 -0
  33. nextpyper/src/sample_table.py +63 -0
  34. nextpyper/src/seeds_collection.py +387 -0
  35. nextpyper/src/summarize_results.py +507 -0
  36. nextpyper/src/union_find.py +65 -0
  37. nextpyper/src/var_asm_parser.py +229 -0
  38. nextpyper/test/.gitkeep +0 -0
  39. nextpyper/workflow/Snakefile +62 -0
  40. nextpyper/workflow/envs/alignment.yaml +7 -0
  41. nextpyper/workflow/envs/assembly.yaml +8 -0
  42. nextpyper/workflow/envs/clustering.yaml +9 -0
  43. nextpyper/workflow/envs/matching.yaml +8 -0
  44. nextpyper/workflow/envs/preprocessing.yaml +11 -0
  45. nextpyper/workflow/envs/saute.yaml +7 -0
  46. nextpyper/workflow/envs/translating.yaml +8 -0
  47. nextpyper/workflow/rules/0_preprocessing/0.1_reads.smk +90 -0
  48. nextpyper/workflow/rules/0_preprocessing/0.2_probes.smk +16 -0
  49. nextpyper/workflow/rules/1_seeds_assembly/1.1_assembly_spades.smk +48 -0
  50. nextpyper/workflow/rules/1_seeds_assembly/1.2_seeds_extension.smk +90 -0
  51. nextpyper/workflow/rules/1_seeds_assembly/1.3_seeds_filtering.smk +64 -0
  52. nextpyper/workflow/rules/1_seeds_assembly/1.4_seeds_clustering.smk +73 -0
  53. nextpyper/workflow/rules/2_homologs_assembly/2.1_saute_assembly.smk +228 -0
  54. nextpyper/workflow/rules/3_homolog_prospection/3.1_allele_collapsing.smk +23 -0
  55. nextpyper/workflow/rules/3_homolog_prospection/3.2_homologs_filtering.smk +76 -0
  56. nextpyper/workflow/rules/3_homolog_prospection/3.3_region_separation.smk +189 -0
  57. nextpyper/workflow/rules/common.smk +160 -0
  58. nextpyper/workflow/schemas/probes.yaml +12 -0
  59. nextpyper/workflow/schemas/sample_table.yaml +29 -0
  60. nextpyper/workflow/scripts/bench_busco.py +572 -0
  61. nextpyper/workflow/scripts/categories_bench.sh +92 -0
  62. nextpyper/workflow/scripts/end_recs_parser.py +146 -0
  63. nextpyper/workflow/scripts/tribble_stats.py +131 -0
  64. nextpyper-0.1.0.dist-info/METADATA +231 -0
  65. nextpyper-0.1.0.dist-info/RECORD +69 -0
  66. nextpyper-0.1.0.dist-info/WHEEL +5 -0
  67. nextpyper-0.1.0.dist-info/entry_points.txt +3 -0
  68. nextpyper-0.1.0.dist-info/licenses/nextpyper/nextpyper.LICENSE +19 -0
  69. nextpyper-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1245 @@
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
+ Functions and classes for parsing the gfa assembly graph and retrieve path sequence.
12
+ """
13
+
14
+ __version__ = "0.1"
15
+
16
+
17
+ # =======================================================================================
18
+ # IMPORTS
19
+ # =======================================================================================
20
+ from collections import Counter, defaultdict
21
+ from fractions import Fraction
22
+ from operator import attrgetter, itemgetter, add
23
+ from dataclasses import dataclass, field
24
+ from itertools import chain, count, repeat, groupby
25
+ from pathlib import Path
26
+ from typing import Callable, Iterator, Self, Literal, Optional, NamedTuple
27
+ from functools import partial
28
+ import re
29
+ import sys
30
+
31
+ from Bio.Seq import Seq
32
+ from Bio.SeqRecord import SeqRecord
33
+ from Bio import SeqIO
34
+ from Bio.Align import PairwiseAligner
35
+ import polars as pl
36
+ from intervaltree import IntervalTree, Interval
37
+ from more_itertools import split_at, transpose
38
+
39
+ from graph_utils import (
40
+ OrientedEdge,
41
+ ColorInfo,
42
+ filt_probe_hits,
43
+ probe_cov,
44
+ effective_cov,
45
+ build_probe_trees,
46
+ )
47
+
48
+ # from graph_alns_parser import Read
49
+ from union_find import UnionFind
50
+ from diversity import select_k_paths
51
+
52
+ # =============================================================================
53
+ # CONSTANTS
54
+ # =============================================================================
55
+
56
+ NODE_ID_PAT = r"^NODE_(\d+)_"
57
+ PROBE_PAT = r"-(.*?)_EDGE"
58
+ LOG_COLS = ["orig_name", "ext_name", "comp_id", "probe", "orig_path", "ext_path"]
59
+ DMND_COLS = [
60
+ "query",
61
+ "evalue",
62
+ "qstart",
63
+ "qend",
64
+ "qlen",
65
+ "tstart",
66
+ "tend",
67
+ "tlen",
68
+ "theader",
69
+ "gapopen",
70
+ "nident",
71
+ "mismatch",
72
+ ]
73
+
74
+ # =============================================================================
75
+ # CLASSES
76
+ # =============================================================================
77
+ LinkSupport = dict[tuple[str], int]
78
+
79
+
80
+ @dataclass(slots=True)
81
+ class Path_on_graph:
82
+ """
83
+ Sequence of OrientedEdges that compose a scaffold
84
+ Attributes
85
+ ----------
86
+ -name: scaffold's name.
87
+ -edge:
88
+ -start: possible start on the first OrientedEdge.
89
+ -end: possible end on the last OrientedEdge.
90
+ -length: length of the scaffold in nucleotides. To be implemented.
91
+ """
92
+
93
+ name: str
94
+ edges: list[OrientedEdge]
95
+ start: Optional[int] = field(default=0)
96
+ end: Optional[int] = field(default=None)
97
+ length: Optional[int] = field(default=None)
98
+
99
+ def get_parameters(self):
100
+ return self.name, self.edges, self.start, self.end, self.length
101
+
102
+
103
+ class ExtLimits(NamedTuple):
104
+ """Parameters to control the maximum extension of a path during
105
+ graph exploration. The length limit is calculated by scaling the
106
+ probe length by scaling. The resulting number is constrained to
107
+ the range defined by [floor, ceiling].
108
+ """
109
+
110
+ floor: int
111
+ ceiling: int
112
+ scaling: float
113
+
114
+
115
+ @dataclass
116
+ class Edge:
117
+ """
118
+ Encodes the edge of the graph, i.e. the 'S' line in a gfa file.
119
+ Keeps information about matching elements, that is sequences from SPAligner or hmm profile from PathRacer.
120
+ Attributes
121
+ ----------
122
+ -id: edge number.
123
+ -raw_seq: nucleotide sequence including k-mer overlap.
124
+ -coverage: k-mer coverage.
125
+ -kc: kmer count.
126
+
127
+ Post init
128
+ ----------
129
+ -seq: 'raw_seq' converted to Bio.Seq.Seq object.
130
+ -matching_exons: dictionary of matches (hmm or sequences, needs to be worked out).
131
+ """
132
+
133
+ id: str
134
+ raw_seq: str = field(repr=False)
135
+ coverage: float
136
+ kc: float = field(default=None)
137
+ seq: Seq = field(init=False)
138
+ matching_exons: dict[str, int] = field(
139
+ init=False, default_factory=lambda: defaultdict(list)
140
+ ) # name (key), interval (value) and extra info of the matching probe
141
+
142
+ def __post_init__(self):
143
+ self.seq = Seq(self.raw_seq)
144
+
145
+ def __len__(self) -> int:
146
+ return len(self.seq)
147
+
148
+ def has_match(self) -> bool:
149
+ return self.matching_exons and any(self.matching_exons.values())
150
+
151
+ def get_colors(self) -> list[str]:
152
+ return (
153
+ [probe for probe, inter in self.matching_exons.items() if inter]
154
+ if self.has_match()
155
+ else list()
156
+ )
157
+
158
+ def get_seq(self) -> Seq:
159
+ return self.seq
160
+
161
+ def get_length(self) -> int:
162
+ return len(self.seq)
163
+
164
+ def retrieve_seq(self, start: int, end: int, orientation: Literal["+", "-"]) -> Seq:
165
+ tmp_seq = self.seq[start:end]
166
+ if orientation == "+":
167
+ return tmp_seq
168
+ return tmp_seq.reverse_complement()
169
+
170
+
171
+ @dataclass
172
+ class Assembly_graph:
173
+ """
174
+ Encodes the gfa assembly graph. Provides methods for graph traversal and sequence retrieval.
175
+ Attributes
176
+ ----------
177
+ -gfa_filename: complete path to gfa assembly file.
178
+ Post init
179
+ -K: k-mer used during SPAdes assembly (edge overlap value).
180
+ -edge_dict: edge number mapping to their respective Edge objects. Used for sequence retrieval.
181
+ -graph: encoding of the graph structure, with an edge mapping.
182
+ Each node represented symmetrically as (1,+)->[(2,+),(3,+)] and (2,-)->[(1,-)].
183
+ -linked_edges: information about non-adjacent edges, that are connected through mate-reads.
184
+ ----------
185
+ """
186
+
187
+ gfa_filename: str = field(repr=False)
188
+ K: int = field(init=False)
189
+ edge_dict: dict[str, Edge] = field(default_factory=dict, init=False, repr=False)
190
+ graph: dict[OrientedEdge, list[OrientedEdge]] = field(
191
+ default_factory=lambda: defaultdict(list), init=False, repr=False
192
+ )
193
+ linked_edges: LinkSupport = field(
194
+ default_factory=lambda: defaultdict(int), init=False, repr=False
195
+ )
196
+ paths: dict[str, Path_on_graph] = field(
197
+ default_factory=dict, init=False, repr=False
198
+ )
199
+ components: list[set[str]] = field(default_factory=list, init=False, repr=False)
200
+ rev = {"+": "-", "-": "+"}
201
+
202
+ def __repr__(self):
203
+ return f"Assembly_graph(K={self.K}, components={len(self.components)}, paths={len(self.paths)}, edges={len(self.edge_dict)}, colored={self.is_colored()})"
204
+
205
+ def __post_init__(self):
206
+ self._parse_graph()
207
+
208
+ def _parse_graph(self) -> Self:
209
+ graph_path = Path(self.gfa_filename)
210
+ assert graph_path.exists(), f"Graph file {self.gfa_filename} not found"
211
+ with open(self.gfa_filename, "r") as file, UnionFind() as UV:
212
+ seg_pat = re.compile(r"[,|;]?\d+[+-]")
213
+ for line in file:
214
+ match line[0]:
215
+ case "H":
216
+ pass
217
+ case "S":
218
+ node_id, seq, _dp, _kc = line.strip().split("\t")[1:]
219
+ dp = float(_dp.removeprefix("DP:f:"))
220
+ kc = int(_kc.removeprefix("KC:i:"))
221
+
222
+ if not hasattr(self, "K"):
223
+ self.K = round(len(seq) - kc / dp)
224
+
225
+ coverage = kc / (len(seq) - self.K)
226
+ self.edge_dict[node_id] = Edge(node_id, seq, coverage, kc=kc)
227
+ case "L":
228
+ _, node_id1, pos1, node_id2, pos2, _match = line.strip().split(
229
+ "\t"
230
+ )
231
+ self.graph[OrientedEdge(node_id1, pos1)].append(
232
+ OrientedEdge(node_id2, pos2)
233
+ )
234
+ self.graph[OrientedEdge(node_id2, self.rev[pos2])].append(
235
+ OrientedEdge(node_id1, self.rev[pos1])
236
+ )
237
+ UV.union((node_id1, node_id2))
238
+ case "J":
239
+ _, node_id1, pos1, node_id2, pos2, _dist, *_tags = (
240
+ line.strip().split("\t")
241
+ )
242
+ self.graph[OrientedEdge(node_id1, pos1)].append(
243
+ OrientedEdge(node_id2, pos2, True)
244
+ )
245
+ self.graph[OrientedEdge(node_id2, self.rev[pos2])].append(
246
+ OrientedEdge(node_id1, self.rev[pos1], True)
247
+ )
248
+
249
+ ## Add to the Jump Links (J-Lines) the connections from L-Lines to prevent graph disconnection
250
+ self.graph[OrientedEdge(node_id2, pos2, True)].extend(
251
+ self.graph[OrientedEdge(node_id2, pos2)]
252
+ )
253
+ self.graph[OrientedEdge(node_id1, self.rev[pos1], True)].extend(
254
+ self.graph[OrientedEdge(node_id1, self.rev[pos1])]
255
+ )
256
+ UV.union((node_id1, node_id2))
257
+
258
+ case "P":
259
+ _, name, path, _, *tags = line.split()
260
+ edges = [
261
+ OrientedEdge.from_seg(seg) for seg in seg_pat.findall(path)
262
+ ]
263
+ self.paths[name] = Path_on_graph(name, edges)
264
+ case _:
265
+ raise NotImplementedError(
266
+ f"ERROR: found line of type {line[0]}"
267
+ )
268
+ # For ends here:
269
+ components = UV.get_components()
270
+ comp_list = list(map(list, UV.get_components()))
271
+ single_edges = set(self.edge_dict).difference(set(chain(*comp_list)))
272
+ components.extend([{edge} for edge in single_edges])
273
+ self.components = dict(enumerate(components, 1))
274
+
275
+ return self
276
+
277
+ # def link_edges(self, reads: list["Read"]) -> Self:
278
+ # """Given a list of paired reads, compute the link support that those pairs
279
+ # exhibit. Each pair that connects a composition of edges is added as a
280
+ # supported link, increasing its count in the dictionary. Compositions of
281
+ # a single edge are not taken into account.
282
+ # """
283
+
284
+ # get_edges = lambda frags: (frag.edge.id for frag in frags)
285
+
286
+ # for read in reads:
287
+ # edges = get_edges(read.fragments + read.mate.fragments)
288
+ # if len(unique_edges := set(edges)) > 1:
289
+ # self.linked_edges[tuple(sorted(unique_edges))] += 1
290
+
291
+ # return self
292
+
293
+ def path_support(self, path: Path_on_graph) -> LinkSupport:
294
+ "Return the links support that are congruent with the given path."
295
+
296
+ if not self.linked_edges:
297
+ raise ValueError("No link information in the graph to evaluate path.")
298
+
299
+ path_edges = {edge.id for edge in path.edges}
300
+ return {
301
+ link: support
302
+ for link, support in self.linked_edges.items()
303
+ if path_edges.issuperset(set(link))
304
+ }
305
+
306
+ @staticmethod
307
+ def _ovlp_extension(
308
+ seq1: Seq, seq2: Seq, gap: int = 10, size_only: bool = False
309
+ ) -> Seq | int:
310
+ """Use pairwise alignment to detect if seq1 and seq2 overlap. If they do
311
+ Use the alignment coordinates to merge them. Otherwise, scaffold them
312
+ with a gap of the given size.
313
+
314
+ If size_only is True, instead of scaffolding the given sequences, return
315
+ the size of the overlap or the size of the gap they produce."""
316
+
317
+ aligner = PairwiseAligner(scoring="megablast", mode="local")
318
+ alns = aligner.align(seq1, seq2)
319
+
320
+ # Proceed as no overlap between the sequences. Add a gap of 10 N
321
+ if alns.score < 30:
322
+ return -1 * gap if size_only else seq1 + Seq("N" * gap) + seq2
323
+
324
+ # Overlap detected. Use alignment coordinates to merge the sequences
325
+ else:
326
+ coords = alns[0].coordinates
327
+ if size_only:
328
+ return coords[0, -1] - coords[0, 0]
329
+ else:
330
+ end1, start2 = coords[:, -1]
331
+ return seq1[:end1] + seq2[start2:]
332
+
333
+ def _retrieve_path(
334
+ self,
335
+ path: list[OrientedEdge],
336
+ start: int = 0,
337
+ end: int = -1,
338
+ extension: str = "",
339
+ first_edge: bool = True,
340
+ ) -> Seq:
341
+ """
342
+
343
+ :param path:
344
+ :param start:
345
+ :param end:
346
+ :param extension:
347
+ :param first_edge:
348
+ :return:
349
+ """
350
+ id = path[0].id
351
+ orientation = path[0].orientation
352
+ jump = path[0].jump
353
+
354
+ if len(path) == 1:
355
+ if (edge := self.edge_dict[id]) is not None:
356
+ if first_edge:
357
+ extension += edge.retrieve_seq(start, end, orientation)
358
+ elif jump:
359
+ newseq = edge.retrieve_seq(0, end, orientation)
360
+ extension = self._ovlp_extension(extension, newseq)
361
+ else:
362
+ extension += edge.retrieve_seq(0, end, orientation)[self.K :]
363
+ return extension
364
+ else:
365
+ sys.exit(f"failed to find edge in graph {path}")
366
+
367
+ else:
368
+ if (edge := self.edge_dict[id]) is not None:
369
+ if first_edge:
370
+ extension += edge.retrieve_seq(start, None, orientation)
371
+ elif jump:
372
+ newseq = edge.retrieve_seq(0, None, orientation)
373
+ extension = self._ovlp_extension(extension, newseq)
374
+ else:
375
+ extension += edge.retrieve_seq(0, None, orientation)[self.K :]
376
+ return self._retrieve_path(path[1:], start, end, extension, False)
377
+ else:
378
+ sys.exit(f"failed to find edge in graph {path}")
379
+
380
+ def retrieve_path(self, path: Path_on_graph) -> SeqRecord:
381
+ """
382
+ Retrieve the sequence corresponding to a graph transversal.
383
+ :param name: Name of the sequence, should correspond to the name of the consensus sequence or hmm profile.
384
+ :param path: Path_on_graph object
385
+ :return:
386
+ """
387
+ return SeqRecord(
388
+ seq=self._retrieve_path(*path.get_parameters()[1:4]),
389
+ id=path.name,
390
+ description="",
391
+ name="",
392
+ )
393
+
394
+ def _get_path_intervals(self, path: str) -> list[Interval]:
395
+ """Given a path name, return a list of intervals specifying which edge that part of the
396
+ sequence comes from."""
397
+
398
+ def _get_ovlp_size(
399
+ edge1: OrientedEdge, edge2: OrientedEdge, gap: int = 10
400
+ ) -> int:
401
+ """Determine the size of the overlp between the given edges.
402
+ If not overlap is found, return the gap size"""
403
+
404
+ seq1 = self.edge_dict[edge1.id].seq
405
+ seq2 = self.edge_dict[edge2.id].seq
406
+ return self._ovlp_extension(seq1, seq2, gap, size_only=True)
407
+
408
+ edges: list[OrientedEdge] = self.paths[path].edges
409
+ edge, *edges = edges
410
+ length = len(self.edge_dict[edge.id])
411
+ start, end = 0, length
412
+ intervals = [Interval(start, end, edge.id)]
413
+
414
+ while edges:
415
+ ovlp = _get_ovlp_size(edge, edges[0]) if edges[0].jump else self.K
416
+ edge, *edges = edges
417
+ start += length - ovlp
418
+ length = len(self.edge_dict[edge.id])
419
+ end += length - ovlp
420
+ intervals.append(Interval(start, end, edge.id))
421
+
422
+ return intervals
423
+
424
+ def color_edges(self, hits: pl.DataFrame, min_idt: float = 0.7) -> Self:
425
+ """Use a table of probe hits to color the edges of the graph, populating the attribute
426
+ 'matching exons' of each edge with the interval they match of the best probe of
427
+ the graph's component they belong.
428
+
429
+ If the identity of a hit is below min_idt, the hit is skipped and the htting edges
430
+ are not colored.
431
+ """
432
+
433
+ KEEP_COLS = (
434
+ "query",
435
+ "theader",
436
+ "cis",
437
+ "tlen",
438
+ "qstart",
439
+ "qend",
440
+ "tstart",
441
+ "tend",
442
+ "nident",
443
+ "mismatch",
444
+ )
445
+
446
+ # ToDo: Should we also degroup this and keep only smaller more granular
447
+ # hits? How would that afect the coloring? Compare results
448
+ df = hits.group_by(["query", "theader", "cis"]).agg(
449
+ pl.sum("nident"),
450
+ pl.sum("mismatch"),
451
+ pl.sum("gapopen"),
452
+ pl.first("tlen"),
453
+ pl.first("comp_id"),
454
+ pl.first("tprobe"),
455
+ pl.col("qstart"),
456
+ pl.col("qend"),
457
+ pl.col("tstart"),
458
+ pl.col("tend"),
459
+ )
460
+
461
+ for (
462
+ path,
463
+ probe,
464
+ direc,
465
+ tlen,
466
+ qstarts,
467
+ qends,
468
+ tstarts,
469
+ tends,
470
+ matches,
471
+ mismatches,
472
+ ) in df[KEEP_COLS].iter_rows():
473
+ # Skip hits that have a low identity
474
+ colorinfo = ColorInfo(probe, tlen, direc, matches, mismatches)
475
+ if colorinfo.idt < min_idt:
476
+ continue
477
+
478
+ # If the hits are not in the same strand, swap starts and ends accordingly
479
+ if not direc:
480
+ qstarts, qends = qends, qstarts
481
+
482
+ path_intervals = self._get_path_intervals(path)
483
+ qinter = sorted(map(Interval, qstarts, qends))
484
+ mod_tstarts = (tstart - 1 for tstart in tstarts)
485
+ tinter = sorted(map(Interval, mod_tstarts, tends, repeat(colorinfo)))
486
+
487
+ for qint, tint in zip(qinter, tinter):
488
+ for pint in path_intervals:
489
+ if qint.overlaps(pint):
490
+ edge_id = pint.data
491
+ self.edge_dict[edge_id].matching_exons[probe].append(tint)
492
+
493
+ # Simplify (merge) overlapping intervals of the same color.
494
+ for edge in self.edge_dict.values():
495
+ if edge.has_match():
496
+ for probe, intervals in edge.matching_exons.items():
497
+ if len(intervals) > 1:
498
+ tree = IntervalTree(intervals)
499
+ tree.merge_overlaps(data_reducer=add, strict=False)
500
+ edge.matching_exons[probe] = sorted(tree)
501
+
502
+ def is_colored(self) -> bool:
503
+ "Return whether the graph is currently colored or not"
504
+
505
+ return any(edge.has_match() for edge in self.edge_dict.values())
506
+
507
+ def remove_colors(self) -> Self:
508
+ "Remove the colors (probe hit information) of all the edges of the graph, making it colorless."
509
+
510
+ for edge in self.edge_dict.values():
511
+ edge.matching_exons.clear()
512
+ return self
513
+
514
+
515
+ @dataclass(slots=True)
516
+ class OptimalExtension:
517
+ """
518
+ Container of partial extensions of paths discovered during graph exploration.
519
+ The container holds the N best extensions where N is the size of the container
520
+ at instantiation. A function key function can be given to control how the "best"
521
+ extensions are determined.
522
+
523
+ extensions: a list containing the paths.
524
+ size: How many extensions to hold.
525
+ key: Function to score the extensions, which should receive a path as only argument.
526
+ """
527
+
528
+ extensions: list[list[OrientedEdge]] = field(default_factory=list)
529
+ size: int = field(default=10)
530
+ key: Optional[Callable[[list[OrientedEdge]], int]] = field(default=None)
531
+
532
+ def __len__(self) -> int:
533
+ return len(self.extensions)
534
+
535
+ def __repr__(self) -> str:
536
+ if self.key is None:
537
+ return f"OptimalExtension(size={self.size}, extensions={self.extensions})"
538
+ else:
539
+ ranks = list(map(self.key, self.extensions))
540
+ return f"OptimalExtension(size={self.size}, ranks={ranks})"
541
+
542
+ def __iter__(self) -> Iterator[list[OrientedEdge]]:
543
+ for path in iter(self.extensions):
544
+ yield path
545
+
546
+ def _purge(self) -> None:
547
+ while len(self) > self.size:
548
+ self.extensions.pop()
549
+
550
+ def __contains__(self, _other: OrientedEdge) -> bool:
551
+ if not isinstance(_other, OrientedEdge):
552
+ return False
553
+
554
+ return any(_other == path for path in self.extensions)
555
+
556
+ def add(self, path: list[OrientedEdge]) -> Self:
557
+ if path in self:
558
+ return Self
559
+ self.extensions.append(path)
560
+ self.extensions.sort(reverse=True, key=self.key)
561
+ self._purge()
562
+ return Self
563
+
564
+ def extend(self, paths: list[list[OrientedEdge]]) -> Self:
565
+ dedup_paths = [path for path in paths if path not in self]
566
+ if len(dedup_paths) == 0:
567
+ return Self
568
+
569
+ self.extensions.extend(paths)
570
+ self.extensions.sort(reverse=True, key=self.key)
571
+ self._purge()
572
+ return Self
573
+
574
+
575
+ # =============================================================================
576
+ # FUNCTIONS
577
+ # =============================================================================
578
+
579
+
580
+ def dfs_track_paths(
581
+ graph: Assembly_graph,
582
+ start: OrientedEdge,
583
+ probe: Optional[str] = None,
584
+ max_len: int = 5000,
585
+ max_extensions: int = 10,
586
+ max_intron_size: Optional[int] = 2000,
587
+ goal: Optional[OrientedEdge] = None,
588
+ key: Optional[Callable[[list[OrientedEdge]], int]] = None,
589
+ ):
590
+ """
591
+ Given a starting node (from a path), compute and return compatible with the given graph.
592
+
593
+ The number of returned extensions is limited to the "best" n, where n is controlled
594
+ by _max_extensions_. The definition of "Best" can be customised by providing any
595
+ scoring function that accepts a path and returns a score. By default, length is
596
+ used (the longest path is the best).
597
+
598
+ Finally, the exploration of the graph is limited to max_len. Extensions longer than
599
+ this value are stopped early.
600
+
601
+ Attributes
602
+ ----------
603
+ -graph: Assembly_graph
604
+ -start: OrientedEdge last edge on scaffold to be extended
605
+ -max_len: in nucleotides
606
+ -max_extensions: max number of paths
607
+ -goal: edge where to stop the DFS path exploration
608
+ -key: function to score the produced paths. The function has
609
+ to receive a single argument which has to be a path: list[OrientedEdge]
610
+ """
611
+
612
+ def get_path_len(path: list[OrientedEdge], graph: Assembly_graph) -> int:
613
+ return sum(len(graph.edge_dict[edge[0]]) for edge in path) - graph.K * (
614
+ len(path) - 1
615
+ )
616
+
617
+ def exons_gap(path: list[OrientedEdge], probe: str, graph: Assembly_graph) -> int:
618
+ "Determine the maximum gap (in nucleotides) between colored edges in a path"
619
+ if len(path) == 1:
620
+ return 0
621
+
622
+ def local_gap(edge: Edge, probe: str) -> int:
623
+ if edge.has_match() and any(edge.matching_exons[probe]):
624
+ return 0
625
+ else:
626
+ return len(edge)
627
+
628
+ gaps = (local_gap(graph.edge_dict[edge.id], probe) for edge in path)
629
+ return max(map(sum, split_at(gaps, lambda gap: gap == 0)))
630
+
631
+ def _trim_path(
632
+ path: list[OrientedEdge], graph: Assembly_graph, probe: str = None
633
+ ) -> list[OrientedEdge]:
634
+ """Given a proposed path extension and a color, trim such extension
635
+ to the last colored Edge."""
636
+
637
+ # If we have no color, we can not trim.
638
+ if probe is None:
639
+ return path
640
+
641
+ # Where is the last time we see a colored Edge?
642
+ last_color_idx = 0
643
+ for idx, edge in enumerate(path):
644
+ if probe in graph.edge_dict[edge.id].get_colors():
645
+ last_color_idx = idx
646
+
647
+ return path[: last_color_idx + 1]
648
+
649
+ def dfs_helper(
650
+ edge: OrientedEdge,
651
+ current_path: list[OrientedEdge],
652
+ extensions: OptimalExtension,
653
+ ):
654
+ """
655
+ Help function to apply the DFS recursion.
656
+
657
+ edge: current edge being evaluated.
658
+ current_path: path (ordered list of edges being explored).
659
+ extensions: container with the best paths.
660
+ """
661
+ current_path.append(edge)
662
+
663
+ # If we reach the goal, add the path
664
+ if goal is not None and edge == goal:
665
+ extensions.add(trim_path(current_path[:]))
666
+ return
667
+
668
+ # Maximum len size check (avoids long recursions)
669
+ if max_len is not None and get_path_len(current_path, graph) > max_len:
670
+ extensions.add(trim_path(current_path[:]))
671
+ return
672
+
673
+ # Colored graph exploration
674
+ if probe:
675
+ # No-mix color policy (abort a path if changing color)
676
+ if (
677
+ edge_colors := set(graph.edge_dict[edge.id].get_colors())
678
+ ) and probe not in edge_colors:
679
+ extensions.add(trim_path(current_path[:-1]))
680
+ return
681
+
682
+ # Gap size is bigger than the limit
683
+ if (
684
+ max_intron_size
685
+ and exons_gap(current_path, probe, graph) > max_intron_size
686
+ ):
687
+ extensions.add(trim_path(current_path[:]))
688
+ return
689
+
690
+ # Reached a dead-end
691
+ if not (neighbors := graph.graph[edge]):
692
+ extensions.add(trim_path(current_path[:]))
693
+ return
694
+
695
+ # Explore neighbors
696
+ for neighbor in neighbors:
697
+ if neighbor.id not in [edge.id for edge in current_path]:
698
+ dfs_helper(neighbor, current_path[:], extensions)
699
+ # Avoid getting stuck in loops and reversing your steps.
700
+ else:
701
+ extensions.add(trim_path(current_path[:]))
702
+ return
703
+
704
+ if key is None:
705
+ key = partial(get_path_len, graph=graph)
706
+
707
+ current_path = []
708
+ extensions = OptimalExtension(size=max_extensions, key=key)
709
+ trim_path = partial(_trim_path, probe=probe, graph=graph)
710
+
711
+ dfs_helper(start, current_path, extensions)
712
+
713
+ return extensions
714
+
715
+
716
+ def extend_path(
717
+ path: Path_on_graph,
718
+ graph: Assembly_graph,
719
+ max_len: int = 5000,
720
+ max_ext: int = 10,
721
+ max_intron_size: int = 2000,
722
+ key: Optional[Callable[[list[OrientedEdge]], int]] = None,
723
+ allow_gray: bool = False,
724
+ probe: str | None = None,
725
+ ) -> list[OrientedEdge]:
726
+ """Given an assembly graph and a path, extend the path following the graph topology
727
+ using a Depth First Search. Up to max_ext extensions of the given path are returned.
728
+
729
+ By default, the extension is guided by the color of the path. If the path is colored by
730
+ more than one probe, the probe with the highest effective coverage (matches) is chosen.
731
+ If the path is gray (colorless) and allow_gray is True, colorless extension follows.
732
+ Otherwise a ValueError is performed.
733
+
734
+ To avoid long recursions, an extension bigger than max_len stops the exploration of that
735
+ extension. Path extensions are limited to max_len.
736
+
737
+ Color guided extension is further limited by max_intron_size, which is the maximum gap
738
+ allowed between colored edges. If an extension would introduce a gap bigger than this
739
+ value, the extension is terminated.
740
+
741
+ Since a path can have multiple possible extensions and these are limited to max_ext,
742
+ The extensions are scored using the key funtion and onyl the best are kept. The key
743
+ function should receive a path and return a score. By the default, the length of the
744
+ path is used (longer paths are better).
745
+
746
+ Return a list with all the extended paths, represented as list of oriented edges.
747
+ """
748
+
749
+ edges = [graph.edge_dict[edge.id] for edge in path.edges]
750
+ probes = {probe for edge in edges for probe in edge.get_colors()}
751
+
752
+ # A probe was provided to use for the exploration
753
+ if probe is not None and probe not in probes:
754
+ raise ValueError(f"path {path.name} is not colored by {probe} but by {probes}.")
755
+
756
+ # Probe was not provided but it is going to be discovered for colored exploration
757
+ elif probe is None:
758
+ match len(probes):
759
+ case 0:
760
+ probe = None
761
+ case 1:
762
+ probe = probes.pop()
763
+ case _:
764
+ probe_idts = {}
765
+ for probe in probes:
766
+ tree = IntervalTree(
767
+ inter for edge in edges for inter in edge.matching_exons[probe]
768
+ )
769
+ probe_idts[probe] = effective_cov(tree, colored_intervals=True)
770
+
771
+ probe = max(probe_idts.items(), key=itemgetter(1))[0]
772
+
773
+ if not allow_gray and probe is None:
774
+ raise ValueError(f"All edges in path {path.name} are colorless. Exiting.")
775
+
776
+ # In case of colored extension, deactivate the max_len filter.
777
+ if probe is not None:
778
+ max_len = None
779
+
780
+ *edges, tail = path.edges
781
+ extensions = dfs_track_paths(
782
+ graph, tail, probe, max_len, max_ext, max_intron_size, key=key
783
+ )
784
+ return [edges + ext for ext in extensions]
785
+
786
+
787
+ def get_seq_atts(path: list[OrientedEdge], graph: Assembly_graph) -> tuple[int, float]:
788
+ """Given a list of OrientedEdges which represent a path, infer the length and coverage of
789
+ the sequence it encodes. Returns a tuple with both values.
790
+ """
791
+
792
+ edges = [graph.edge_dict[edge.id] for edge in path]
793
+ path_length = sum(len(edge) for edge in edges) - (graph.K * (len(path) - 1))
794
+ path_cov = sum(edge.kc for edge in edges) / (path_length - graph.K)
795
+
796
+ return path_length, path_cov
797
+
798
+
799
+ def make_path_name(path: list[OrientedEdge], idx: int, graph: Assembly_graph):
800
+ length, cov = get_seq_atts(path, graph)
801
+ return f"EDGE_{idx}_length_{length}_cov_{cov:.3f}"
802
+
803
+
804
+ def find_best_probe_hits(
805
+ df: pl.DataFrame, min_idt: float = 0.7, div_mod: float = 0.1
806
+ ) -> pl.DataFrame:
807
+ """From a table of probe hits to the paths of a graph, compute which probe hits
808
+ are the best or compatible with the best.
809
+
810
+ To determine the best hits of each probe, the probe hits are stacked in the
811
+ probe coordinates, and overlapping hits are split, defining local subregions.
812
+ The, the best hit (the one with the highest similarity to the probe) is selected
813
+ for each sub region.
814
+
815
+ All probe hits are reevaluated and kept if its identity is higher than the identity
816
+ threshold set by the best hit of the subregion they belong to. The identity threshold
817
+ is a function of the divergence (1 - idt) of the best hit, which makes it more relaxed
818
+ for lower identity values and stricter for higher identities. It is computed as:
819
+
820
+ margin = best_hit_idt * sqrt(divergence) * div_mod
821
+ idt_threshold = best_hit_idt - margin
822
+
823
+ Hits with lower identity than min_idt are always filtered.
824
+
825
+ Return simplified table with only the best (or compatible) hits.
826
+ """
827
+
828
+ def is_main_hit(
829
+ hit: Interval, probe_tree: IntervalTree, div_mod: float = 0.98
830
+ ) -> bool:
831
+ """Given a hit and a probe_tree, determine if the hit identity is within the accepted
832
+ identity threshold of the best homologous hit in the probe_tree.
833
+ """
834
+
835
+ ovlps = probe_tree.overlap(hit.begin, hit.end)
836
+ if len(ovlps) == 0:
837
+ return False
838
+
839
+ homolog_hit = max(ovlps, key=lambda inter: hit.overlap_size(inter))
840
+ idt_threshold = homolog_hit.data * (1 - (1 - homolog_hit.data) ** 2 * div_mod)
841
+
842
+ return hit.data >= idt_threshold
843
+
844
+ # Compute the hits coverage of the probes and which are the best hits in
845
+ # each subregion
846
+ TREE_COLS = ["theader", "tstart", "tend", "nident", "mismatch"]
847
+ probe_hits = df.sort("theader").select(TREE_COLS)
848
+
849
+ probe_trees = build_probe_trees(df, min_idt)
850
+
851
+ # Filter the hits that are not compatible (low-identity) with the best hits on each probe
852
+ mask = [
853
+ (idt := Fraction(n, n + m)) >= min_idt
854
+ and is_main_hit(Interval(start - 1, end, idt), probe_trees[probe], div_mod)
855
+ for probe, start, end, n, m in probe_hits.iter_rows()
856
+ ]
857
+ clean_hits = df.sort(by="theader").filter(mask)
858
+
859
+ # This is a multiprobe set, so pick the best probe version:
860
+ if (clean_hits["theader"] != clean_hits["tprobe"]).any():
861
+ clean_hits = filt_probe_hits(clean_hits, probe_trees)
862
+
863
+ return clean_hits.sort(by="theader")
864
+
865
+
866
+ def compute_dp_stats(graph: Assembly_graph) -> pl.DataFrame:
867
+ """Given a colored graph, compute basic statitistics about the depth distribution
868
+ of on-target and off-target edges on the graph."""
869
+
870
+ covs = [
871
+ (edge.coverage, bool(edge.has_match())) for edge in graph.edge_dict.values()
872
+ ]
873
+
874
+ return (
875
+ pl.DataFrame(covs, {"cov": pl.Float64, "target": pl.Boolean}, orient="row")
876
+ .group_by("target")
877
+ .agg(
878
+ q25=pl.quantile("cov", 0.25),
879
+ q50=pl.median("cov"),
880
+ q75=pl.quantile("cov", 0.75),
881
+ std90=pl.col("cov")
882
+ .filter(
883
+ (pl.col("cov") < pl.quantile("cov", 0.95))
884
+ & (pl.col("cov") > pl.quantile("cov", 0.05))
885
+ )
886
+ .std(),
887
+ )
888
+ )
889
+
890
+
891
+ def colored_paths_extension(
892
+ graph: Assembly_graph,
893
+ hits: pl.DataFrame,
894
+ max_extensions: int = 10,
895
+ max_intron_size: int = 2000,
896
+ extension_len_limits: ExtLimits = ExtLimits(3000, 7000, 3.0),
897
+ ):
898
+ """
899
+ Given a graph colored by probe hits, and a set of best probe hits, proceed to
900
+ extend all the paths that keep at least one probe hit.
901
+
902
+ Extensions are done per probe and component, using probe coverage as key function.
903
+ For each combination, locally generated extensions are filtered first to remove
904
+ duplicates and contained paths. Then, only the best max_extensions are kept,
905
+ which are selected using kmedioids on the jaccard distance of the edges of the paths
906
+ (to select a more diverse set of extensions).
907
+
908
+ Return a dictionary with the names of the original paths as keys and the list of
909
+ possible extensions as values.
910
+ """
911
+
912
+ def _get_max_len(tlen: int, extension_limits: ExtLimits) -> int:
913
+ "Compute the maximum extension length allowed given the extension limits."
914
+ floor_len, ceil_len, plen_scaling = extension_limits
915
+ return min(max(floor_len, tlen * 3 * plen_scaling), ceil_len)
916
+
917
+ def _hash_path(path) -> int:
918
+ return hash(tuple(sorted(edge.id for edge in path)))
919
+
920
+ def is_contained(ext: list[OrientedEdge], ext_sets: tuple[set[str]]) -> bool:
921
+ """Given an extension (path), determine if it is contained within another one,
922
+ by comparing with a collection of sets representing the alternative paths."""
923
+
924
+ qext = set(map(attrgetter("id"), ext))
925
+ return any(qext.issubset(edge_set) for edge_set in ext_sets if qext != edge_set)
926
+
927
+ get_max_len = partial(_get_max_len, extension_limits=extension_len_limits)
928
+ comp_pcov = partial(probe_cov, graph=graph)
929
+ get_path_length = partial(get_seq_atts, graph=graph)
930
+
931
+ # Drop path duplicates (e.g. due to multiple colors) and take the longest tlen for the exploration
932
+ hits_iter = (
933
+ hits.sort(["query", "tlen"], descending=True)
934
+ .group_by("query")
935
+ .agg(
936
+ pl.first("tlen"),
937
+ pl.first("comp_id"),
938
+ pl.first("tprobe"),
939
+ pl.first("theader"),
940
+ )
941
+ .select(["query", "tlen", "comp_id", "tprobe", "theader"])
942
+ .sort(["comp_id", "tprobe", "query"])
943
+ .iter_rows()
944
+ )
945
+
946
+ # path_extensions = {}
947
+ path_extensions = defaultdict(dict)
948
+ for (comp, probe), queries in groupby(hits_iter, key=itemgetter(2, 3)):
949
+ # Compute extensions for all paths
950
+ comp_ext = {}
951
+ for name, tlen, _, _, probe_ver in queries:
952
+ try:
953
+ comp_ext[name] = extend_path(
954
+ graph.paths[name],
955
+ graph,
956
+ key=comp_pcov,
957
+ max_len=get_max_len(tlen),
958
+ max_ext=max_extensions,
959
+ max_intron_size=max_intron_size,
960
+ probe=probe_ver,
961
+ )
962
+ except RecursionError as err:
963
+ err.add_note(
964
+ f"While extending: path={name}, probe={probe_ver} ({tlen=})"
965
+ )
966
+ raise
967
+
968
+ # Remove duplicated paths
969
+ signs = set()
970
+ filt_paths = defaultdict(list)
971
+ for name, paths in comp_ext.items():
972
+ for path in paths:
973
+ if (sign := _hash_path(path)) not in signs:
974
+ signs.add(sign)
975
+ filt_paths[name].append(path)
976
+
977
+ # Some extensions would be contained by others, we need to get rid of those
978
+ ext_sets = tuple(
979
+ set(map(attrgetter("id"), ext))
980
+ for ext in chain.from_iterable(filt_paths.values())
981
+ )
982
+
983
+ filt_comp_ext = defaultdict(list)
984
+ for name, extensions in comp_ext.items():
985
+ for ext in extensions:
986
+ if not is_contained(ext, ext_sets):
987
+ filt_comp_ext[name].append(ext)
988
+
989
+ # Now use Kmedioids to select K extensions
990
+ selected_ext = select_k_paths(
991
+ list(chain.from_iterable(filt_comp_ext.values())),
992
+ max_extensions,
993
+ graph,
994
+ key=lambda path: (comp_pcov(path), get_path_length(path)),
995
+ )
996
+
997
+ # Finally recover the original path names for logging
998
+ final_comp_ext = defaultdict(list)
999
+ path2name = {
1000
+ _hash_path(path): name
1001
+ for name, paths in filt_comp_ext.items()
1002
+ for path in paths
1003
+ }
1004
+ for ext in selected_ext:
1005
+ final_comp_ext[path2name[_hash_path(ext)]].append(ext)
1006
+
1007
+ path_extensions[probe].update(final_comp_ext)
1008
+
1009
+ return path_extensions
1010
+
1011
+
1012
+ def summarize_extensions(
1013
+ ext_dict: dict[str, list[Path_on_graph]],
1014
+ path2comp: dict[str, int],
1015
+ graph: Assembly_graph,
1016
+ ) -> pl.DataFrame:
1017
+ """Summarize the final extended paths into a dataframe for logging.
1018
+ Information includes the original and extended names and paths, the component
1019
+ in the graph and the probe used to do the extension."""
1020
+
1021
+ def log_path(path: Path_on_graph) -> str:
1022
+ return ",".join(edge.id for edge in path.edges)
1023
+
1024
+ def extract_info(path: str, ext: Path_on_graph) -> tuple[str, str, int, str, str]:
1025
+ probe = re.search(PROBE_PAT, ext.name)[1]
1026
+ orig_path = log_path(graph.paths[path])
1027
+ ext_path = log_path(ext)
1028
+ return path, ext.name, path2comp[path], probe, orig_path, ext_path
1029
+
1030
+ log_iter = transpose(
1031
+ extract_info(path, ext) for path, exts in ext_dict.items() for ext in exts
1032
+ )
1033
+ log_df = pl.DataFrame(log_iter, orient="col", schema=LOG_COLS)
1034
+
1035
+ return (
1036
+ log_df.with_columns(
1037
+ id=pl.col("orig_name").str.extract(NODE_ID_PAT).cast(pl.Int64)
1038
+ )
1039
+ .sort("id")
1040
+ .drop("id")
1041
+ .insert_column(3, (pl.col("orig_path") != pl.col("ext_path")).alias("extended"))
1042
+ )
1043
+
1044
+
1045
+ def snakemake_call(snakemake):
1046
+ with open(snakemake.log[0], "w") as outlog:
1047
+ sys.stdout = sys.stderr = outlog
1048
+ sys.setrecursionlimit(5000)
1049
+
1050
+ graph_path = Path(snakemake.input.graph)
1051
+ table_path = Path(snakemake.input.table)
1052
+ out = Path(snakemake.output.ext_seqs)
1053
+ ext_table = Path(snakemake.output.ext_table)
1054
+
1055
+ filter_low_dp_comps = snakemake.params.get("filter_low_dp_comps", True)
1056
+ floor_len = (
1057
+ snakemake.params.floor_len
1058
+ ) # maximum extension of a path in nucleotide
1059
+ ceil_len = (
1060
+ snakemake.params.ceil_len
1061
+ ) # maximum extension of a path in nucleotide
1062
+ plen_scaling = (
1063
+ snakemake.params.plen_scaling
1064
+ ) # float that multiplies the length of the probe for an alternative extension
1065
+ min_idt = snakemake.params.min_idt # For probe hits
1066
+ # The selected extension is the max of these two thresholds.
1067
+ max_intron_size = snakemake.params.max_intron_size
1068
+ pat = snakemake.params.probe_pattern
1069
+
1070
+ extension_limits = ExtLimits(floor_len, ceil_len, plen_scaling)
1071
+ max_extensions = snakemake.params.max_extensions
1072
+
1073
+ # Load the matches
1074
+ df = pl.read_csv(
1075
+ table_path, separator="\t", has_header=False, new_columns=DMND_COLS
1076
+ )
1077
+
1078
+ # Load the graph and a dictionary edge -> components
1079
+ graph = Assembly_graph(graph_path)
1080
+ print(f"Graph at the start: {graph}")
1081
+ comp_ids = {
1082
+ edge: comp_id
1083
+ for comp_id, edges in graph.components.items()
1084
+ for edge in edges
1085
+ }
1086
+
1087
+ # Add component information to the table of matches
1088
+ path2comp = {
1089
+ path: comp_ids[graph.paths[path].edges[0].id]
1090
+ for path in df["query"].unique()
1091
+ }
1092
+
1093
+ pre_comp = df.with_columns(
1094
+ cis=pl.col("qend") > pl.col("qstart"),
1095
+ comp_id=pl.col("query").replace_strict(path2comp),
1096
+ tprobe=pl.col("theader").str.extract(pat),
1097
+ )
1098
+
1099
+ print(
1100
+ f"Initial number of components with hits: {len(pre_comp["comp_id"].unique())}"
1101
+ )
1102
+
1103
+ # Find which probe is best for each component and color the graph
1104
+ final_hits = find_best_probe_hits(pre_comp, min_idt)
1105
+ print(
1106
+ f"Number of components with hits after processing the best hits: {len(final_hits["comp_id"].unique())}"
1107
+ )
1108
+ print("Coloring the graph")
1109
+
1110
+ graph.color_edges(final_hits, min_idt)
1111
+
1112
+ # Activate the component-level low coverage heuristic
1113
+ print(f"Filtering low depth components: {filter_low_dp_comps}")
1114
+ if filter_low_dp_comps:
1115
+
1116
+ # Find a Coverage threshold to filter noisy components.
1117
+ cov_stats = compute_dp_stats(graph)
1118
+ print("On/off target edges stats \n")
1119
+ cov_stats.with_columns(
1120
+ pl.col("target").replace_strict({False: "off", True: "on"})
1121
+ ).write_csv(sys.stdout, separator="\t", float_precision=4)
1122
+
1123
+ # Current heuristic is to choose the max between the q25 on-target and the median off-target
1124
+ on_q25 = cov_stats.filter(pl.col("target"))["q25"][0]
1125
+ off_q50 = cov_stats.filter(~pl.col("target"))["q50"][0]
1126
+ dp_thr = max(on_q25, off_q50)
1127
+ print(f"Depth threshold selected: {dp_thr}")
1128
+
1129
+ # Find and keep the components with enough depth of coverage
1130
+ colored_comps = {
1131
+ comp_ids[edge_id]
1132
+ for edge_id, edge in graph.edge_dict.items()
1133
+ if edge.has_match()
1134
+ }
1135
+ high_dp_colored_comps = {
1136
+ comp
1137
+ for comp in colored_comps
1138
+ if any(
1139
+ graph.edge_dict[edge_id].coverage > dp_thr
1140
+ for edge_id in graph.components[comp]
1141
+ )
1142
+ }
1143
+
1144
+ # Filter the hits from the filtered components and recompute the best hits and coloring
1145
+ dp_filt_hits = pre_comp.filter(
1146
+ pl.col("comp_id").is_in(high_dp_colored_comps)
1147
+ )
1148
+ final_hits = find_best_probe_hits(dp_filt_hits, min_idt)
1149
+
1150
+ print(
1151
+ f"Number of components with hits after depth filtering: {len(final_hits["comp_id"].unique())}"
1152
+ )
1153
+ print("Coloring the graph")
1154
+
1155
+ graph.remove_colors()
1156
+ graph.color_edges(final_hits, min_idt)
1157
+
1158
+ # If there are no connections in the graph, there is nothing to extend.
1159
+ newpaths = defaultdict(list)
1160
+ if not hasattr(graph, "K"):
1161
+ for name, path in graph.paths.items():
1162
+ if not (
1163
+ colors := Counter(
1164
+ probe
1165
+ for edge in path.edges
1166
+ for probe in graph.edge_dict[edge.id].get_colors()
1167
+ )
1168
+ ):
1169
+ continue
1170
+
1171
+ probe = re.search(pat, colors.most_common(1)[0][0])[1]
1172
+ path.name = f'{out.stem}-{probe}_{path.name.replace("NODE", "EDGE")}'
1173
+ newpaths[name].append(path)
1174
+
1175
+ # Explore the colored graph:
1176
+ else:
1177
+ print("Computing path extensions")
1178
+ path_extensions = colored_paths_extension(
1179
+ graph, final_hits, max_extensions, max_intron_size, extension_limits
1180
+ )
1181
+
1182
+ # Make the new paths out of the extensions
1183
+ node_pat = re.compile(NODE_ID_PAT)
1184
+ counter = count(1)
1185
+ for probe, path_ext in path_extensions.items():
1186
+ for path, extensions in sorted(
1187
+ path_ext.items(), key=lambda x: int(node_pat.match(x[0])[1])
1188
+ ):
1189
+ for extension in extensions:
1190
+ name = f"{out.stem}-{probe}_"
1191
+ name += make_path_name(extension, next(counter), graph)
1192
+ newpaths[path].append(Path_on_graph(name, extension))
1193
+
1194
+ print(f"Number of starting paths for extension: {len(newpaths)}")
1195
+ print(
1196
+ f"Number of extensions obtained: {sum(len(exts) for exts in newpaths.values())}"
1197
+ )
1198
+
1199
+ log_df = summarize_extensions(newpaths, path2comp, graph)
1200
+ log_df.write_csv(ext_table, separator="\t")
1201
+
1202
+ # Finally write the new sequences
1203
+ seqs_iter = (
1204
+ graph.retrieve_path(path) for path in chain.from_iterable(newpaths.values())
1205
+ )
1206
+ SeqIO.write(seqs_iter, out, "fasta")
1207
+
1208
+
1209
+ def main():
1210
+ import sys
1211
+
1212
+ if len(sys.argv) != 5:
1213
+ print(
1214
+ "Usage: python gfa_graph.py <graph.gfa> <hits.tsv> <output.fasta> <extensions.log>"
1215
+ )
1216
+ sys.exit(1)
1217
+
1218
+ class Run:
1219
+ def __init__(self, **kwargs):
1220
+ for key, val in kwargs.items():
1221
+ setattr(self, key, val)
1222
+
1223
+ # Mock the snakemake object
1224
+ snakemake = Run(
1225
+ input=Run(graph=sys.argv[1], table=sys.argv[2]),
1226
+ output=Run(ext_seqs=sys.argv[3], ext_table=sys.argv[4]),
1227
+ log=[sys.stdout],
1228
+ params=Run(
1229
+ floor_len=3000,
1230
+ ceil_len=7000,
1231
+ plen_scaling=3,
1232
+ max_extensions=5,
1233
+ max_intron_size=2000,
1234
+ probe_pattern=r"(\d+)$",
1235
+ ),
1236
+ )
1237
+
1238
+ snakemake_call(snakemake)
1239
+
1240
+
1241
+ if __name__ == "__main__":
1242
+ if "snakemake" in globals():
1243
+ snakemake_call(snakemake)
1244
+ else:
1245
+ main()