This makes sense to me - except, do you really need the multiple_iterators = True here, then?
From pysam documentation for fetch():
multiple_iterators(bool) – Ifmultiple_iteratorsisTrue, multiple iterators on the same file can be used at the same time. The iterator returned will receive its own copy of a filehandle to the file effectively re-opening the file. Re-opening a file creates some overhead, so beware.
It is my understanding that in the code above, you moved opening of the file (bam = pysam.AlignmentFile(BAM, 'rb')) and creating a separate filehandle to each separate thread. Therefore do you need to also include multiple_iterators = True? That sounds like doing the same thing twice.
I am asking because I'd like to use something very similar, but the countReads() function would look something like this instead:
def countReads(regions, chrom, BAM):
count = 0
bam = pysam.AlignmentFile(BAM, 'rb')
for start, stop in regions:
Itr = bam.fetch(str(chrom), start, stop, multiple_iterators = True)
for Aln in Itr:
count += 1
Including multiple_iterators = True here would reopen the file for every region of the chromosome, which would make this a much slower process.
EDIT: I believe that this issue thread on pysam's Git repo confirms the claim above: multiple_iterators = True is only needed when using multiple iterators in the same process; when opening a separate file handle in each process, multiple_iterators = True should not be necessary.