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,493 @@
1
+ # Copyright (C) 2024
2
+ # Simón Villanueva CORRALES: simon.corrales@ibot.cas.cz
3
+ # Yann J.K. BERTRAND: yjk_bertrand@ybertrand.org
4
+ #
5
+ # All rights reserved.
6
+
7
+ """
8
+ Functions and classes used to run orfipy and assemble the putative exons into the longest translated peptide.
9
+ For each probe, the longest path obtained by combining the possible orfs is calculated.
10
+ Stop codons ('*') are removed from the sequences and the orfs are combined.
11
+ AA sequences are saved in fasta format.
12
+ Three parameters are use
13
+ -sensitivity: between 0 and 1, is the proportion of the nucleotide sequence that gets translated to be deemed sufficient.
14
+ -stop_per_1Kbp: proportion of stop codons within exons that are most likely sequencing errors
15
+ -min_exon_length: minimum number of AA in an exon
16
+ # Usage example:
17
+ find_cds(Path("../data/probe.fasta"), Path("../data/longest_cds.fasta"), sensitivity, stop_per_1Kbp, min_exon_length)
18
+ """
19
+
20
+ __version__ = "0.1"
21
+
22
+ # =======================================================================================
23
+ # IMPORTS
24
+ # =======================================================================================
25
+ from collections import defaultdict, namedtuple
26
+ from dataclasses import dataclass, field, fields
27
+ import re
28
+ import sys
29
+ from typing import Final, Optional, Self, TypedDict, Literal, Any
30
+ from pathlib import Path
31
+
32
+ from Bio import SeqIO
33
+ from Bio.SeqRecord import SeqRecord
34
+ from Bio.Seq import Seq
35
+
36
+ import orfipy_core
37
+
38
+ pattern = re.compile(
39
+ r"""^ID=Seq_ORF\.(?P<name>\d+?);ORF_type=(?P<type>.*?);ORF_len=(?P<length>\d+?);ORF_frame=(?P<frame>.*?);Start.*$""",
40
+ re.VERBOSE,
41
+ )
42
+
43
+ # Named tuple that keeps the nodes in a path either as their suffixes or their cds and the sum of their length.
44
+ GraphPath = namedtuple("GraphPath", ["path", "length"])
45
+
46
+ # =======================================================================================
47
+ # EXCEPTIOMS
48
+ # =======================================================================================
49
+
50
+ # =======================================================================================
51
+ # FUNCTIONS
52
+ # =======================================================================================
53
+
54
+
55
+ def select_best_cds(
56
+ orf_list: list["Orf"], seq_length: int, max_stops: int, sensitivity: float
57
+ ) -> GraphPath:
58
+ """
59
+ Create an interval graph for '+' and '-' list of orf. Explore all possible paths and determine the best path.
60
+ Return the longest path that can be translated.
61
+ Parameters
62
+ ----------
63
+ orf_list: list of Orf objects.
64
+ seq_length: length in nucleotides of the original record.
65
+ max_stops: maximum number of stops allowed on path.
66
+ sensitivity: proportion of the nucleotide sequence that gets translated to be deemed sufficient.
67
+ """
68
+ partial_plus = []
69
+ partial_minus = []
70
+ for orf in orf_list:
71
+ if orf.strand == "+":
72
+ partial_plus.append(orf)
73
+ else:
74
+ partial_minus.append(orf)
75
+ optima = None
76
+ best_length = 0
77
+ # perform the path search on each strand separately
78
+ if partial_plus:
79
+ sorted_partial_plus = sorted(partial_plus, key=lambda o: o.start)
80
+ iter_graph_plus = IntervalGraph(
81
+ sorted_partial_plus, seq_length, max_stops, sensitivity
82
+ )
83
+ optima = iter_graph_plus.get_best_path()
84
+ if optima:
85
+ best_length = optima.length
86
+ if partial_minus:
87
+ sorted_partial_minus = sorted(partial_minus, key=lambda o: o.start)
88
+ # use the best length from the '+' strand
89
+ iter_graph_minus = IntervalGraph(
90
+ sorted_partial_minus, seq_length, max_stops, sensitivity, best_length
91
+ )
92
+ if (optimum := iter_graph_minus.get_best_path()) is not None:
93
+ optima = optimum
94
+ return optima
95
+
96
+
97
+ def find_cds(
98
+ input_fasta: Path,
99
+ output_fasta: Path,
100
+ sensitivity: float = 0.95,
101
+ stop_per_1Kbp: float = 2.0,
102
+ min_exon_length: int = 20,
103
+ ) -> None:
104
+ """
105
+ Controle function to run orfipy and use the identified orf to find the longest translated region.
106
+ Parameters
107
+ ----------
108
+ input_fasta
109
+ output_fasta
110
+ sensitivity: proportion of the nucleotide sequence that gets translated to be deemed sufficient, between 0 and 1.
111
+ stop_per_1Kbp: stops found within exons that are most likely sequencing errors.
112
+ min_exon_length: discard the smallest exons.
113
+
114
+ """
115
+ assert input_fasta.exists(), f"{input_fasta} does not exist"
116
+ Path(output_fasta.parent).mkdir(parents=True, exist_ok=True)
117
+ new_records = []
118
+ records = SeqIO.parse(input_fasta, "fasta")
119
+ for record in records:
120
+ print(f"working on record {record.id}")
121
+ if (
122
+ translated_record := AllOrfs(
123
+ record, sensitivity, stop_per_1Kbp, min_exon_length
124
+ ).get_best_pep()
125
+ ) is not None:
126
+ new_records.append(translated_record)
127
+ trans_fraction = 100 * (len(translated_record.seq) * 3) / len(record.seq)
128
+ print(
129
+ f"orfipy translated {int(trans_fraction)} percent of the original sequence"
130
+ )
131
+ else:
132
+ print("no translation occurred.")
133
+ # break
134
+ if new_records:
135
+ SeqIO.write(new_records, output_fasta, "fasta")
136
+
137
+
138
+ # =======================================================================================
139
+ # CLASSES
140
+ # =======================================================================================
141
+
142
+
143
+ @dataclass
144
+ class Orf:
145
+ """
146
+ Data structure used to store relevant data from a orfipy record.
147
+ Attributes
148
+ ----------
149
+ -name: orfipy ID.
150
+ -strand:
151
+ -type: Currently not relevant.
152
+ -start: start index on the nucleotide sequence (it would be the end on a rev-translated sequence).
153
+ -end: end index on the nucleotide sequence (it would be the start on a rev-translated sequence).
154
+ """
155
+
156
+ name: str
157
+ strand: Literal["+", "-"]
158
+ type: Literal["complete", "3-prime-partial"]
159
+ start: int
160
+ end: int
161
+ length: int
162
+ frame: Literal[-1, -2, -3, 1, 2, 3]
163
+
164
+ def invert_coordinates(self):
165
+ """For reversed complemented sequences the start and end coordinates are reversed for better sorting"""
166
+ left = self.start
167
+ right = self.end
168
+ self.start = right
169
+ self.end = left
170
+
171
+ def get_strand(self):
172
+ return self.strand
173
+
174
+ def get_length(self):
175
+ return self.length
176
+
177
+ def get_start(self):
178
+ return self.start
179
+
180
+ def get_end(self):
181
+ return self.end
182
+
183
+ def overlap(self, other: "Orf") -> bool:
184
+ if self.get_end() > other.get_start():
185
+ return True
186
+ return False
187
+
188
+
189
+ @dataclass
190
+ class Node:
191
+ name: str
192
+ orf: Orf = field(repr=False)
193
+ children: list[str] = field(init=False, default_factory=list)
194
+
195
+ def overlap(self, other: "Node") -> bool:
196
+ if self.orf.overlap(other.orf):
197
+ return True
198
+ return False
199
+
200
+ def add_child(self, child: str) -> Self:
201
+ self.children.append(child)
202
+ return self
203
+
204
+ def not_root(self) -> Self:
205
+ self.root = False
206
+ return self
207
+
208
+ def has_children(self) -> bool:
209
+ if self.children:
210
+ return True
211
+ return False
212
+
213
+ def get_length(self) -> int:
214
+ return self.orf.get_length()
215
+
216
+ def get_children(self) -> list[str]:
217
+ return self.children
218
+
219
+ def get_orf(self) -> Orf:
220
+ return self.orf
221
+
222
+
223
+ @dataclass
224
+ class IntervalGraph:
225
+ """
226
+ Data structure that create a graph of non overlapping intervals (nodes).
227
+ Intervals are ordered by starting position. Starting with each target interval, we iterate over the rest
228
+ of the intervals that start at greater position. For each interval, if it doesn't overlap with the target
229
+ we draw an edge, otherwise we skip the interval. Once the graph is constructed, we iterarate over all nodes starting
230
+ from the most 5' nodes. Finding the longest path of non-overlapping intervals uses a DSF from each starting node.
231
+ Attributes
232
+ ----------
233
+ -orf_list: a list of Orf objects.
234
+ -seq_length: length in nucleotides of the whole sequence.
235
+ -sensitivity: proportion of the nucleotide sequence that gets translated to be deemed sufficient.
236
+ -best_path_length: length of the best path found so far.
237
+
238
+ Post Init
239
+ -nodes: list of Node objects ordered by starting position.
240
+ -node_dict: orf name as key and node as value.
241
+ -best_graph_path: best path found so far.
242
+ """
243
+
244
+ orf_list: list["Orf"]
245
+ seq_length: int
246
+ max_stops: int
247
+ sensitivity: float = field(default=0.95)
248
+ best_path_length: int = field(default=0)
249
+ nodes: list[Node] = field(init=False, default_factory=list)
250
+ node_dict: dict[str, Node] = field(init=False, default_factory=dict)
251
+ best_graph_path: GraphPath = field(init=False, default=None)
252
+
253
+ def __post_init__(self):
254
+ self._create_nodes()
255
+ self._create_edges()
256
+ self._explore_graph()
257
+
258
+ def _create_nodes(self) -> Self:
259
+ """
260
+ Populate the nodes attribute.
261
+ """
262
+ sorted_orfs = sorted(self.orf_list, key=lambda x: x.start)
263
+ for orf in sorted_orfs:
264
+ node = Node(orf.name, orf)
265
+ self.nodes.append(node)
266
+ return self
267
+
268
+ def _create_edges(self) -> Self:
269
+ """Connect the node to all other nodes whose orf is left of the current node orf and whose sequences
270
+ do not overlap"""
271
+ self.node_dict = {node.name: node for node in self.nodes}
272
+ for idx, node in enumerate(self.nodes):
273
+ for other_node in self.nodes[idx + 1 :]:
274
+ if node.overlap(other_node):
275
+ continue
276
+ node.add_child(other_node.name)
277
+ return self
278
+
279
+ def _explore_graph(self) -> Self:
280
+ """
281
+ Find all paths between root nodes (starting node in the path) and leaf nodes (nodes without children).
282
+ Populate best_graph_path, modify the best_path_length attribute.
283
+ """
284
+
285
+ def dfs_util(
286
+ current_name: str,
287
+ current_path=None,
288
+ current_length: int = 0,
289
+ number_stops=0,
290
+ ) -> GraphPath:
291
+ if current_path is None:
292
+ current_path = []
293
+ current_node = self.node_dict[current_name]
294
+ current_end = current_node.orf.get_end()
295
+ current_path_copy = current_path.copy()
296
+ current_number_stop = number_stops
297
+ current_path_copy.append(current_name)
298
+ current_length += current_node.get_length()
299
+
300
+ # case there is not enough distance from the current index to the end of the sequence
301
+ # to discover a better path than the best current one
302
+ if self.seq_length + current_length - current_end < self.best_path_length:
303
+ return
304
+
305
+ # case node is a leaf
306
+ if not current_node.has_children():
307
+ if current_length > self.best_path_length:
308
+ self.best_path_length = current_length
309
+ self.best_graph_path = GraphPath(
310
+ current_path_copy,
311
+ current_length,
312
+ )
313
+ return
314
+ else:
315
+ for child in current_node.get_children():
316
+ child_node = self.node_dict[child]
317
+ child_start = child_node.orf.get_start()
318
+ child_frame = child_node.orf.frame
319
+ # counting number of stops that separate adjacent exons.
320
+ if child_start - current_end <= 3:
321
+ current_number_stop += 1
322
+ if current_number_stop == self.max_stops:
323
+ if current_length > self.best_path_length:
324
+ self.best_path_length = current_length
325
+ self.best_graph_path = GraphPath(
326
+ current_path_copy,
327
+ current_length,
328
+ )
329
+ return
330
+ dfs_util(
331
+ child, current_path_copy, current_length, current_number_stop
332
+ )
333
+
334
+ # check all nodes in the list, starting from 5' end
335
+ for root_name in (x.name for x in self.nodes):
336
+ root_node = self.node_dict[root_name]
337
+ root_start = root_node.orf.get_start()
338
+ # case there is not enough distance from the current index to the end of the sequence
339
+ # to discover a better path than the best current one
340
+ if self.seq_length - root_start < self.best_path_length:
341
+ continue
342
+ # case the path is good enough
343
+ if self.best_path_length >= self.seq_length * self.sensitivity:
344
+ break
345
+ dfs_util(root_name)
346
+ return self
347
+
348
+ def get_best_path(self) -> Optional[GraphPath]:
349
+ if not self.best_graph_path:
350
+ return
351
+ return self.best_graph_path
352
+
353
+
354
+ @dataclass
355
+ class AllOrfs:
356
+ """
357
+ Infer all possible orfs in both strands with orfipy.
358
+ Select the longest orf or a path made out of orfs that provides the best translation.
359
+ Attributes
360
+ ----------
361
+ -seq: Seq object from biopython.
362
+ -sensitivity: proportion of the nucleotide sequence that gets translated to be deemed sufficient.
363
+ -stop_per_1Kbp: stops found within exons that are most likely sequencing errors
364
+ -min_exon_length: number of amino acids
365
+ Post Init
366
+ -candidates: keys are Orf numbers, value are Orf recovered with orfipy
367
+ -best_path: best path found overall.
368
+ """
369
+
370
+ record: SeqRecord
371
+ sensitivity: float = 0.99
372
+ stop_per_1Kbp: float = 2.0
373
+ min_exon_length: int = 20 # number of amino acids
374
+ candidates: dict[str, Orf] = field(
375
+ init=False,
376
+ default_factory=dict,
377
+ )
378
+ best_path: GraphPath = field(init=False, default=None) # name of orf(s)
379
+
380
+ def __post_init__(self):
381
+ if 0 < self.sensitivity <= 1:
382
+ self.sensitivity = 0.95
383
+ self._find_orfs()
384
+ self._select_best()
385
+
386
+ def _find_orfs(self):
387
+ for start, stop, strand, description in orfipy_core.orfs(
388
+ str(self.record.seq).upper(),
389
+ strand="b",
390
+ minlen=3,
391
+ maxlen=20000,
392
+ include_stop=False,
393
+ partial3=True,
394
+ partial5=True,
395
+ between_stops=True,
396
+ starts=["ATG"],
397
+ ):
398
+ match = pattern.match(description)
399
+ name = match.group("name")
400
+ length = int(match.group("length"))
401
+ if length < self.min_exon_length * 3:
402
+ continue
403
+ frame_match = match.group("frame")
404
+ frame = int(frame_match) if strand == "+" else -int(frame_match[1:])
405
+ type_match = match.group("type")
406
+ self.candidates[name] = Orf(
407
+ name=name,
408
+ strand=strand,
409
+ type=type_match,
410
+ start=start,
411
+ end=stop,
412
+ length=length,
413
+ frame=frame,
414
+ )
415
+
416
+ def _select_best(self):
417
+ length = len(self.record.seq)
418
+ if not self.candidates:
419
+ return
420
+ sorted_orfs = sorted(
421
+ self.candidates.values(), key=lambda o: o.length, reverse=True
422
+ )
423
+ if sorted_orfs[0].length >= length * self.sensitivity:
424
+ best_orf_name = sorted_orfs[0].name
425
+ best_orf_length = sorted_orfs[0].length
426
+ self.best_path = GraphPath([best_orf_name], best_orf_length)
427
+ return
428
+ max_stop = int((length / 1000) * self.stop_per_1Kbp)
429
+ self.best_path = select_best_cds(
430
+ list(self.candidates.values()), length, max_stop, self.sensitivity
431
+ )
432
+
433
+ def get_best_pep(self) -> Optional[SeqRecord]:
434
+ if not self.best_path:
435
+ return
436
+ new_sequence = []
437
+ best_path = self.best_path.path
438
+ strand = self.candidates[best_path[0]].strand
439
+ if strand == "+":
440
+ for orf_name in best_path:
441
+ orf = self.candidates[orf_name]
442
+ new_sequence.append(
443
+ str(self.record.seq[orf.start : orf.end].translate())
444
+ )
445
+ else:
446
+ best_path.reverse()
447
+ for orf_name in best_path:
448
+ orf = self.candidates[orf_name]
449
+ new_sequence.append(
450
+ str(
451
+ self.record.seq[orf.start : orf.end]
452
+ .reverse_complement()
453
+ .translate()
454
+ )
455
+ )
456
+ pep_seq = "".join(new_sequence).replace("X", "")
457
+ return SeqRecord(
458
+ Seq(pep_seq),
459
+ id=self.record.id,
460
+ description=self.record.description,
461
+ name=self.record.name,
462
+ )
463
+
464
+
465
+ def snakemake_call(snakemake) -> None:
466
+ with open(snakemake.log[0], "w") as outlog:
467
+ sys.stdout = sys.stderr = outlog
468
+
469
+ probes = Path(snakemake.input[0])
470
+ translated_probes = Path(snakemake.output[0])
471
+
472
+ translated_prop = snakemake.params.translated_prop
473
+ stop_per_1Kbp = snakemake.params.stop_per_1Kbp
474
+ min_exon_length = snakemake.params.min_exon_length
475
+
476
+ find_cds(
477
+ probes, translated_probes, translated_prop, stop_per_1Kbp, min_exon_length
478
+ )
479
+
480
+
481
+ if __name__ == "__main__":
482
+ if "snakemake" in globals():
483
+ snakemake_call(snakemake)
484
+ else:
485
+ # probes_fasta = Path("/home/yjkbertrand/Documents/projects/nextpiper/debug/batrachium_prones/targets.fasta")
486
+ probes_fasta = Path(
487
+ "/home/yjkbertrand/Documents/projects/nextpiper/debug/brassica_probes/kasper_mega_probes.fasta"
488
+ )
489
+ # output_fasta = Path("/home/yjkbertrand/Documents/projects/nextpiper/debug/batrachium_prones/test_translation.fasta")
490
+ output_fasta = Path(
491
+ "/home/yjkbertrand/Documents/projects/nextpiper/debug/brassica_probes/test_translation.fasta"
492
+ )
493
+ find_cds(probes_fasta, output_fasta)
@@ -0,0 +1,63 @@
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
+ __version__ = "0.1"
12
+
13
+ # =======================================================================================
14
+ # IMPORTS
15
+ # =======================================================================================
16
+
17
+ from pathlib import Path
18
+ import os
19
+
20
+ # =============================================================================
21
+ # FUNCTIONS
22
+ # =============================================================================
23
+
24
+ COLS = ["sample", "path_forward", "path_reverse", "ploidy"]
25
+
26
+
27
+ # =============================================================================
28
+ # FUNCTIONS
29
+ # =============================================================================
30
+
31
+
32
+ def make_table(data_dir: Path, out_table: Path, sep: str = "\t") -> None:
33
+ """Parse the directory with paired-end reads data and write a sample table
34
+ specifying paths for each sample. The sample name is inferred from the common
35
+ prefix of each pair of reads.
36
+
37
+ The output table has 3 columns: sample_name, path_forward_reads, path_reverse_reads.
38
+ If extra is given, a fourth column will be included for all the samples with extra.
39
+ """
40
+
41
+ with out_table.open("w") as table:
42
+ files = sorted(data_dir.iterdir())
43
+
44
+ if len(files) % 2 != 0:
45
+ raise ValueError(
46
+ f"There is an odd number of files in {data_dir}. All samples must have forward and reverse files."
47
+ )
48
+
49
+ # Add the header to the table
50
+ table.write(f"{sep.join(COLS)}\n")
51
+
52
+ for file1, file2 in zip(files[::2], files[1::2]):
53
+ # Get sample name
54
+ sample = os.path.commonprefix([file1.name, file2.name])
55
+
56
+ ## Do name processing magic
57
+ if sample.endswith("R"):
58
+ sample = sample.removesuffix("R")
59
+ sample = sample.rstrip("._-")
60
+ sample = sample.replace("-", "_")
61
+
62
+ row = f"{sample}{sep}{file1.resolve()}{sep}{file2.resolve()}{sep}0\n"
63
+ table.write(row)