| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
import sys |
| 4 |
|
| 5 |
if len(sys.argv) < 3: |
| 6 |
print("usage: <bamtools_coverage_output {} fasta_index num_regions >regions.bed".format(sys.argv[0])) |
| 7 |
print("Generates regions with even sequencing coverage, provided an input of coverage per-position as") |
| 8 |
print("generated by bamtools coverage. In other words, generates regions such that the integral of") |
| 9 |
print("coverage is approximately equal for each. These can be used when variant calling to reduce") |
| 10 |
print("variance in job runtime.") |
| 11 |
exit(1) |
| 12 |
|
| 13 |
lengths = {} |
| 14 |
fai = open(sys.argv[1]) |
| 15 |
for line in fai.readlines(): |
| 16 |
c, l = line.split("\t")[:2] |
| 17 |
lengths[c] = int(l) |
| 18 |
|
| 19 |
positions = [] |
| 20 |
total_coverage = 0 |
| 21 |
for line in sys.stdin: |
| 22 |
chrom, pos, depth = line.strip().split("\t") |
| 23 |
pos = int(pos) |
| 24 |
depth = int(depth) |
| 25 |
positions.append([chrom, pos, depth]) |
| 26 |
total_coverage += depth |
| 27 |
|
| 28 |
bp_per_region = total_coverage / int(sys.argv[2]) |
| 29 |
|
| 30 |
lchrom = None |
| 31 |
lpos = 0 |
| 32 |
bp_in_region = 0 |
| 33 |
|
| 34 |
for line in positions: |
| 35 |
chrom, pos, depth = line #line.strip().split("\t") |
| 36 |
if lchrom != chrom: |
| 37 |
if lchrom: |
| 38 |
print(lchrom+":"+str(lpos)+"-"+str(lengths[lchrom])) |
| 39 |
lpos = 0 |
| 40 |
lchrom = chrom |
| 41 |
bp_in_region = 0 |
| 42 |
else: |
| 43 |
lchrom = chrom |
| 44 |
bp_in_region += depth |
| 45 |
if bp_in_region > bp_per_region: |
| 46 |
print(chrom+":"+str(lpos)+"-"+str(pos)) #, pos - lpos |
| 47 |
lpos = pos |
| 48 |
bp_in_region = 0 |
| 49 |
|
| 50 |
print(lchrom+":"+str(lpos)+"-"+str(lengths[lchrom])) |