Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve cigarstring performance #1295

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions pysam/libcalignedsegment.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ from pysam.libcutils cimport force_bytes, force_str, \
charptr_to_str, charptr_to_bytes
from pysam.libcutils cimport qualities_to_qualitystring, qualitystring_to_array, \
array_to_qualitystring
from libc.stdio cimport snprintf

# Constants for binary tag conversion
cdef char * htslib_types = 'cCsSiIf'
Expand Down Expand Up @@ -1279,13 +1280,41 @@ cdef class AlignedSegment:
empty string.
'''
def __get__(self):
c = self.cigartuples
if c is None:
cdef uint32_t *cigar_p
cdef bam1_t *src
cdef uint32_t op, l
cdef int k
cdef int ret
cdef int pos = 0
cdef int size = 16
cdef char buf[16]
cdef char *s = buf

src = self._delegate
if pysam_get_n_cigar(src) == 0:
return None
# reverse order
else:
return "".join([ "%i%c" % (y,CODE2CIGAR[x]) for x,y in c])

cigar_p = pysam_bam_get_cigar(src)
while True:
for k from 0 <= k < pysam_get_n_cigar(src):
op = cigar_p[k] & BAM_CIGAR_MASK
l = cigar_p[k] >> BAM_CIGAR_SHIFT
ret = snprintf(s + pos, size - pos, "%u%c", l, CODE2CIGAR[op])
if ret >= size - pos:
pos = 0
size = size * 2
if s != buf:
free(s)
s = <char *>malloc(size)
break
pos += ret
else:
break
try:
return s[:pos].decode("utf8")
finally:
if s != buf:
free(s)
def __set__(self, cigar):
if cigar is None or len(cigar) == 0:
self.cigartuples = []
Expand Down
10 changes: 10 additions & 0 deletions tests/AlignedSegment_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,16 @@ def testStats(self):
expected[1][i] = 1
self.assertEqual([list(x) for x in a.get_cigar_stats()], expected)

for i in range(1, 100):
cigarstring = "".join("10{}".format(x)
for x in iter("MIDNSHP=X")) * i
a.cigarstring = cigarstring
self.assertEqual(a.cigarstring, cigarstring)
expected = [[i * 10 for j in range(len("MIDNSHP=X"))] + [0, 0],
[i for j in range(len("MIDNSHP=X"))] + [0, 0]]
obtained = [list(x) for x in a.get_cigar_stats()]
self.assertEqual(obtained, expected)

a.cigarstring = "10M"
a.set_tag("NM", 5)
self.assertEqual(
Expand Down