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,292 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #
5
+ # Copyright (C) 2024
6
+ # Simón Villanueva CORRALES: simon.corrales@ibot.cas.cz
7
+ # Yann J.K. BERTRAND: yjk_bertrand@ybertrand.org
8
+ #
9
+ # All rights reserved.
10
+
11
+
12
+ __version__ = "0.1"
13
+
14
+ # =======================================================================================
15
+ # IMPORTS
16
+ # =======================================================================================
17
+
18
+ from pathlib import Path
19
+ from operator import itemgetter
20
+ from itertools import groupby
21
+ from collections import defaultdict
22
+ from functools import partial
23
+ from typing import TextIO
24
+ import re
25
+ import sys
26
+
27
+ from Bio import SeqIO
28
+ from Bio.SeqRecord import SeqRecord
29
+ from snakemake.utils import validate
30
+ import polars as pl
31
+ from polars.exceptions import NoDataError
32
+ import pandas as pd
33
+
34
+ # =============================================================================
35
+ # FUNCTIONS
36
+ # =============================================================================
37
+
38
+ PROBE_SCHEMA = (Path(__file__).parent / "../workflow/schemas/probes.yaml").resolve()
39
+
40
+
41
+ class NoGrouping(Exception):
42
+ "Exception raised when a pattern (RegEx) does not yield any grouping"
43
+
44
+
45
+ class NoMatch(Exception):
46
+ "Exception raised when a pattern (RegEx) does not match a probre name"
47
+
48
+
49
+ def group_probes(
50
+ recs: list[SeqRecord],
51
+ pattern: str,
52
+ match_group: int | str = 1,
53
+ strict: bool = True,
54
+ ) -> dict[str, list[SeqRecord]]:
55
+ """Given a list of records with multiple sequences per probe, use the given
56
+ pattern (a RegEx) to group the sequences using their ID. The pattern must
57
+ have at least one capture group. By default, the first capture group will be used
58
+ to group the probes, although other captures group can be specified with match_group.
59
+ If strict, raise a NoGrouping exception if the pattern does not group any records.
60
+ """
61
+
62
+ def get_probe_generic(rec: SeqRecord, pattern: re.Pattern, match_group: int | str):
63
+ if (match := pattern.search(rec.id)) is None:
64
+ raise NoMatch(f"Probe {rec.id} does not match pattern {pattern.pattern}")
65
+ else:
66
+ return match[match_group]
67
+
68
+ pat = re.compile(pattern)
69
+ if pat.groups == 0:
70
+ raise ValueError(
71
+ "RegEx must have at least one capture group that groups the sequences."
72
+ )
73
+ elif isinstance(match_group, int):
74
+ if match_group > pat.groups:
75
+ raise IndexError(
76
+ f"{match_group=} bigger than the number of capture groups ({pat.groups}) in RegEx."
77
+ )
78
+ elif isinstance(match_group, str):
79
+ if match_group not in pat.groupindex:
80
+ raise ValueError(f"{match_group=} not defined in RegEx {pattern}.")
81
+
82
+ get_probe = partial(get_probe_generic, pattern=pat, match_group=match_group)
83
+ probe_recs = {
84
+ probe: list(recs)
85
+ for probe, recs in groupby(sorted(recs, key=get_probe), key=get_probe)
86
+ }
87
+
88
+ if len(probe_recs) == len(recs) and strict:
89
+ raise NoGrouping(f"Pattern {pattern} yielded no grouping of the sequences.")
90
+
91
+ return probe_recs
92
+
93
+
94
+ def write_summary(probe_counts: dict[str, int], output: Path | TextIO) -> None:
95
+ if isinstance(output, Path):
96
+ with output.open("w") as out:
97
+ for probe, count in probe_counts.items():
98
+ out.write(f"{probe}\t{count}\n")
99
+ else:
100
+ for probe, count in probe_counts.items():
101
+ output.write(f"{probe}\t{count}\n")
102
+
103
+
104
+ def write_hierarchy(
105
+ probe_counts: dict[str, list[str]], output: Path, sep: str = ","
106
+ ) -> None:
107
+ with output.open("w") as out:
108
+ for probe, names in probe_counts.items():
109
+ out.write(f"{probe}\t{sep.join(names)}\n")
110
+
111
+
112
+ def check_probes(
113
+ probes_path: Path,
114
+ pattern: str,
115
+ out_summary: Path | None,
116
+ out_hierarchy: Path | None,
117
+ ):
118
+ """Validate that the given probes file follows the naming convention of the schema
119
+ and that the given pattern does group the probes.
120
+ """ # ToDo: Write proper docstring
121
+
122
+ probes = list(SeqIO.parse(probes_path, "fasta"))
123
+ probe_ids = [rec.id for rec in probes]
124
+
125
+ # Test if the probe names comply the naming convention
126
+ validate(pd.DataFrame({"probe_name": probe_ids}), schema=PROBE_SCHEMA)
127
+
128
+ print("Probe sequence names comply with naming convention.", file=sys.stderr)
129
+ try:
130
+ probes_dict = group_probes(probes, pattern)
131
+ except NoMatch as err:
132
+ print(err, file=sys.stderr)
133
+ print(
134
+ "At least one of probe does not match the given pattern",
135
+ file=sys.stderr,
136
+ )
137
+ return
138
+ except NoGrouping as err:
139
+ print(err, file=sys.stderr)
140
+ print(
141
+ "Either this is a single-probe set or the pattern is not appropriate for multi-probe mode",
142
+ file=sys.stderr,
143
+ )
144
+ return
145
+
146
+ probes_counts = {probe: len(recs) for probe, recs in probes_dict.items()}
147
+
148
+ print(
149
+ f"The pattern yields {len(probes_dict)} groups from {len(probes)} probe sequences",
150
+ file=sys.stderr,
151
+ )
152
+ # print("The probes have the following number of members: \n", file=sys.stderr)
153
+ # write_summary(probes_counts, sys.stdout)
154
+
155
+ if out_summary:
156
+ write_summary(probes_counts, out_summary)
157
+
158
+ if out_hierarchy:
159
+ probes_hier = {
160
+ probe: [rec.id for rec in recs] for probe, recs in probes_dict.items()
161
+ }
162
+ write_hierarchy(probes_hier, out_hierarchy)
163
+
164
+
165
+ def add_chim_tag(
166
+ rec: SeqRecord,
167
+ chimera_set: set[str],
168
+ tribble_set: set[tuple[str]],
169
+ pat: re.Pattern,
170
+ ):
171
+ """Add chimera tag to the record based on the Vsearch de novo detection and tribble provenance.
172
+ If the record comes from a tribble it is tagged as 'putative'. If it is additionally detected as
173
+ chimeric by vsearch it is tagged as 'chimeric'. Otherwise, the record is considered normal.
174
+ """
175
+
176
+ get_comp = itemgetter("probe", "sample2", "seed_id", "comp")
177
+
178
+ in_tribble = get_comp(pat.match(rec.id)) in tribble_set
179
+ in_chimeras = rec.id in chimera_set
180
+
181
+ if in_tribble and in_chimeras:
182
+ tag = "chimeric"
183
+ elif in_tribble:
184
+ tag = "putative"
185
+ else:
186
+ tag = "normal"
187
+
188
+ rec.description += f" [chimeric={tag}]"
189
+
190
+
191
+ # Main execution for rule "per_probe_scaffold_grouping" in workflow
192
+ def snakemake_call(snakemake):
193
+ with open(snakemake.log[0], "w") as outlog:
194
+ sys.stdout = sys.stderr = outlog
195
+
196
+ inputs = snakemake.input
197
+ outfolder = Path(snakemake.output[0]).parent
198
+ pattern = snakemake.params.pattern
199
+ probes_list = snakemake.params.get("probes")
200
+ mode = snakemake.params.mode
201
+ pat = re.compile(pattern, re.VERBOSE)
202
+
203
+ # Todo: Refactor this block as a function
204
+ match mode:
205
+ case "exons" | "genetigs" | "supercontigs":
206
+ all_recs = [
207
+ rec
208
+ for file in Path(inputs.scfs[0]).parent.rglob(f"*_{mode}.fasta")
209
+ for rec in SeqIO.parse(file, "fasta")
210
+ ]
211
+ grouped_recs = group_probes(all_recs, pat, match_group="sample1")
212
+
213
+ ## Chimera tagging
214
+ tag_sets = defaultdict(set)
215
+ tribble_sets = defaultdict(set)
216
+
217
+ # Load de novo chimera detection results by vsearch
218
+ # if inputs.get("chimera_tags"):
219
+ # for table in map(Path, inputs.chimera_tags):
220
+ # try:
221
+ # tag_sets[table.stem].update(
222
+ # pl.read_csv(table, separator="\t", has_header=False)[
223
+ # "column_2"
224
+ # ]
225
+ # )
226
+ # except NoDataError:
227
+ # pass
228
+
229
+ if inputs.get("tribbles"):
230
+ # Load tribble tables
231
+ tribble_sets = {
232
+ tribble.stem: set(
233
+ pl.read_csv(tribble, separator="\t").iter_rows()
234
+ )
235
+ for tribble in map(Path, inputs.tribbles)
236
+ }
237
+
238
+ # Add chimera tags to the sequences
239
+ if inputs.get("tribbles") or inputs.get("chimera_tags"):
240
+ for sample, recs in grouped_recs.items():
241
+ for rec in recs:
242
+ add_chim_tag(
243
+ rec, tag_sets[sample], tribble_sets[sample], pat
244
+ )
245
+
246
+ case "scfs":
247
+ all_recs = [
248
+ rec for file in inputs for rec in SeqIO.parse(file, "fasta")
249
+ ]
250
+ grouped_recs = group_probes(all_recs, pat, match_group="probe")
251
+ case "single_probes":
252
+ grouped_recs = {
253
+ pat.search(rec.id)[1]: rec
254
+ for rec in SeqIO.parse(inputs.probes, "fasta")
255
+ }
256
+ case "multi_probes":
257
+ tables_dir = Path(inputs.tables[0]).parent
258
+ matched_probes = set(
259
+ pd.concat(
260
+ pd.read_csv(table, sep="\t") for table in tables_dir.iterdir()
261
+ )["theader"].unique()
262
+ )
263
+ all_recs = [
264
+ rec
265
+ for rec in SeqIO.parse(inputs.probes, "fasta")
266
+ if rec.id in matched_probes
267
+ ]
268
+ grouped_recs = group_probes(all_recs, pat)
269
+ # It could happen that in a very ideal scenario where a single probe
270
+ # version per probe is the only surviving probe, this would raise a NoGrouping exception.
271
+ case _:
272
+ raise ValueError(
273
+ f"{mode=} not recognized. Use scfs, supercontigs, single_probes or multi_probes."
274
+ )
275
+
276
+ # Writing output is common to all uses
277
+ # In "supercontigs" mode, "probe" is actually samples.
278
+ outfolder.mkdir(exist_ok=True)
279
+ for probe, recs in grouped_recs.items():
280
+ SeqIO.write(recs, outfolder / f"{probe}.fasta", "fasta")
281
+
282
+ # In all cases, we may have missing probes, so we need to at least touch them
283
+ # In supercontigs mode this is not needed, because the outputs are per sample,
284
+ # which are guaranteed to exist.
285
+ if mode in ("scfs", "single_probes", "multi_probes"):
286
+ for probe in probes_list:
287
+ (outfolder / f"{probe}.fasta").touch(exist_ok=True)
288
+
289
+
290
+ if __name__ == "__main__":
291
+ if "snakemake" in globals():
292
+ snakemake_call(snakemake)