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,387 @@
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 does two tasks in preparation for assembly with saute:
13
+
14
+ 1. Collects potentially informative seeds based on vsearch clustering.
15
+ 2. A Heuristic computes the kmer sizes based on the depth observed during the seeds assembly.
16
+
17
+ The seeds for a given sample are composed of:
18
+ - The seeds assembled for that sample (intra-seeds).
19
+ - The seeds of "sister-samples" (inter-seeds).
20
+ - The probes sequences for those probes that were not represented already
21
+ in the intra or inter-seeds.
22
+
23
+ #ToDo: Expand the docstring to include more details about the sister samples and inter-seeds.
24
+
25
+ The computation of the kmer sizes is based on the depth observed during the seeds assembly.
26
+ The read median depth of the sample observed during assembly is computed from the kmer depth
27
+ and kmer size found during seeds assembly. The heuristic consists in computing the primary
28
+ and secondary kmer sizes by targeting a given primary and secondary depth. The kmer sizes
29
+ are constrained to a range of values defined in the heuristic parameters.
30
+ """
31
+
32
+ __version__ = "0.1"
33
+
34
+ # =======================================================================================
35
+ # IMPORTS
36
+ # =======================================================================================
37
+
38
+ from pathlib import Path
39
+ from typing import TypedDict
40
+ from collections import Counter, defaultdict
41
+ import json
42
+ import re
43
+
44
+ from Bio import SeqIO
45
+ import numpy as np
46
+ import polars as pl
47
+ from more_itertools import one
48
+
49
+ from multi_seq_probes import group_probes
50
+
51
+ # =======================================================================================
52
+ # CONSTANTS
53
+ # =======================================================================================
54
+
55
+ CLUSTER_COLS = [
56
+ "type",
57
+ "cluster_id",
58
+ "size",
59
+ "idt",
60
+ "strand",
61
+ "NU1",
62
+ "NU2",
63
+ "cigar",
64
+ "query",
65
+ "centroid",
66
+ ]
67
+ REC_PAT = r"^(.*?)-(.*?)_EDGE_.*_cov_([\d\.]+)$"
68
+ METABAT_COLS = ("query", "len", "cov", "nu", "var")
69
+
70
+ # =============================================================================
71
+ # CLASSES
72
+ # =============================================================================
73
+
74
+
75
+ class KmerParams(TypedDict):
76
+ """Parameters for kmer size computation."""
77
+
78
+ primary_target_depth: int
79
+ secondary_target_depth: int
80
+ k1_min: float
81
+ k1_max: float
82
+ k2_min: float
83
+ k2_max: float
84
+
85
+
86
+ # =============================================================================
87
+ # FUNCTIONS
88
+ # =============================================================================
89
+
90
+
91
+ def get_spades_kmer_size(spades_graph: Path) -> int:
92
+ """Get the kmer size used by spades from the assembly graph."""
93
+
94
+ with spades_graph.open() as gfa:
95
+ for line in gfa:
96
+ if line.startswith("S"):
97
+ _, seq, _dp, _kc = line.strip().split("\t")[1:]
98
+ dp = float(_dp.removeprefix("DP:f:"))
99
+ kc = int(_kc.removeprefix("KC:i:"))
100
+
101
+ return round(len(seq) - kc / dp)
102
+
103
+
104
+ def get_map_coverage(cov_table: Path) -> float:
105
+ """Get the median depth of coverage found by read mapping."""
106
+ meta_df = pl.read_csv(cov_table, separator="\t", new_columns=METABAT_COLS)
107
+ return meta_df["cov"].median()
108
+
109
+
110
+ def get_read_length(read_stats: Path) -> int:
111
+ """Get the read length from the fastp report."""
112
+
113
+ summary = json.loads(read_stats.read_text())
114
+ return int(summary["summary"]["after_filtering"]["read2_mean_length"])
115
+
116
+
117
+ def compute_saute_kmers(
118
+ read_med_cov: float,
119
+ L: int,
120
+ kmer_params: KmerParams,
121
+ ) -> str:
122
+ """Compute the kmer sizes to be used by saute based on the median coverage,
123
+ read length, and the target depths for primary and secondary kmers. The kmer
124
+ sizes are constrained to a range of values defined in the heuristic parameters."""
125
+
126
+ # Compute kmer sizes for the given targets depths
127
+ k1 = int(L * (1 - (kmer_params["primary_target_depth"] / read_med_cov)) + 1)
128
+ k2 = int(L * (1 - (kmer_params["secondary_target_depth"] / read_med_cov)) + 1)
129
+
130
+ # Constrain the kmer sizes to "sane" ranges (defined in the parameters):
131
+ k1_min, k1_max = int(L * kmer_params["k1_min"]), int(L * kmer_params["k1_max"])
132
+ k2_min, k2_max = int(L * kmer_params["k2_min"]), int(L * kmer_params["k2_max"])
133
+
134
+ # Cap primary and secondary kmers to their respective absolute floors (Def: 49, 21)
135
+ k1_min = max(k1_min, int(kmer_params["k1_floor"]))
136
+ k2_min = max(k2_min, int(kmer_params["k2_floor"]))
137
+
138
+ if k2 < k2_min:
139
+ k2 = k2_min
140
+ elif k2 > k2_max:
141
+ k2 = k2_max
142
+
143
+ if k1 < k1_min:
144
+ k1 = k1_min
145
+ elif k1 > k1_max:
146
+ k1 = k1_max
147
+
148
+ # Ensure odd kmers
149
+ k2 = k2 - 1 if k2 % 2 == 0 else k2
150
+ k1 = k1 - 1 if k1 % 2 == 0 else k1
151
+
152
+ # Pack the results to log them later
153
+ kmer_results = {
154
+ "read_med_cov": read_med_cov,
155
+ "primary_target_depth": kmer_params["primary_target_depth"],
156
+ "secondary_target_depth": kmer_params["secondary_target_depth"],
157
+ "k1_min": k1_min,
158
+ "k1_max": k1_max,
159
+ "k2_min": k2_min,
160
+ "k2_max": k2_max,
161
+ "k1": k1,
162
+ "k2": k2,
163
+ }
164
+
165
+ return kmer_results
166
+
167
+
168
+ def infer_sister_samples(
169
+ probe_tables: dict[str, dict[str, pl.DataFrame]],
170
+ ) -> dict[str, dict[str, tuple[int, int]]]:
171
+ """Use the clustering results for all the probes to determine the sister samples
172
+ of all samples in the run.
173
+
174
+ For a given sample and probe, look at which other samples co-occur in the same
175
+ clusters for that probe. Those will constitute the "sister-samples" for that sample
176
+ according to that probe.
177
+
178
+ After consulting all the probes, keep the sister samples that were voted by more than
179
+ min_sister_freq proportion of all probes.
180
+
181
+ Return a dictionary of samples as key and their inferred sister-samples as values.
182
+ """
183
+
184
+ sister_samples = defaultdict(Counter)
185
+ samples = pl.concat(probe_tables.values())["sample"].unique().to_list()
186
+
187
+ for probe, table in probe_tables.items():
188
+ for sample in samples:
189
+ clusters = set(
190
+ table.filter(pl.col("sample") == sample)["cluster_id"].unique()
191
+ )
192
+ sister_samples[sample].update(
193
+ table.filter(pl.col("cluster_id").is_in(clusters))["sample"].unique()
194
+ )
195
+
196
+ # Compute the sister samples based on the votes of each probe
197
+ sister_samples = {
198
+ sample: {
199
+ sister: (count, counts[sample])
200
+ for sister, count in counts.most_common()
201
+ if sister != sample
202
+ }
203
+ for sample, counts in sister_samples.items()
204
+ }
205
+
206
+ return sister_samples
207
+
208
+
209
+ # ToDo: Add logging to this function.
210
+ def snakemake_call(snakemake):
211
+ # Read inputs for seed collection
212
+ cluster_tables_dir = snakemake.input.cluster_tables
213
+ sample_probes_dir = snakemake.input.samples
214
+ probes_path = snakemake.input.probes
215
+
216
+ # Read inputs for saute kmer size computation
217
+ spades_graphs = snakemake.input.spades_graphs
218
+ read_stats = snakemake.input.read_stats
219
+ cov_paths = snakemake.input.covs
220
+
221
+ # Read outputs
222
+ seeds_out = snakemake.output.seeds
223
+ saute_params = snakemake.output.saute_params
224
+
225
+ # Params for seed collection
226
+ probes_pattern = snakemake.params.pattern
227
+ multi_probes = snakemake.params.is_multi
228
+ interseeds_use = snakemake.params.interseeds_use
229
+ min_sister_freq = snakemake.params.min_sister_freq
230
+ sister_dir = Path(snakemake.params.sister_samples_dir)
231
+
232
+ # Params for saute kmer size computation
233
+ cov_by_mapping = snakemake.params.cov_by_mapping
234
+ heuristic_params = snakemake.params.heuristic_params
235
+
236
+ # Parse the records fo all the samples
237
+ sample_recs = {
238
+ sample.stem: {
239
+ probe: SeqIO.to_dict(recs)
240
+ for probe, recs in group_probes(
241
+ list(SeqIO.parse(sample, "fasta")), REC_PAT, 2, strict=False
242
+ ).items()
243
+ }
244
+ for sample in map(Path, sample_probes_dir)
245
+ }
246
+
247
+ ## Kmer size parameters computation
248
+ # Organize the Spades folders and fastp reports to make them accessible by sample
249
+ spades_graphs = {graph.parent.name: graph for graph in map(Path, spades_graphs)}
250
+ read_covs = {file.stem: get_map_coverage(file) for file in map(Path, cov_paths)}
251
+ read_lengths = {file.stem: get_read_length(file) for file in map(Path, read_stats)}
252
+ kmer_params_out = {file.stem: file for file in map(Path, saute_params)}
253
+
254
+ # Compute the kmer sizes to be used by saute for each sample
255
+ pat = re.compile(REC_PAT)
256
+ for sample, probe_recs in sample_recs.items():
257
+ L = read_lengths[sample]
258
+
259
+ # Compute median depth observed in base space
260
+ # By mapping
261
+ if cov_by_mapping:
262
+ read_med_cov = read_covs[sample]
263
+ kmer_log = {"read_length": L, "cov_estimation": "mapping"}
264
+
265
+ # By spades assembly
266
+ else:
267
+ kspades = get_spades_kmer_size(spades_graphs[sample])
268
+ med_cov = np.median(
269
+ [
270
+ float(pat.search(rec)[3])
271
+ for recs in probe_recs.values()
272
+ for rec in recs
273
+ ]
274
+ )
275
+ read_med_cov = med_cov * L / (L - kspades + 1)
276
+ kmer_log = {
277
+ "read_length": L,
278
+ "cov_estimation": "assembly",
279
+ "kspades": kspades,
280
+ }
281
+
282
+ kmer_results = compute_saute_kmers(read_med_cov, L, heuristic_params)
283
+ kmer_log.update(kmer_results)
284
+
285
+ # Write the kmer results to a log file
286
+ kmer_params_out[sample].write_text(json.dumps(kmer_log, indent=4))
287
+
288
+ ## Seed collection
289
+ # Read the probes in order to supplement the seeds in case they are missing
290
+ probes = list(SeqIO.parse(probes_path, "fasta"))
291
+ if multi_probes:
292
+ probes_dict = group_probes(probes, probes_pattern)
293
+ else:
294
+ probe_pat = re.compile(probes_pattern)
295
+ probes_dict = {probe_pat.search(probe.id)[1]: [probe] for probe in probes}
296
+
297
+ # Reformat the probes name to follow the seeds pattern
298
+ for probe, recs in probes_dict.items():
299
+ for rec in recs:
300
+ rec.id = f"{rec.id}-{probe}_EDGE_0_length_{len(rec)}_cov_0.0"
301
+ rec.name = rec.description = ""
302
+
303
+ # Load the clustering tables
304
+ probe_tables = {}
305
+ for probe in map(Path, cluster_tables_dir):
306
+ if probe.stat().st_size == 0:
307
+ continue
308
+
309
+ probe_tables[probe.stem] = pl.read_csv(
310
+ probe, separator="\t", has_header=False, new_columns=CLUSTER_COLS
311
+ ).with_columns(sample=pl.col("query").str.extract(REC_PAT))
312
+
313
+ # Subset the inter-seeds with the sister-samples approach
314
+ if interseeds_use == "sister":
315
+ # sister_dir = Path(saute_params[0]).parent.parent / "sister_samples"
316
+ sister_dir.mkdir(parents=True, exist_ok=True)
317
+
318
+ sister_samples_counts = infer_sister_samples(probe_tables)
319
+
320
+ # Log the sister samples counts
321
+ for sample, sister_samples in sister_samples_counts.items():
322
+ (sister_dir / f"{sample}.json").write_text(json.dumps(sister_samples))
323
+
324
+ # Filter to keep the sister samples above the frequency threshold
325
+ sister_samples = {
326
+ sample: {
327
+ sister
328
+ for sister, (count, max_count) in sister_samples.items()
329
+ if count / max_count > min_sister_freq
330
+ }
331
+ for sample, sister_samples in sister_samples_counts.items()
332
+ }
333
+
334
+ # Redistribute the seeds according complementing with the centroids of clusters
335
+ # where sister samples are present
336
+ # This is a clusters centric approach, where we take the seeds from the current sample
337
+ # and then we add the centroids of the clusters its sister samples matched as extra seeds.
338
+ sample_seeds = defaultdict(list)
339
+ for probe, probe_table in probe_tables.items():
340
+ for sample in sample_recs:
341
+ # First, add the seeds from the current sample
342
+ sample_seeds[sample].extend(sample_recs[sample].get(probe, {}).values())
343
+
344
+ # If following sister-sample strategy, subset the table to sister clusters
345
+ if interseeds_use == "sister":
346
+ # Find the clusters that sister samples matched
347
+ clusters = (
348
+ probe_table.filter(pl.col("sample").is_in(sister_samples[sample]))
349
+ .select("cluster_id")
350
+ .unique()
351
+ )
352
+ table = probe_table.join(clusters, on="cluster_id", how="inner")
353
+ else:
354
+ table = probe_table
355
+
356
+ # Then, add the centroids of the clusters as extra seeds (inter-seeds)
357
+ if interseeds_use != "none":
358
+ for inter_sample, rec in (
359
+ table.filter((pl.col("type") == "C") & (pl.col("sample") != sample))
360
+ .select(["sample", "query"])
361
+ .iter_rows()
362
+ ):
363
+ # One sample does not have a given probe. But why is it triggering Key Error?
364
+ sample_seeds[sample].append(sample_recs[inter_sample][probe][rec])
365
+
366
+ # Finally, add the probes that were not present in the sample seeds.
367
+ for sample, seeds in sample_seeds.items():
368
+ covered_probes = {pat.search(seed.id)[2] for seed in seeds}
369
+ for missing_probe in set(probes_dict) - covered_probes:
370
+ seeds.extend(probes_dict[missing_probe])
371
+
372
+ # Write the seeds for all the samples
373
+ seeds_out_dir = Path(seeds_out[0]).parent
374
+ seeds_out_dir.mkdir(exist_ok=True, parents=True)
375
+
376
+ for sample, seeds in sample_seeds.items():
377
+ SeqIO.write(seeds, seeds_out_dir / f"{sample}.fasta", "fasta")
378
+
379
+
380
+ def main(): ...
381
+
382
+
383
+ if __name__ == "__main__":
384
+ if "snakemake" in globals():
385
+ snakemake_call(snakemake)
386
+ else:
387
+ main()