Debian Codegraph @

scripts/fasta_generate_regions.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 from math import ceil
5
6
7 def generate_regions(fasta_index_file, size, chunks=False, chromosomes=None, bed_files=None):
8
9 if not fasta_index_file.endswith(".fai"):
10 fasta_index_file = fasta_index_file + ".fai"
11
12 with open(fasta_index_file, "r") as fasta_index:
13 for line in fasta_index:
14 fields = line.strip().split("\t")
15 chrom_name = fields[0]
16 chrom_length = int(fields[1])
17 if chromosomes is not None and chrom_name not in chromosomes:
18 continue
19 region_start = 0
20 if chunks is True:
21 region_size = ceil(chrom_length / size) # have to make sure this works
22 else:
23 region_size = size
24 while region_start < chrom_length:
25 region_end = region_start + region_size
26 if region_end > chrom_length:
27 region_end = chrom_length
28 start = str(region_start)
29 end = str(region_end)
30 if bed_files is not None:
31 region = str(ceil(region_end / region_size))
32 file_path = f"{bed_files}.{chrom_name}.region.{region}.bed"
33 with open(file_path, "w") as f:
34 f.write("\t".join([chrom_name, start, end]))
35 else:
36 print(f"{chrom_name}:{start}-{end}")
37 region_start = region_end
38
39
40 if __name__ == "__main__":
41
42 parser = argparse.ArgumentParser(description="Generates a list of freebayes/bamtools region specifiers. Intended "
43 "for parallelization or creating cluster jobs.")
44
45 parser.add_argument("--chunks", action="store_true",
46 help="Split the fasta into N chunks rather than into N length pieces")
47 parser.add_argument("--chromosomes", nargs="+", default=None,
48 help="List of chromosomes to create chunks for")
49 parser.add_argument("--bed", metavar="base name", type=str,
50 help="Write chunks to individual bed files (for Snakemake) instead of stdout.")
51 parser.add_argument("fai", metavar="<fasta or fai file>",
52 help="The fasta file to split. Must be indexed.")
53 parser.add_argument("region_size", metavar="<N>", type=int,
54 help="Region size")
55
56 args = parser.parse_args()
57 generate_regions(args.fai, args.region_size, chunks=args.chunks, chromosomes=args.chromosomes, bed_files=args.bed)