NextPyper 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nextpyper/__init__.py +0 -0
- nextpyper/__main__.py +429 -0
- nextpyper/config/config.yaml +80 -0
- nextpyper/config/rich_config.yaml +54 -0
- nextpyper/config/system_config.yaml +10 -0
- nextpyper/data/blosum62.csv +32 -0
- nextpyper/data/cps_seqids.csv +674 -0
- nextpyper/data/mock/mock_args.yaml +17 -0
- nextpyper/data/mock/probes.fasta +56 -0
- nextpyper/data/mock/reads/sample1_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample1_R2.fastq +20 -0
- nextpyper/data/mock/reads/sample2_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample2_R2.fastq +20 -0
- nextpyper/data/mock/reads/sample3_R1.fastq +20 -0
- nextpyper/data/mock/reads/sample3_R2.fastq +20 -0
- nextpyper/data/mock/sample.tsv +4 -0
- nextpyper/nextpyper.CITATION +9 -0
- nextpyper/nextpyper.LICENSE +19 -0
- nextpyper/nextpyper.VERSION +1 -0
- nextpyper/src/divergence_estimation.py +131 -0
- nextpyper/src/diversity.py +93 -0
- nextpyper/src/exon_discovery.py +294 -0
- nextpyper/src/exon_intron.py +197 -0
- nextpyper/src/fix_headers.py +107 -0
- nextpyper/src/gfa2fasta.py +71 -0
- nextpyper/src/gfa_graph.py +1245 -0
- nextpyper/src/gff_parser.py +344 -0
- nextpyper/src/graph_utils.py +201 -0
- nextpyper/src/homolog_filtering.py +411 -0
- nextpyper/src/miniprot.py +1008 -0
- nextpyper/src/multi_seq_probes.py +292 -0
- nextpyper/src/run_orfipy.py +493 -0
- nextpyper/src/sample_table.py +63 -0
- nextpyper/src/seeds_collection.py +387 -0
- nextpyper/src/summarize_results.py +507 -0
- nextpyper/src/union_find.py +65 -0
- nextpyper/src/var_asm_parser.py +229 -0
- nextpyper/test/.gitkeep +0 -0
- nextpyper/workflow/Snakefile +62 -0
- nextpyper/workflow/envs/alignment.yaml +7 -0
- nextpyper/workflow/envs/assembly.yaml +8 -0
- nextpyper/workflow/envs/clustering.yaml +9 -0
- nextpyper/workflow/envs/matching.yaml +8 -0
- nextpyper/workflow/envs/preprocessing.yaml +11 -0
- nextpyper/workflow/envs/saute.yaml +7 -0
- nextpyper/workflow/envs/translating.yaml +8 -0
- nextpyper/workflow/rules/0_preprocessing/0.1_reads.smk +90 -0
- nextpyper/workflow/rules/0_preprocessing/0.2_probes.smk +16 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.1_assembly_spades.smk +48 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.2_seeds_extension.smk +90 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.3_seeds_filtering.smk +64 -0
- nextpyper/workflow/rules/1_seeds_assembly/1.4_seeds_clustering.smk +73 -0
- nextpyper/workflow/rules/2_homologs_assembly/2.1_saute_assembly.smk +228 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.1_allele_collapsing.smk +23 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.2_homologs_filtering.smk +76 -0
- nextpyper/workflow/rules/3_homolog_prospection/3.3_region_separation.smk +189 -0
- nextpyper/workflow/rules/common.smk +160 -0
- nextpyper/workflow/schemas/probes.yaml +12 -0
- nextpyper/workflow/schemas/sample_table.yaml +29 -0
- nextpyper/workflow/scripts/bench_busco.py +572 -0
- nextpyper/workflow/scripts/categories_bench.sh +92 -0
- nextpyper/workflow/scripts/end_recs_parser.py +146 -0
- nextpyper/workflow/scripts/tribble_stats.py +131 -0
- nextpyper-0.1.0.dist-info/METADATA +231 -0
- nextpyper-0.1.0.dist-info/RECORD +69 -0
- nextpyper-0.1.0.dist-info/WHEEL +5 -0
- nextpyper-0.1.0.dist-info/entry_points.txt +3 -0
- nextpyper-0.1.0.dist-info/licenses/nextpyper/nextpyper.LICENSE +19 -0
- nextpyper-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,507 @@
|
|
|
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
|
+
# ToDo: Expand on the assumptions and usage
|
|
12
|
+
"""
|
|
13
|
+
Functions to summarize the results from a NextPyper run. The main function of the module is
|
|
14
|
+
summarize workflow, and given the ouput directory of a successful NextPyper run, it creates
|
|
15
|
+
a table with the following metrics about the run (for each sample):
|
|
16
|
+
|
|
17
|
+
- raw_reads: Number of raw reads in the sample.
|
|
18
|
+
- trimmed_reads: Number of reads after trimming.
|
|
19
|
+
- cleaned_reads: Number of reads after cleaning (rRNA + [cpDNA]).
|
|
20
|
+
- probe_matching_reads: Number of reads after probe matching filtering.
|
|
21
|
+
- probes_in_assembly: Number of probes that had a hit in the assembly.
|
|
22
|
+
- probes_at_25pct: Number of probes in the final alignments that have at least 25% of the probe length.
|
|
23
|
+
- probes_at_50pct: Number of probes in the final alignments that have at least 50% of the probe length.
|
|
24
|
+
- probes_at_75pct: Number of probes in the final alignments that have at least 75% of the probe length.
|
|
25
|
+
- probes_at_100pct: Number of probes in the final alignments that have at least 100% of the probe length.
|
|
26
|
+
- probes_at_125pct: Number of probes in the final alignments that have at least 125% of the probe length.
|
|
27
|
+
|
|
28
|
+
Example of usage:
|
|
29
|
+
|
|
30
|
+
>>> results_dir = Path("my_directory/nextpyper_output")
|
|
31
|
+
>>> out_stats = Path("my_directory/stats_nextpyper.csv")
|
|
32
|
+
>>> stats = summarize_workflow(results_dir)
|
|
33
|
+
>>> stats.to_csv(out_stats, index=False)
|
|
34
|
+
|
|
35
|
+
Will create a csv table "stats_nextpyper.csv" summarizing the run.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
__version__ = "0.1"
|
|
39
|
+
|
|
40
|
+
# =======================================================================================
|
|
41
|
+
# IMPORTS
|
|
42
|
+
# =======================================================================================
|
|
43
|
+
|
|
44
|
+
from collections import Counter, defaultdict
|
|
45
|
+
from dataclasses import dataclass, field
|
|
46
|
+
from itertools import groupby
|
|
47
|
+
from functools import reduce
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
import json
|
|
50
|
+
import re
|
|
51
|
+
import sys
|
|
52
|
+
from typing import Literal
|
|
53
|
+
|
|
54
|
+
from Bio import SeqIO
|
|
55
|
+
from Bio.SeqRecord import SeqRecord
|
|
56
|
+
import polars as pl
|
|
57
|
+
import pandas as pd
|
|
58
|
+
import numpy as np
|
|
59
|
+
|
|
60
|
+
# =======================================================================================
|
|
61
|
+
# CONSTANTS
|
|
62
|
+
# =======================================================================================
|
|
63
|
+
|
|
64
|
+
MATCHING_PATTERN = r"(Input|Contaminants):\s+(\d+)"
|
|
65
|
+
CLEANING_PATTERN = r"(Input|Result):\s+(\d+)"
|
|
66
|
+
|
|
67
|
+
SCF_PATTERN = re.compile(
|
|
68
|
+
r"^(?P<sample>.*?)-(?P<probe>.*?)_(?P<cluster>.+?)_(?P<seed>\d+?)", re.VERBOSE
|
|
69
|
+
)
|
|
70
|
+
PROBE_EXT = re.compile(r"-(.*)(?=_EDGE)")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# =======================================================================================
|
|
74
|
+
# CLASSES
|
|
75
|
+
# =======================================================================================
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class AlnTable:
|
|
80
|
+
samples: list[str]
|
|
81
|
+
probe_lens: dict[str, int]
|
|
82
|
+
mat: pd.DataFrame = field(init=False, repr=False)
|
|
83
|
+
|
|
84
|
+
def __post_init__(self):
|
|
85
|
+
seq_lens = np.zeros((len(self.samples), len(self.probe_lens)))
|
|
86
|
+
self.mat = pd.DataFrame(
|
|
87
|
+
seq_lens, index=self.samples, columns=self.probe_lens, dtype=int
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def update_counts(self, counts: dict[str, int], probe: str) -> None:
|
|
91
|
+
|
|
92
|
+
if not counts:
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
if probe not in self.mat.columns:
|
|
96
|
+
raise ValueError(f"{probe=} not in probe set")
|
|
97
|
+
|
|
98
|
+
rows, vals = zip(*counts.items())
|
|
99
|
+
self.mat.loc[rows, probe] = vals
|
|
100
|
+
|
|
101
|
+
def make_normalized_table(self) -> pd.DataFrame:
|
|
102
|
+
return self.mat / (np.array(list(self.probe_lens.values())) * 3)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class AsmLoc:
|
|
107
|
+
stage: str
|
|
108
|
+
path: Path
|
|
109
|
+
struct: Literal["flat", "nested", "spreaded", "miniprot"] = "flat"
|
|
110
|
+
file_name: str | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
ASM_PATHS = {
|
|
114
|
+
"seeds": AsmLoc(
|
|
115
|
+
"seeds",
|
|
116
|
+
Path("1_assembly/12_filtering/122_filt_seeds/1221_filtered_scfs"),
|
|
117
|
+
"flat",
|
|
118
|
+
),
|
|
119
|
+
"assembly": AsmLoc(
|
|
120
|
+
"assembly", Path("2_saute/24_postprocessing/242_reheading"), "flat"
|
|
121
|
+
),
|
|
122
|
+
"alleles": AsmLoc(
|
|
123
|
+
"alleles", Path("3_homolog_prospection/30_allele_collapsing"), "flat"
|
|
124
|
+
),
|
|
125
|
+
"homologs": AsmLoc(
|
|
126
|
+
"homologs",
|
|
127
|
+
Path(
|
|
128
|
+
"3_homolog_prospection/31_homologs_filtering/312_filt_homologs/3121_sequences"
|
|
129
|
+
),
|
|
130
|
+
"flat",
|
|
131
|
+
),
|
|
132
|
+
"separation": AsmLoc(
|
|
133
|
+
"separation",
|
|
134
|
+
Path("3_homolog_prospection/32_region_separation/321_output/3211_scfs"),
|
|
135
|
+
"miniprot",
|
|
136
|
+
),
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# =======================================================================================
|
|
141
|
+
# FUNCTIONS
|
|
142
|
+
# =======================================================================================
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _get_raw_and_trimmed_reads(sample: str, rootdir: Path) -> int:
|
|
146
|
+
with (
|
|
147
|
+
rootdir / f"logs/0_preprocessing/01_trimming_fastp/{sample}.json"
|
|
148
|
+
).open() as file:
|
|
149
|
+
report = json.load(file)
|
|
150
|
+
raw_reads = report["summary"]["before_filtering"]["total_reads"]
|
|
151
|
+
trimmed_reads = report["summary"]["after_filtering"]["total_reads"]
|
|
152
|
+
return raw_reads, trimmed_reads
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# def _get_matched_reads(sample: str, rootdir: Path, pat: str) -> tuple[int, int]:
|
|
156
|
+
# """Extract from bbduk logs the number of input and output reads. Depending on the
|
|
157
|
+
# pattern, the output would be tha matching (contaminants) or non matching (clean reads).
|
|
158
|
+
# """
|
|
159
|
+
|
|
160
|
+
# read_ext = re.compile(pat)
|
|
161
|
+
# with (
|
|
162
|
+
# rootdir / f"logs/preprocessing/bbduk_probe_matching/{sample}.log"
|
|
163
|
+
# ).open() as file:
|
|
164
|
+
# return tuple(int(match[2]) for line in file if (match := read_ext.match(line)))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _get_len_probes(file: Path) -> int:
|
|
168
|
+
"Given a file with multiple versions of a probe, return the size of the longest."
|
|
169
|
+
|
|
170
|
+
return (
|
|
171
|
+
np.fromiter((len(rec) for rec in SeqIO.parse(file, "fasta")), dtype=int)
|
|
172
|
+
).max()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _get_seqs_lens(aln: Path, pat: re.Pattern) -> dict[str, int]:
|
|
176
|
+
"""Given a an alignment file with multiple sequences, group them by sample using
|
|
177
|
+
the provided pattern and take the longest for each sample. Return a dictionary
|
|
178
|
+
sample: length pairs."""
|
|
179
|
+
|
|
180
|
+
get_sample = lambda rec: pat.search(rec.id)["sample"]
|
|
181
|
+
return {
|
|
182
|
+
sample: max(map(len, recs))
|
|
183
|
+
for sample, recs in groupby(
|
|
184
|
+
sorted(SeqIO.parse(aln, "fasta"), key=get_sample), key=get_sample
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _condense_counts(mul_counts: list[dict[str, int]]) -> dict[str, int]:
|
|
190
|
+
"Given a list of dictionaries of sample:count with overlapping samples, returned a unified dictionary with the sum of the counts."
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
key: sum(counts.get(key, 0) for counts in mul_counts)
|
|
194
|
+
for key in reduce(set.union, mul_counts, set())
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def compute_Nx(lens: np.ndarray[np.int64], x: float) -> int:
|
|
199
|
+
"""Compute the length of the sequence that separates the assembly
|
|
200
|
+
between x and (1-x) parts."""
|
|
201
|
+
|
|
202
|
+
fraction = x / 100.0 if x > 1.0 else x
|
|
203
|
+
idx = np.where(lens.cumsum() >= lens.sum() * fraction)[0][0]
|
|
204
|
+
|
|
205
|
+
return int(lens[idx])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def contiguity_stats(
|
|
209
|
+
recs: list[SeqRecord] | list[int],
|
|
210
|
+
Nx: tuple[int] = (25, 50, 75, 90),
|
|
211
|
+
cutoffs: tuple[int] = (500, 750, 1000, 1500, 2000, 3000),
|
|
212
|
+
) -> dict[str, int]:
|
|
213
|
+
"Compute basic contiguity stats of a given assembly/ set of sequences"
|
|
214
|
+
|
|
215
|
+
match recs:
|
|
216
|
+
case list() if all(isinstance(x, SeqRecord) for x in recs):
|
|
217
|
+
lens = np.fromiter(map(len, recs), np.int64)
|
|
218
|
+
case list() if all(isinstance(x, int) for x in recs):
|
|
219
|
+
lens = np.array(recs, np.int64)
|
|
220
|
+
case _:
|
|
221
|
+
raise ValueError(
|
|
222
|
+
f"Expected a list of SeqRecord or a list of int, got {type(recs[0])} with {len(recs)} elements."
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
lens.sort()
|
|
226
|
+
stats = {
|
|
227
|
+
"num_seqs": lens.size,
|
|
228
|
+
"sum": int(lens.sum()),
|
|
229
|
+
"min": int(lens.min()),
|
|
230
|
+
"max": int(lens.max()),
|
|
231
|
+
"mean": round(float(lens.mean()), 2),
|
|
232
|
+
"median": int(np.median(lens)),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
# Add Nx stats.
|
|
236
|
+
stats |= {f"N{n}": compute_Nx(lens, n) for n in Nx}
|
|
237
|
+
|
|
238
|
+
# Add cutoff counts.
|
|
239
|
+
stats |= {f"n:{size}": np.where(lens >= size)[0].size for size in cutoffs}
|
|
240
|
+
|
|
241
|
+
return stats
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def get_probe(rec: SeqRecord, pat: re.Pattern) -> str:
|
|
245
|
+
"""Extract the probe identifier from a SeqRecord id."""
|
|
246
|
+
return pat.search(rec.id).group(1)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def summarize_workflow(results_dir: Path) -> pd.DataFrame:
|
|
250
|
+
"""Given the root path of a NextPyper output, collect and summarize the results of the run.
|
|
251
|
+
Returns a dataframe with a row per sample and multiple statistics.
|
|
252
|
+
|
|
253
|
+
Current columns include:
|
|
254
|
+
|
|
255
|
+
- raw_reads: Number of raw reads in the sample.
|
|
256
|
+
- trimmed_reads: Number of reads after trimming.
|
|
257
|
+
- cleaned_reads: Number of reads after cleaning (rRNA + [cpDNA]).
|
|
258
|
+
- probe_matching_reads: Number of reads after probe matching filtering.
|
|
259
|
+
- probes_in_assembly: Number of probes that had a hit in the assembly.
|
|
260
|
+
- probes_at_25pct: Number of probes in the final alignments that have at least 25% of the probe length.
|
|
261
|
+
- probes_at_50pct: Number of probes in the final alignments that have at least 50% of the probe length.
|
|
262
|
+
- probes_at_75pct: Number of probes in the final alignments that have at least 75% of the probe length.
|
|
263
|
+
- probes_at_100pct: Number of probes in the final alignments that have at least 100% of the probe length.
|
|
264
|
+
- probes_at_125pct: Number of probes in the final alignments that have at least 125% of the probe length.
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
## Get the samples processed
|
|
268
|
+
if results_dir.name != "workflow":
|
|
269
|
+
results_dir = results_dir / "workflow"
|
|
270
|
+
|
|
271
|
+
samples = sorted(
|
|
272
|
+
sample.name
|
|
273
|
+
for sample in (results_dir / "1_assembly/10_raw_assembly/100_spades").iterdir()
|
|
274
|
+
)
|
|
275
|
+
stats = pd.DataFrame(index=samples)
|
|
276
|
+
|
|
277
|
+
## Get the raw reads
|
|
278
|
+
trimmed_stats = {
|
|
279
|
+
sample: _get_raw_and_trimmed_reads(sample, results_dir.parent)
|
|
280
|
+
for sample in samples
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
stats["raw_reads"] = {sample: raw for sample, (raw, trim) in trimmed_stats.items()}
|
|
284
|
+
stats["trimmed_reads"] = {
|
|
285
|
+
sample: trim for sample, (raw, trim) in trimmed_stats.items()
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
## ToDo: revisit to extract probes from the assemblies
|
|
289
|
+
stage_stats = {
|
|
290
|
+
stage: summarize_assemblies(results_dir / loc.path, loc.struct, loc.file_name)
|
|
291
|
+
for stage, loc in ASM_PATHS.items()
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
for stage, sample_stats in stage_stats.items():
|
|
295
|
+
# if stage != "alleles":
|
|
296
|
+
stats[f"probes_in_{stage}"] = {
|
|
297
|
+
sample: sample_stats["probes"]
|
|
298
|
+
for sample, sample_stats in sample_stats.items()
|
|
299
|
+
}
|
|
300
|
+
for stage, sample_stats in stage_stats.items():
|
|
301
|
+
stats[f"median_seqs_per_probe_in_{stage}"] = {
|
|
302
|
+
sample: sample_stats["median_seqs_per_probe"]
|
|
303
|
+
for sample, sample_stats in sample_stats.items()
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
## ToDo: Rethink how to compute probe completeness
|
|
307
|
+
## Get probe lens in aa
|
|
308
|
+
final_probes_dir = results_dir / ASM_PATHS["separation"].path.parent / "probes"
|
|
309
|
+
probe_lens = {
|
|
310
|
+
file.stem: len(SeqIO.read(file, "fasta"))
|
|
311
|
+
for file in sorted((final_probes_dir).glob("*.fasta"))
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
## Make an auxiliary matrix of [Samples x probes]
|
|
315
|
+
# table = AlnTable(samples, probe_lens)
|
|
316
|
+
|
|
317
|
+
# for probe_dir in (
|
|
318
|
+
# results_dir / "homolog_prospection/region_separation/separation_output/scfs"
|
|
319
|
+
# ).iterdir():
|
|
320
|
+
# if probe_dir.is_file():
|
|
321
|
+
# continue
|
|
322
|
+
|
|
323
|
+
# if counts := _condense_counts(
|
|
324
|
+
# [_get_seqs_lens(aln, SCF_PATTERN) for aln in probe_dir.glob("*.fasta")]
|
|
325
|
+
# ):
|
|
326
|
+
# table.update_counts(counts, probe=probe_dir.name)
|
|
327
|
+
|
|
328
|
+
# norm_table = table.make_normalized_table()
|
|
329
|
+
|
|
330
|
+
# for level in (25, 50, 75, 100, 125):
|
|
331
|
+
# stats[f"probes_at_{level}pct"] = (norm_table > level / 100).sum(axis=1)
|
|
332
|
+
|
|
333
|
+
# return stats.reset_index().rename({"index": "samples"}, axis=1), norm_table
|
|
334
|
+
return stats.reset_index().rename({"index": "samples"}, axis=1)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def summarize_assemblies(
|
|
338
|
+
asm_dir: Path,
|
|
339
|
+
dir_struct: Literal["flat", "nested", "spreaded", "miniprot"] = "flat",
|
|
340
|
+
name: str | None = None,
|
|
341
|
+
):
|
|
342
|
+
"""Parse the samples (sequences) of the given assembly directory, compute
|
|
343
|
+
contiguity statistics and report them in a table in the specified path.
|
|
344
|
+
|
|
345
|
+
There are 3 directory structures supported, according to how the sequences
|
|
346
|
+
of each sample are structured in the assembly directory:
|
|
347
|
+
|
|
348
|
+
Flat:
|
|
349
|
+
asm_dir/
|
|
350
|
+
├── sample1.fasta
|
|
351
|
+
├── sample2.fasta
|
|
352
|
+
├── ...
|
|
353
|
+
├── ...
|
|
354
|
+
└── sampleN.fasta
|
|
355
|
+
|
|
356
|
+
Nested:
|
|
357
|
+
asm_dir/
|
|
358
|
+
├── sample1/
|
|
359
|
+
│ └── NAME.fasta
|
|
360
|
+
├── sample2/
|
|
361
|
+
│ └── NAME.fasta
|
|
362
|
+
├── ...
|
|
363
|
+
└── sampleN/
|
|
364
|
+
└── NAME.fasta
|
|
365
|
+
|
|
366
|
+
Spreaded:
|
|
367
|
+
asm_dir/
|
|
368
|
+
├── sample1/
|
|
369
|
+
│ ├── file1.fasta
|
|
370
|
+
│ ├── file2.fasta
|
|
371
|
+
│ ├── ...
|
|
372
|
+
│ └── fileN.fasta
|
|
373
|
+
├── sample2/
|
|
374
|
+
│ ├── file1.fasta
|
|
375
|
+
│ ├── file2.fasta
|
|
376
|
+
│ ├── ...
|
|
377
|
+
│ └── fileN.fasta
|
|
378
|
+
└── sampleN
|
|
379
|
+
├── file1.fasta
|
|
380
|
+
├── file2.fasta
|
|
381
|
+
├── ...
|
|
382
|
+
└── fileN.fasta
|
|
383
|
+
|
|
384
|
+
Miniprot:
|
|
385
|
+
asm_dir/
|
|
386
|
+
├── probe1/
|
|
387
|
+
│ ├── probe1_X_XX_exons.fasta
|
|
388
|
+
│ ├── probe1_X_XX_genotigs.fasta
|
|
389
|
+
│ ├── probe1_X_XX_supercontigs.fasta
|
|
390
|
+
│ ├── ...
|
|
391
|
+
│ ├── probe1_Y_YY_exons.fasta
|
|
392
|
+
│ ├── probe1_Y_YY_genotigs.fasta
|
|
393
|
+
│ └── probe1_Y_YY_supercontigs.fasta
|
|
394
|
+
├── probe2/
|
|
395
|
+
│ ├── probe2_X_XX_exons.fasta
|
|
396
|
+
│ ├── probe2_X_XX_genotigs.fasta
|
|
397
|
+
│ └── probe2_X_XX_supercontigs.fasta
|
|
398
|
+
└── probeN/
|
|
399
|
+
├── probeN_X_XX_exons.fasta
|
|
400
|
+
├── probeN_X_XX_genotigs.fasta
|
|
401
|
+
├── probeN_X_XX_supercontigs.fasta
|
|
402
|
+
├── ...
|
|
403
|
+
├── probeN_Y_YY_exons.fasta
|
|
404
|
+
├── probeN_Y_YY_genotigs.fasta
|
|
405
|
+
└── probeN_Y_YY_supercontigs.fasta
|
|
406
|
+
|
|
407
|
+
The default is to assume a flat directiry structure. If the dir_struct is
|
|
408
|
+
"nested" the common name of the file with the sequences is expected
|
|
409
|
+
as an argument. Name is ignored in any other scenario.
|
|
410
|
+
|
|
411
|
+
the miniprot s tructure is a special case where the sequences are organized
|
|
412
|
+
by probe rather than by sample. All supercontigs files are parsed and the sequences
|
|
413
|
+
are restructured per sample on the fly.
|
|
414
|
+
"""
|
|
415
|
+
|
|
416
|
+
# ${asm_dir}/assembled/filtering/filtered_scfs/H1_A1/*.fasta ## Spread
|
|
417
|
+
# ${asm_dir}/saute/target_assembly/H1_A1/fixed_vars.fasta ## nested
|
|
418
|
+
# ${asm_dir}/homolog_prospection/homologs_filtering/filtered_scfs/H1_A1.fasta ## flat
|
|
419
|
+
# ${asm_dir}/homolog_prospection/allele_collapsing/H1_A1.fasta ## flat
|
|
420
|
+
# ${asm_dir}/homolog_prospection/region_separation/separation_output/scfs ## miniprot
|
|
421
|
+
|
|
422
|
+
match dir_struct:
|
|
423
|
+
case "flat":
|
|
424
|
+
sample_recs = {
|
|
425
|
+
path.stem: list(SeqIO.parse(path, "fasta"))
|
|
426
|
+
for path in sorted(asm_dir.iterdir())
|
|
427
|
+
}
|
|
428
|
+
case "nested":
|
|
429
|
+
if name is None:
|
|
430
|
+
raise ValueError(
|
|
431
|
+
f"The name of the assembly has to be provided when {dir_struct=}"
|
|
432
|
+
)
|
|
433
|
+
sample_recs = {
|
|
434
|
+
path.parent.stem: list(SeqIO.parse(path, "fasta"))
|
|
435
|
+
for path in sorted(asm_dir.rglob(name))
|
|
436
|
+
}
|
|
437
|
+
case "spreaded":
|
|
438
|
+
sample_recs = {
|
|
439
|
+
sample_path.stem: [
|
|
440
|
+
rec
|
|
441
|
+
for file in sample_path.iterdir()
|
|
442
|
+
for rec in SeqIO.parse(file, "fasta")
|
|
443
|
+
]
|
|
444
|
+
for sample_path in sorted(asm_dir.iterdir())
|
|
445
|
+
}
|
|
446
|
+
case "miniprot":
|
|
447
|
+
sample_recs = defaultdict(list)
|
|
448
|
+
for file in sorted(asm_dir.rglob("*_supercontigs.fasta")):
|
|
449
|
+
for rec in SeqIO.parse(file, "fasta"):
|
|
450
|
+
sample = rec.id.split("|")[0]
|
|
451
|
+
sample_recs[sample].append(rec)
|
|
452
|
+
|
|
453
|
+
case _:
|
|
454
|
+
raise ValueError(
|
|
455
|
+
f"file {dir_struct=} not supported. Use option flat, saute, spreaded or miniprot."
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
# Compute contiguity stats for the assemblies and number of probes
|
|
459
|
+
sample_stats = {}
|
|
460
|
+
for sample, recs in sample_recs.items():
|
|
461
|
+
sample_stats[sample] = contiguity_stats(recs)
|
|
462
|
+
seq_per_probe = Counter(get_probe(rec, PROBE_EXT) for rec in recs)
|
|
463
|
+
sample_stats[sample]["probes"] = len(seq_per_probe)
|
|
464
|
+
sample_stats[sample]["median_seqs_per_probe"] = seq_per_probe.most_common(
|
|
465
|
+
len(seq_per_probe) // 2
|
|
466
|
+
)[-1][1]
|
|
467
|
+
|
|
468
|
+
return sample_stats
|
|
469
|
+
|
|
470
|
+
# with out_table.open("w") as out:
|
|
471
|
+
# header = f"sample{sep}{sep.join(next(iter(sample_stats.values())))}\n"
|
|
472
|
+
# out.write(header)
|
|
473
|
+
|
|
474
|
+
# for sample, stats in sample_stats.items():
|
|
475
|
+
# out.write(f"{sample}{sep}{sep.join(map(str, stats.values()))}\n")
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def snakemake_call(snakemake):
|
|
479
|
+
with open(snakemake.log[0], "w") as outlog:
|
|
480
|
+
sys.stdout = sys.stderr = outlog
|
|
481
|
+
|
|
482
|
+
wf_dir = Path(snakemake.input.workflowdir)
|
|
483
|
+
out_stats = Path(snakemake.output[0])
|
|
484
|
+
|
|
485
|
+
df, _ = summarize_workflow(wf_dir)
|
|
486
|
+
df.to_csv(out_stats, index=False)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def main():
|
|
490
|
+
results_dir = sys.argv[1]
|
|
491
|
+
out_file = sys.argv[2]
|
|
492
|
+
|
|
493
|
+
df, table = summarize_workflow(Path(results_dir))
|
|
494
|
+
df.to_csv(out_file, index=False)
|
|
495
|
+
|
|
496
|
+
try:
|
|
497
|
+
tab_file = sys.argv[3]
|
|
498
|
+
table.T.to_csv(tab_file, float_format="%.2f")
|
|
499
|
+
except IndexError:
|
|
500
|
+
pass
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
if __name__ == "__main__":
|
|
504
|
+
if "snakemake" in globals():
|
|
505
|
+
snakemake_call(snakemake)
|
|
506
|
+
else:
|
|
507
|
+
main()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# =======================================================================================
|
|
2
|
+
# CLASS
|
|
3
|
+
# =======================================================================================
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UnionFind:
|
|
7
|
+
"""Union-find data structure with path compression and Union-by-rank.
|
|
8
|
+
getComponents return a list of sets, each set instance represents
|
|
9
|
+
a component.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self):
|
|
13
|
+
"""Create a new empty union-find structure."""
|
|
14
|
+
self.weights = {}
|
|
15
|
+
self.parents = {}
|
|
16
|
+
self.components = {}
|
|
17
|
+
|
|
18
|
+
def __getitem__(self, object):
|
|
19
|
+
"""
|
|
20
|
+
Find and return the name of the set containing the object.
|
|
21
|
+
"""
|
|
22
|
+
# check for previously unknown object
|
|
23
|
+
if object not in self.parents:
|
|
24
|
+
self.parents[object] = object
|
|
25
|
+
self.weights[object] = 1
|
|
26
|
+
self.components[object] = [object]
|
|
27
|
+
return object
|
|
28
|
+
|
|
29
|
+
# find path of objects leading to the root
|
|
30
|
+
path = [object]
|
|
31
|
+
root = self.parents[object]
|
|
32
|
+
while root != path[-1]:
|
|
33
|
+
path.append(root)
|
|
34
|
+
root = self.parents[root]
|
|
35
|
+
for ancestor in path:
|
|
36
|
+
self.parents[ancestor] = root
|
|
37
|
+
if ancestor != root:
|
|
38
|
+
self.components[root].append(ancestor)
|
|
39
|
+
try:
|
|
40
|
+
del self.components[ancestor]
|
|
41
|
+
except:
|
|
42
|
+
continue
|
|
43
|
+
return root
|
|
44
|
+
|
|
45
|
+
def union(self, objects):
|
|
46
|
+
"""
|
|
47
|
+
Find the sets containing the objects and merge them all.
|
|
48
|
+
"""
|
|
49
|
+
roots = [self[x] for x in objects] # uses__getitem__
|
|
50
|
+
heaviest = max([(self.weights[r], r) for r in roots])[1]
|
|
51
|
+
for r in roots:
|
|
52
|
+
if r != heaviest:
|
|
53
|
+
self.weights[heaviest] += self.weights[r]
|
|
54
|
+
self.parents[r] = heaviest
|
|
55
|
+
self.components[heaviest].extend(self.components[r])
|
|
56
|
+
del self.components[r]
|
|
57
|
+
|
|
58
|
+
def get_components(self):
|
|
59
|
+
return [set(x) for x in self.components.values()]
|
|
60
|
+
|
|
61
|
+
def __enter__(self):
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
65
|
+
pass
|