1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
|
from cpython cimport PyBytes_FromStringAndSize
from libc.stdio cimport printf, feof, fgets
from libc.string cimport strcpy, strlen, memcmp, memcpy, memchr, strstr, strchr
from libc.stdlib cimport free, malloc, calloc, realloc
from libc.stdlib cimport atoi, atol, atof
from pysam.libcutils cimport force_bytes, force_str, charptr_to_str
from pysam.libcutils cimport encode_filename, from_string_and_size
import collections
cdef char *StrOrEmpty(char * buffer):
if buffer == NULL:
return ""
else: return buffer
cdef int isNew(char * p, char * buffer, size_t nbytes):
"""return True if `p` is located within `buffer` of size
`nbytes`
"""
if p == NULL:
return 0
return not (buffer <= p < buffer + nbytes)
cdef class TupleProxy:
'''Proxy class for access to parsed row as a tuple.
This class represents a table row for fast read-access.
Access to individual fields is via the [] operator.
Only read-only access is implemented.
'''
def __cinit__(self, encoding="ascii"):
self.data = NULL
self.fields = NULL
self.index = 0
self.nbytes = 0
self.is_modified = 0
self.nfields = 0
# start counting at field offset
self.offset = 0
self.encoding = encoding
def __dealloc__(self):
cdef int x
if self.is_modified:
for x from 0 <= x < self.nfields:
if isNew(self.fields[x], self.data, self.nbytes):
free(self.fields[x])
self.fields[x] = NULL
if self.data != NULL:
free(self.data)
if self.fields != NULL:
free(self.fields)
def __copy__(self):
if self.is_modified:
raise NotImplementedError(
"copying modified tuples is not implemented")
cdef TupleProxy n = type(self)()
n.copy(self.data, self.nbytes, reset=True)
return n
def compare(self, TupleProxy other):
'''return -1,0,1, if contents in this are binary
<,=,> to *other*
'''
if self.is_modified or other.is_modified:
raise NotImplementedError(
'comparison of modified TupleProxies is not implemented')
if self.data == other.data:
return 0
if self.nbytes < other.nbytes:
return -1
elif self.nbytes > other.nbytes:
return 1
return memcmp(self.data, other.data, self.nbytes)
def __richcmp__(self, TupleProxy other, int op):
if op == 2: # == operator
return self.compare(other) == 0
elif op == 3: # != operator
return self.compare(other) != 0
else:
err_msg = "op {0} isn't implemented yet".format(op)
raise NotImplementedError(err_msg)
cdef take(self, char * buffer, size_t nbytes):
'''start presenting buffer.
Take ownership of the pointer.
'''
self.data = buffer
self.nbytes = nbytes
self.update(buffer, nbytes)
cdef present(self, char * buffer, size_t nbytes):
'''start presenting buffer.
Do not take ownership of the pointer.
'''
self.update(buffer, nbytes)
cdef copy(self, char * buffer, size_t nbytes, bint reset=False):
'''start presenting buffer of size *nbytes*.
Buffer is a '\0'-terminated string without the '\n'.
Take a copy of buffer.
'''
# +1 for '\0'
cdef int s = sizeof(char) * (nbytes + 1)
self.data = <char*>malloc(s)
if self.data == NULL:
raise ValueError("out of memory in TupleProxy.copy()")
memcpy(<char*>self.data, buffer, s)
if reset:
for x from 0 <= x < nbytes:
if self.data[x] == '\0':
self.data[x] = '\t'
self.update(self.data, nbytes)
cpdef int getMinFields(self):
'''return minimum number of fields.'''
# 1 is not a valid tabix entry, but TupleProxy
# could be more generic.
return 1
cpdef int getMaxFields(self):
'''return maximum number of fields. Return
0 for unknown length.'''
return 0
cdef update(self, char * buffer, size_t nbytes):
'''update internal data.
*buffer* is a \0 terminated string.
*nbytes* is the number of bytes in buffer (excluding
the \0)
Update starts work in buffer, thus can be used
to collect any number of fields until nbytes
is exhausted.
If max_fields is set, the number of fields is initialized to
max_fields.
'''
cdef char * pos
cdef char * old_pos
cdef int field
cdef int max_fields, min_fields, x
assert strlen(buffer) == nbytes, \
"length of buffer (%i) != number of bytes (%i)" % (
strlen(buffer), nbytes)
if buffer[nbytes] != 0:
raise ValueError("incomplete line at %s" % buffer)
#################################
# remove line breaks and feeds and update number of bytes
x = nbytes - 1
while x > 0 and (buffer[x] == '\n' or buffer[x] == '\r'):
buffer[x] = '\0'
x -= 1
self.nbytes = x + 1
#################################
# clear data
if self.fields != NULL:
free(self.fields)
for field from 0 <= field < self.nfields:
if isNew(self.fields[field], self.data, self.nbytes):
free(self.fields[field])
self.is_modified = self.nfields = 0
#################################
# allocate new
max_fields = self.getMaxFields()
# pre-count fields - better would be
# to guess or dynamically grow
if max_fields == 0:
for x from 0 <= x < nbytes:
if buffer[x] == '\t':
max_fields += 1
max_fields += 1
self.fields = <char **>calloc(max_fields, sizeof(char *))
if self.fields == NULL:
raise ValueError("out of memory in TupleProxy.update()")
#################################
# start filling
field = 0
self.fields[field] = pos = buffer
field += 1
old_pos = pos
while 1:
pos = <char*>memchr(pos, '\t', nbytes)
if pos == NULL:
break
if field >= max_fields:
raise ValueError(
"parsing error: more than %i fields in line: %s" %
(max_fields, buffer))
pos[0] = '\0'
pos += 1
self.fields[field] = pos
field += 1
nbytes -= pos - old_pos
if nbytes < 0:
break
old_pos = pos
self.nfields = field
if self.nfields < self.getMinFields():
raise ValueError(
"parsing error: fewer that %i fields in line: %s" %
(self.getMinFields(), buffer))
def _getindex(self, int index):
'''return item at idx index'''
cdef int i = index
if i < 0:
i += self.nfields
if i < 0:
raise IndexError("list index out of range")
# apply offset - separating a fixed number
# of fields from a variable number such as in VCF
i += self.offset
if i >= self.nfields:
raise IndexError(
"list index out of range %i >= %i" %
(i, self.nfields))
return force_str(self.fields[i], self.encoding)
def __getitem__(self, key):
if type(key) == int:
return self._getindex(key)
# slice object
start, end, step = key.indices(self.nfields)
result = []
for index in range(start, end, step):
result.append(self._getindex(index))
return result
def _setindex(self, index, value):
'''set item at idx index.'''
cdef int idx = index
if idx < 0:
raise IndexError("list index out of range")
if idx >= self.nfields:
raise IndexError("list index out of range")
if isNew(self.fields[idx], self.data, self.nbytes):
free(self.fields[idx] )
self.is_modified = 1
if value is None:
self.fields[idx] = NULL
return
# conversion with error checking
value = force_bytes(value)
cdef char * tmp = <char*>value
self.fields[idx] = <char*>malloc((strlen( tmp ) + 1) * sizeof(char))
if self.fields[idx] == NULL:
raise ValueError("out of memory" )
strcpy(self.fields[idx], tmp)
def __setitem__(self, index, value):
'''set item at *index* to *value*'''
cdef int i = index
if i < 0:
i += self.nfields
i += self.offset
self._setindex(i, value)
def __len__(self):
return self.nfields
def __iter__(self):
self.index = 0
return self
def __next__(self):
"""python version of next().
"""
if self.index >= self.nfields:
raise StopIteration
cdef char * retval = self.fields[self.index]
self.index += 1
if retval == NULL:
return None
else:
return force_str(retval, self.encoding)
def __str__(self):
'''return original data'''
# copy and replace \0 bytes with \t characters
cdef char * cpy
if self.is_modified:
# todo: treat NULL values
result = []
for x in xrange(0, self.nfields):
result.append(StrOrEmpty(self.fields[x]).decode(self.encoding))
return "\t".join(result)
else:
cpy = <char*>calloc(sizeof(char), self.nbytes+1)
if cpy == NULL:
raise ValueError("out of memory")
memcpy(cpy, self.data, self.nbytes+1)
for x from 0 <= x < self.nbytes:
if cpy[x] == '\0':
cpy[x] = '\t'
result = cpy[:self.nbytes]
free(cpy)
r = result.decode(self.encoding)
return r
def toDot(v):
'''convert value to '.' if None'''
if v is None:
return "."
else:
return str(v)
def quote(v):
'''return a quoted attribute.'''
if isinstance(v, str):
return '"%s"' % v
else:
return str(v)
cdef class GTFProxy(TupleProxy):
'''Proxy class for access to GTF fields.
This class represents a GTF entry for fast read-access.
Write-access has been added as well, though some care must
be taken. If any of the string fields (contig, source, ...)
are set, the new value is tied to the lifetime of the
argument that was supplied.
The only exception is the attributes field when set from
a dictionary - this field will manage its own memory.
'''
def __cinit__(self):
# automatically calls TupleProxy.__cinit__
self.hasOwnAttributes = False
self._attributes = NULL
def __dealloc__(self):
# automatically calls TupleProxy.__dealloc__
if self.hasOwnAttributes:
free(self._attributes)
cpdef int getMinFields(self):
'''return minimum number of fields.'''
return 9
cpdef int getMaxFields(self):
'''return max number of fields.'''
return 9
property contig:
'''contig of feature.'''
def __get__(self):
return self._getindex(0)
def __set__(self, value):
self._setindex(0, value)
property source:
'''feature source.'''
def __get__(self):
return self._getindex(1)
def __set__(self, value):
if value is None:
value = "."
self._setindex(1, value)
property feature:
'''feature name.'''
def __get__(self):
return self._getindex(2)
def __set__(self, value):
if value is None:
value = "."
self._setindex(2, value)
property start:
'''feature start (in 0-based open/closed coordinates).'''
def __get__(self ):
return int( self._getindex(3)) - 1
def __set__(self, value ):
self._setindex(3, str(value+1))
property end:
'''feature end (in 0-based open/closed coordinates).'''
def __get__(self):
return int(self._getindex(4))
def __set__(self, value):
self._setindex(4, str(value))
property score:
'''feature score.'''
def __get__(self):
v = self._getindex(5)
if v == "" or v[0] == '.':
return None
else:
return float(v)
def __set__(self, value):
if value is None:
value = "."
self._setindex(5, str(value))
property strand:
'''feature strand.'''
def __get__(self):
return self._getindex(6)
def __set__(self, value ):
if value is None:
value = "."
self._setindex(6, value)
property frame:
'''feature frame.'''
def __get__(self):
v = self._getindex(7)
if v == "" or v[0] == '.':
return v
else:
return int(v)
def __set__(self, value):
if value is None:
value = "."
self._setindex(7, str(value))
property attributes:
'''feature attributes (as a string).'''
def __get__(self):
if self.hasOwnAttributes:
return force_str(self._attributes)
else:
return force_str(self._getindex(8))
def __set__( self, value):
if self.hasOwnAttributes:
free(self._attributes)
self._attributes = NULL
self.hasOwnAttributes = False
self._setindex(8, value)
cdef char * getAttributes(self):
'''return pointer to attributes.'''
cdef char * attributes
if self.hasOwnAttributes:
attributes = self._attributes
else:
attributes = self.fields[8]
if attributes == NULL:
raise KeyError("no attributes defined GTF entry")
return attributes
def asDict(self):
"""parse attributes - return as dict
"""
# remove comments
attributes = self.attributes
# separate into fields
# Fields might contain a ";", for example in ENSEMBL GTF file
# for mouse, v78:
# ...; transcript_name "TXNRD2;-001"; ....
# The current heuristic is to split on a semicolon followed by a
# space, see also http://mblab.wustl.edu/GTF22.html
# Remove white space to prevent a last empty field.
fields = [x.strip() for x in attributes.strip().split("; ")]
result = collections.OrderedDict()
for f in fields:
# strip semicolon (GTF files without a space after the last semicolon)
if f.endswith(";"):
f = f[:-1]
# split at most once in order to avoid separating
# multi-word values
d = [x.strip() for x in f.split(" ", 1)]
n,v = d[0], d[1]
if len(d) > 2:
v = d[1:]
if v[0] == '"' and v[-1] == '"':
v = v[1:-1]
else:
## try to convert to a value
try:
v = float(v)
v = int(v)
except ValueError:
pass
except TypeError:
pass
result[n] = v
return result
def fromDict(self, d):
'''set attributes from a dictionary.'''
cdef char * p
cdef int l
# clean up if this field is set twice
if self.hasOwnAttributes:
free(self._attributes)
aa = []
for k,v in d.items():
if isinstance(v, str):
aa.append( '%s "%s"' % (k,v) )
else:
aa.append( '%s %s' % (k,str(v)) )
a = force_bytes("; ".join(aa) + ";")
p = a
l = len(a)
self._attributes = <char *>calloc(l + 1, sizeof(char))
if self._attributes == NULL:
raise ValueError("out of memory")
memcpy(self._attributes, p, l)
self.hasOwnAttributes = True
self.is_modified = True
def __str__(self):
cdef char * cpy
cdef int x
if self.is_modified:
return "\t".join(
(self.contig,
self.source,
self.feature,
str(self.start+1),
str(self.end),
toDot(self.score),
toDot(self.strand),
toDot(self.frame),
self.attributes))
else:
return TupleProxy.__str__(self)
def invert(self, int lcontig):
'''invert coordinates to negative strand coordinates
This method will only act if the feature is on the
negative strand.'''
if self.strand[0] == '-':
start = min(self.start, self.end)
end = max(self.start, self.end)
self.start, self.end = lcontig - end, lcontig - start
def keys(self):
'''return a list of attributes defined in this entry.'''
r = self.attributes
return [x.strip().split(" ")[0]
# separator is ';' followed by space
for x in r.split("; ") if x.strip() != '']
def __getitem__(self, key):
return self.__getattr__(key)
def __getattr__(self, item):
"""Generic lookup of attribute from GFF/GTF attributes
Only called if there *isn't* an attribute with this name
"""
cdef char * start
cdef char * query
cdef char * cpy
cdef char * end
cdef int l
#
# important to use the getAttributes function.
# Using the self.attributes property to access
# the attributes caused a hard-to-trace bug
# in which fields in the attribute string were
# set to 0.
# Running through valgrind complained that
# memory was accessed in the memory field
# that has been released. It is not clear
# why this happened and might be a cython bug
# (Version 0.16). The valgrind warnings
# disappeard after accessing the C data structures
# directly and so did the bug.
cdef char * attributes = self.getAttributes()
if attributes == NULL:
raise KeyError("key %s not found, no attributes" % item)
# add space in order to make sure
# to not pick up a field that is a prefix of another field
r = force_bytes(item + " ")
query = r
start = strstr(attributes, query)
if start == NULL:
raise AttributeError("'GTFProxy' has no attribute '%s'" % item)
start += strlen(query)
# skip gaps before
while start[0] == ' ':
start += 1
if start[0] == '"':
start += 1
end = start
while end[0] != '\0' and end[0] != '"':
end += 1
l = end - start
result = force_str(PyBytes_FromStringAndSize(start, l),
self.encoding)
return result
else:
return force_str(start, self.encoding)
def setAttribute(self, name, value):
'''convenience method to set an attribute.'''
r = self.asDict()
r[name] = value
self.fromDict(r)
def __cmp__(self, other):
return (self.contig, self.strand, self.start) < \
(other.contig, other.strand, other.start)
# python 3 compatibility
def __richcmp__(GTFProxy self, GTFProxy other, int op):
if op == 0:
return (self.contig, self.strand, self.start) < \
(other.contig, other.strand, other.start)
elif op == 1:
return (self.contig, self.strand, self.start) <= \
(other.contig, other.strand, other.start)
elif op == 2:
return self.compare(other) == 0
elif op == 3:
return self.compare(other) != 0
else:
err_msg = "op {0} isn't implemented yet".format(op)
raise NotImplementedError(err_msg)
cdef class NamedTupleProxy(TupleProxy):
map_key2field = {}
def __setattr__(self, key, value):
'''set attribute.'''
cdef int idx
idx, f = self.map_key2field[key]
if self.nfields < idx:
raise KeyError("field %s not set" % key)
TupleProxy.__setitem__(self, idx, str(value))
def __getattr__(self, key):
cdef int idx
idx, f = self.map_key2field[key]
if self.nfields < idx:
raise KeyError("field %s not set" % key)
if f == str:
return force_str(self.fields[idx],
self.encoding)
return f(self.fields[idx])
cdef class BedProxy(NamedTupleProxy):
'''Proxy class for access to Bed fields.
This class represents a BED entry for fast read-access.
'''
map_key2field = {
'contig' : (0, str),
'start' : (1, int),
'end' : (2, int),
'name' : (3, str),
'score' : (4, float),
'strand' : (5, str),
'thickStart' : (6, int),
'thickEnd' : (7, int),
'itemRGB' : (8, str),
'blockCount': (9, int),
'blockSizes': (10, str),
'blockStarts': (11, str), }
cpdef int getMinFields(self):
'''return minimum number of fields.'''
return 3
cpdef int getMaxFields(self):
'''return max number of fields.'''
return 12
cdef update(self, char * buffer, size_t nbytes):
'''update internal data.
nbytes does not include the terminal '\0'.
'''
TupleProxy.update(self, buffer, nbytes)
if self.nfields < 3:
raise ValueError(
"bed format requires at least three columns")
# determines bed format
self.bedfields = self.nfields
# do automatic conversion
self.contig = self.fields[0]
self.start = atoi(self.fields[1])
self.end = atoi(self.fields[2])
# __setattr__ in base class seems to take precedence
# hence implement setters in __setattr__
#property start:
# def __get__( self ): return self.start
#property end:
# def __get__( self ): return self.end
def __str__(self):
cdef int save_fields = self.nfields
# ensure fields to use correct format
self.nfields = self.bedfields
retval = TupleProxy.__str__(self)
self.nfields = save_fields
return retval
def __setattr__(self, key, value ):
'''set attribute.'''
if key == "start":
self.start = value
elif key == "end":
self.end = value
cdef int idx
idx, f = self.map_key2field[key]
TupleProxy._setindex(self, idx, str(value) )
cdef class VCFProxy(NamedTupleProxy):
'''Proxy class for access to VCF fields.
The genotypes are accessed via a numeric index.
Sample headers are not available.
'''
map_key2field = {
'contig' : (0, str),
'pos' : (1, int),
'id' : (2, str),
'ref' : (3, str),
'alt' : (4, str),
'qual' : (5, str),
'filter' : (6, str),
'info' : (7, str),
'format' : (8, str) }
def __cinit__(self):
# automatically calls TupleProxy.__cinit__
# start indexed access at genotypes
self.offset = 9
cdef update(self, char * buffer, size_t nbytes):
'''update internal data.
nbytes does not include the terminal '\0'.
'''
TupleProxy.update(self, buffer, nbytes)
self.contig = self.fields[0]
# vcf counts from 1 - correct here
self.pos = atoi(self.fields[1]) - 1
def __len__(self):
'''return number of genotype fields.'''
return max(0, self.nfields - 9)
property pos:
'''feature end (in 0-based open/closed coordinates).'''
def __get__(self):
return self.pos
def __setattr__(self, key, value):
'''set attribute.'''
if key == "pos":
self.pos = value
value += 1
cdef int idx
idx, f = self.map_key2field[key]
TupleProxy._setindex(self, idx, str(value))
|