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,411 @@
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
+ This module filter sequences based on:
13
+
14
+ - GC content.
15
+ - Depth of coverage.
16
+ - MMseqs2 alignment hits against probes.
17
+
18
+ Returning the surviving sequences, and a table of metrics of the best constructed alignment
19
+ of each sequence with its corresponding probe. The table includes the identity and coverage
20
+ of the sequence to its probe.
21
+
22
+ Each filter has its own parameters described below.
23
+
24
+ 1. GC filtering: removes sequences whose GC content falls outside the the range [min_gc, max_gc].
25
+ 2. Coverage filtering: Remove sequences that do not meet depth of coverage criteria as
26
+ estimated by mapping. The filtering can be performed in three modes (absolute, relative,
27
+ and dynamic) and it is controlled by two parameters (cov_threshold and cov_dynamic_filt)
28
+
29
+ - In absolute mode (cov_dynamic_filt=False, cov_threshold > 1): All sequences with a depth
30
+ below the given threshold (e.g. 10) are filtered.
31
+ - In relative mode (cov_dynamic_filt=False, cov_threshold in [0 - 1]): The threshold indicates
32
+ the fraction of sequences to be removed. For instance, if cov_threshold=0.05, the 5% of the
33
+ sequences with the lowest coverage will be filtered.
34
+ - In dynamic mode (cov_dynamic_filt=True): A hard_threhold is computed from the distribution
35
+ of depths by the formula: hard_threhold = median(depths) - cov_threshold * std(depths).
36
+ The cov_threshold parameter modulates how strict the filter is from deviations from the
37
+ observed median depth. To make the computation more robust, the 5% lowest depths and 5%
38
+ highest depths are filtered from the distribution before the computation. Sequences with
39
+ a depth below hard_threshold are filtered.
40
+
41
+ 3. Alignment againt probes filtering: Filter the sequences whose best alignment against probes
42
+ do not meet the minimum identity (scf_min_idt) or coverage (scf_min_cov) required.
43
+ """
44
+
45
+ __version__ = "0.1"
46
+
47
+ # =======================================================================================
48
+ # IMPORTS
49
+ # =======================================================================================
50
+
51
+ from pathlib import Path
52
+ import sys
53
+
54
+ import polars as pl
55
+ import numpy as np
56
+ from Bio import SeqIO
57
+ from Bio.SeqRecord import SeqRecord
58
+ from Bio.SeqUtils import gc_fraction
59
+ from intervaltree import IntervalTree
60
+
61
+ from graph_utils import build_probe_trees, filt_probe_hits
62
+
63
+
64
+ # =======================================================================================
65
+ # CONSTANTS
66
+ # =======================================================================================
67
+
68
+ REF_PAT = r".*probe([0-9]+)$"
69
+ SAUTE_PAT = r"^Contig_(?P<sample>.*?)-(?P<probe>.*?)_(?P<cluster>.+?)_(?P<seed>\d+?):(?P<component>\d+?):[^ ]+$"
70
+ METABAT_COLS = ["query", "len", "cov", "nu", "var"]
71
+ DMND_COLS = [
72
+ "query",
73
+ "evalue",
74
+ "qstart",
75
+ "qend",
76
+ "qlen",
77
+ "tstart",
78
+ "tend",
79
+ "tlen",
80
+ "theader",
81
+ "gapopen",
82
+ "nident",
83
+ "mismatch",
84
+ ]
85
+
86
+ # =============================================================================
87
+ # FUNCTIONS
88
+ # =============================================================================
89
+
90
+
91
+ def orient_scf(rec: SeqRecord, trans: bool) -> SeqRecord:
92
+ if trans:
93
+ rec.seq = rec.seq.reverse_complement()
94
+ return rec
95
+
96
+
97
+ def tag_probe(rec: SeqRecord, probe: str) -> SeqRecord:
98
+ """Add the probe information in the record name after the '-'"""
99
+
100
+ idx = rec.id.index("-")
101
+ rec.id = f"{rec.id[:idx+1]}{probe}_{rec.id[idx+1:]}"
102
+ rec.name = rec.description = ""
103
+ return rec
104
+
105
+
106
+ def filter_gc_recs(
107
+ df: pl.DataFrame,
108
+ recs_dict: dict[str, SeqRecord],
109
+ max_gc: float = 0.6,
110
+ min_gc: float = 0.2,
111
+ ):
112
+ """Given a dataframe of hits, filter the query sequences (scfs) with a higher
113
+ gc than max_gc. Return the resulting dataframe."""
114
+
115
+ high_gc_map = {
116
+ name: min_gc <= gc_fraction(rec) <= max_gc for name, rec in recs_dict.items()
117
+ }
118
+ return df.filter(pl.col("query").replace_strict(high_gc_map))
119
+
120
+
121
+ def filter_by_cov(
122
+ df: pl.DataFrame, cov_table: Path, threshold: int | float, dynamic: bool = True
123
+ ):
124
+ """Given a dataframe of hits, filter the query sequences (scfs) by the observed coverage
125
+ from mapped reads."""
126
+
127
+ meta_df = pl.read_csv(cov_table, separator="\t", new_columns=METABAT_COLS)
128
+ covs = meta_df["cov"].to_numpy()
129
+
130
+ if dynamic:
131
+ low, high = np.quantile(covs, [0.05, 0.95])
132
+ mask = (covs > low) & (covs < high)
133
+ subarr = covs[mask]
134
+ median = np.median(subarr)
135
+ std = subarr.std()
136
+ print(f"Coverage mode: dynamic ({median=:.2f}, {std=:.2f}, {threshold=})")
137
+ limit_cov = np.median(subarr) - threshold * subarr.std()
138
+ limit_cov = limit_cov if limit_cov > 0 else 0
139
+ elif threshold >= 1:
140
+ print(f"Coverage mode: absolute ({threshold=})")
141
+ limit_cov = threshold
142
+ elif threshold > 0:
143
+ print(f"Coverage mode: relative ({threshold=})")
144
+ limit_cov = np.quantile(covs, threshold)
145
+ else:
146
+ raise ValueError(
147
+ f"""Error: {threshold=} has to be [0-1] for relative filtering
148
+ or a positive integer for absolute filtering."""
149
+ )
150
+ print(f"Coverage threshold set at {limit_cov:.2f}")
151
+
152
+ surviving_scfs = meta_df.filter(pl.col("cov") >= limit_cov).select("query")
153
+ return df.join(surviving_scfs, on="query")
154
+
155
+
156
+ def compute_hits(
157
+ df: pl.DataFrame,
158
+ min_cov: float,
159
+ min_idt: float,
160
+ qpat: str = SAUTE_PAT,
161
+ tpat: str = REF_PAT,
162
+ ) -> pl.DataFrame:
163
+ """Parse the alignments and determine the sequences that satisfy the min_cov
164
+ and min_idt thresholds.
165
+
166
+ If qpat is given, a pattern is expected to extract the probe version from the
167
+ query name. If qpat is None, a best probe version is determined from the hits
168
+ and picked. This probe information will be used to filter hits different to
169
+ that probe.
170
+
171
+ The remaining sequences (queries) are filtered to comply with the minimum
172
+ coverage and identity to the best they match.
173
+ """
174
+
175
+ def _real_cov(tstart: list[int], tend: list[int]) -> int:
176
+ tree = IntervalTree.from_tuples(zip(tstart, tend))
177
+ tree.merge_overlaps(strict=False)
178
+ return sum(inter.length() for inter in tree)
179
+
180
+ df.replace_column(8, df["theader"].str.split(" ").list.first())
181
+
182
+ # Diamond adds the gaps to the mismatches, so we have to correct that.
183
+ pre_df = df.with_columns(
184
+ pl.col("tstart") - 1,
185
+ tprobe=pl.col("theader").str.extract(tpat, 1),
186
+ cis=pl.col("qend") > pl.col("qstart"),
187
+ # mismatch=(pl.col("mismatch") - pl.col("gaps")),
188
+ )
189
+
190
+ # If query comes with probe information, filter to keep only matches of that probe.
191
+ if qpat:
192
+ pre_df = pre_df.with_columns(
193
+ qprobe=pl.col("query").str.extract(qpat, 2)
194
+ ).filter(pl.col("qprobe") == pl.col("tprobe"))
195
+
196
+ # else:
197
+ # pre_df = df.with_columns(
198
+ # pl.col("tstart") - 1,
199
+ # tprobe=pl.col("theader").str.extract(tpat, 1),
200
+ # cis=pl.col("qend") > pl.col("qstart"),
201
+ # )
202
+
203
+ # We determine the best probe.
204
+ probe_trees = build_probe_trees(pre_df, min_idt)
205
+ pre_df = filt_probe_hits(pre_df, probe_trees)
206
+
207
+ gdf = (
208
+ pre_df.group_by(["query", "theader", "cis"])
209
+ .agg(
210
+ pl.sum("nident"),
211
+ pl.sum("mismatch"),
212
+ pl.sum("gapopen"),
213
+ pl.first("tlen"),
214
+ pl.first("tprobe"),
215
+ pl.col("tstart"),
216
+ pl.col("tend"),
217
+ pl.first("glob_eff_cov"),
218
+ pl.first("glob_cov"),
219
+ )
220
+ .with_columns(
221
+ adj_cov=(
222
+ pl.struct(["tstart", "tend"]).map_elements(
223
+ lambda x: _real_cov(**x), return_dtype=pl.Int64
224
+ )
225
+ )
226
+ )
227
+ )
228
+
229
+ final_df = (
230
+ gdf.with_columns(
231
+ cov=pl.col("adj_cov") / pl.col("tlen"),
232
+ idt=pl.col("nident") / (pl.col("nident") + pl.col("mismatch")),
233
+ )
234
+ .with_columns(eff_cov=(pl.col("cov") * pl.col("idt")))
235
+ .filter((pl.col("cov") > min_cov) & (pl.col("idt") > min_idt))
236
+ .group_by("query")
237
+ .agg(pl.all().sort_by("eff_cov", descending=True).first())
238
+ )
239
+
240
+ return final_df.drop(["tstart", "tend"])
241
+
242
+
243
+ def filt_records(recs: list[SeqRecord], filt_ids: dict[str, bool]) -> list[SeqRecord]:
244
+ return (
245
+ orient_scf(rec, trans)
246
+ for rec in recs
247
+ if (trans := filt_ids.get(rec.id)) is not None
248
+ )
249
+
250
+
251
+ def match_mmseqs_recs(
252
+ rec_path: Path,
253
+ table_path: Path,
254
+ cov_path: Path,
255
+ out_path: Path,
256
+ out_table: Path,
257
+ min_cov: float,
258
+ min_idt: float,
259
+ qpat: str,
260
+ tpat: str,
261
+ max_gc: float = 0.6,
262
+ min_gc: float = 0.2,
263
+ cov_threshold: int | float = 0.025,
264
+ cov_dynamic_filt: bool = False,
265
+ sep_probes: bool = False,
266
+ tag_scfs: bool = False,
267
+ ) -> None:
268
+ """Given a set of file with sequences, and a table with mmseqs2 matches against a set
269
+ of probes, filter the sequences to those that match the probes with at least a minimum
270
+ coverage and a minimum identity.
271
+
272
+ A target pattern (tpat) is required to extract the probe id from the probes db hits. Similarly a
273
+ query pattern (qpat) can be provided, although is optional. If provided, the alignments will be
274
+ filtered to those that match query_probe and target_probe.
275
+
276
+ Finally, is sep_probes is true the sequences will be separated per probe in an output directory.
277
+ Otherwise, all sequences will be written together in a single file.
278
+ """
279
+
280
+ recs_dict = SeqIO.to_dict(SeqIO.parse(rec_path, "fasta"))
281
+ df = pl.read_csv(
282
+ table_path, separator="\t", has_header=False, new_columns=DMND_COLS
283
+ )
284
+ n0 = df["query"].unique().count()
285
+ print(f"Starting seeds: {n0}")
286
+
287
+ # Apply GC filter:
288
+ df = filter_gc_recs(df, recs_dict, max_gc, min_gc)
289
+ n1 = df["query"].unique().count()
290
+ print(f"Seeds after GC filter: {n1} (removed {n0 - n1})")
291
+
292
+ # Apply Coverage filter
293
+ df = filter_by_cov(df, cov_path, cov_threshold, cov_dynamic_filt)
294
+ n2 = df["query"].unique().count()
295
+ print(f"Seeds after Depth filter: {n2} (removed {n1 - n2})")
296
+
297
+ # Compute the hits from the filtered sequences
298
+ filt_df = compute_hits(df, min_cov, min_idt, qpat, tpat)
299
+ n3 = filt_df["query"].unique().count()
300
+ print(f"Seeds after Probes matching filter: {n3} (removed {n2 - n3})")
301
+ print(f"Final set of seeds: {n3} (total removed {n0 - n3})")
302
+
303
+ # Save the computation results in the log
304
+ if out_table:
305
+ filt_df.write_csv(out_table, separator="\t")
306
+
307
+ # Separate the surviving sequences by probe
308
+ if sep_probes:
309
+ out_path.mkdir(exist_ok=True)
310
+ iter_df = filt_df.group_by("tprobe").all().select(["tprobe", "query", "cis"])
311
+
312
+ for probe, ids, orient_list in iter_df.iter_rows():
313
+ probe_recs = [
314
+ tag_probe(orient_scf(recs_dict[rec_id], not cis), probe)
315
+ for rec_id, cis in zip(ids, orient_list)
316
+ ]
317
+ SeqIO.write(probe_recs, out_path / f"{probe}.fasta", "fasta")
318
+
319
+ # Do not separate the sequences in multiple files, but tag them.
320
+ elif tag_scfs:
321
+ iter_df = filt_df.select(["tprobe", "query", "cis"]).iter_rows()
322
+ filt_scfs = [
323
+ tag_probe(orient_scf(recs_dict[rec_id], not cis), probe)
324
+ for probe, rec_id, cis in iter_df
325
+ ]
326
+ SeqIO.write(filt_scfs, out_path, "fasta")
327
+
328
+ # Output all sequences in a single file (they are already tagged)
329
+ else:
330
+ filt_ids = dict(
331
+ filt_df.select(["query", "cis"]).with_columns(~pl.col("cis")).iter_rows()
332
+ )
333
+ filt_scfs = filt_records(recs_dict.values(), filt_ids)
334
+ SeqIO.write(filt_scfs, out_path, "fasta")
335
+
336
+
337
+ def snakemake_call(snakemake):
338
+ with open(snakemake.log[0], "w") as outlog:
339
+ sys.stdout = sys.stderr = outlog
340
+
341
+ # Read input and outputs
342
+ recs = Path(snakemake.input.scfs)
343
+ hits = Path(snakemake.input.hits)
344
+ covs = Path(snakemake.input.covs)
345
+ seeds = Path(snakemake.output.scfs)
346
+ out_table = Path(snakemake.output.metrics)
347
+
348
+ # Params: GC based filtering
349
+ max_gc = snakemake.params.max_gc
350
+ min_gc = snakemake.params.min_gc
351
+
352
+ # Params: Coverage filtering
353
+ cov_threshold = snakemake.params.cov_threshold
354
+ cov_dynamic_filt = snakemake.params.cov_dynamic_filt
355
+
356
+ # Params: probe hits filtering
357
+ min_idt = snakemake.params.min_idt
358
+ min_cov = snakemake.params.min_cov
359
+ qpat = snakemake.params.get("qpat", SAUTE_PAT)
360
+ tpat = snakemake.params.get("tpat", REF_PAT)
361
+
362
+ # Output params
363
+ sep_probes = snakemake.params.separate_probes
364
+ tag_scfs = snakemake.params.get("tag_scfs", False)
365
+
366
+ match_mmseqs_recs(
367
+ rec_path=recs,
368
+ table_path=hits,
369
+ cov_path=covs,
370
+ out_path=seeds,
371
+ out_table=out_table,
372
+ min_cov=min_cov,
373
+ min_idt=min_idt,
374
+ qpat=qpat,
375
+ tpat=tpat,
376
+ max_gc=max_gc,
377
+ min_gc=min_gc,
378
+ cov_threshold=cov_threshold,
379
+ cov_dynamic_filt=cov_dynamic_filt,
380
+ sep_probes=sep_probes,
381
+ tag_scfs=tag_scfs,
382
+ )
383
+
384
+
385
+ def main():
386
+
387
+ if len(sys.argv) != 4:
388
+ print(
389
+ "Usage: python homolog_filtering.py <scfs.fasta> <hits.tsv> <output.fasta>"
390
+ )
391
+ sys.exit(1)
392
+
393
+ min_idt = 0.6
394
+ min_cov = 0.0
395
+ sep_probes = False
396
+
397
+ recs = Path(sys.argv[1])
398
+ table = Path(sys.argv[2])
399
+ out = Path(sys.argv[3])
400
+
401
+ qpat = None
402
+ tpat = r"(\d+)$"
403
+
404
+ match_mmseqs_recs(recs, table, out, min_cov, min_idt, qpat, tpat, sep_probes)
405
+
406
+
407
+ if __name__ == "__main__":
408
+ if "snakemake" in globals():
409
+ snakemake_call(snakemake)
410
+ else:
411
+ main()