I see that my answer was accepted - thanks! However, there are critical assumptions that I make with my one-line awk command above.
Here is a much more robust version that does the following:
- Sorts the BED file
- Splits individual regions greater than 1 megabase into multiple regions
- Breaks up the BED file into multiple BED files, each containing regions totalling 1 megabase or less in length
.
sort -k 1,1 -k2,2n MyBed.bed |
awk '{if ((($3-$2)+1)>1000000) {numintervals=int((((($3-$2)+1)/1000000)+1)); for (i=1; i<=numintervals; ++i) if (i==1) {print $1"\t"$2"\t"($2+999999)} else if (i==numintervals) {print $1"\t"$2+((999999+1)*(i-1))"\t"$3} else {print $1"\t"$2+((999999+1)*(i-1))"\t"($2+((999999+1)*(i-1)))+999999}} else {print}}' |
awk 'BEGIN {chr="chr1"; count=1; file=chr"Block"count".bed"; previouspos=$3} {sum+=(($3-$2)+1); if (sum<1000000 && $1==chr && (($3-previouspos)+1)<1000000) {print >> file}; if (sum>=1000000 || $1!=chr || (($3-previouspos)+1)>=1000000) {chr=$1; count+=1; file=chr"Block"count".bed"; print >> file; sum=(($3-$2)+1)} previouspos=$3} {if ($1!=chr) count=1}'
In python script, you are opening file multiple times until while loop ends. Put the open file statement above second while loop. It will increase a speed. Also, the input file is 24 GB, it will take some time.
To increase your speed, try to reduce while loops or use parallel approach.