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 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
|
from __future__ import absolute_import, print_function, division
from operator import itemgetter, attrgetter
from petl.compat import text_type
from petl.util.base import asindices, records, Table, values, rowgroupby
from petl.errors import DuplicateKeyError
from petl.transform.basics import addfield
from petl.transform.sorts import sort
def tupletree(table, start='start', stop='stop', value=None):
"""
Construct an interval tree for the given table, where each node in the tree
is a row of the table.
"""
import intervaltree
tree = intervaltree.IntervalTree()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
assert start in flds, 'start field not recognised'
assert stop in flds, 'stop field not recognised'
getstart = itemgetter(flds.index(start))
getstop = itemgetter(flds.index(stop))
if value is None:
getvalue = tuple
else:
valueindices = asindices(hdr, value)
assert len(valueindices) > 0, 'invalid value field specification'
getvalue = itemgetter(*valueindices)
for row in it:
tree.addi(getstart(row), getstop(row), getvalue(row))
return tree
def facettupletrees(table, key, start='start', stop='stop', value=None):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a row of the table.
"""
import intervaltree
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
assert start in flds, 'start field not recognised'
assert stop in flds, 'stop field not recognised'
getstart = itemgetter(flds.index(start))
getstop = itemgetter(flds.index(stop))
if value is None:
getvalue = tuple
else:
valueindices = asindices(hdr, value)
assert len(valueindices) > 0, 'invalid value field specification'
getvalue = itemgetter(*valueindices)
keyindices = asindices(hdr, key)
assert len(keyindices) > 0, 'invalid key'
getkey = itemgetter(*keyindices)
trees = dict()
for row in it:
k = getkey(row)
if k not in trees:
trees[k] = intervaltree.IntervalTree()
trees[k].addi(getstart(row), getstop(row), getvalue(row))
return trees
def recordtree(table, start='start', stop='stop'):
"""
Construct an interval tree for the given table, where each node in the
tree is a row of the table represented as a record object.
"""
import intervaltree
getstart = attrgetter(start)
getstop = attrgetter(stop)
tree = intervaltree.IntervalTree()
for rec in records(table):
tree.addi(getstart(rec), getstop(rec), rec)
return tree
def facetrecordtrees(table, key, start='start', stop='stop'):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a record.
"""
import intervaltree
getstart = attrgetter(start)
getstop = attrgetter(stop)
getkey = attrgetter(key)
trees = dict()
for rec in records(table):
k = getkey(rec)
if k not in trees:
trees[k] = intervaltree.IntervalTree()
trees[k].addi(getstart(rec), getstop(rec), rec)
return trees
def intervallookup(table, start='start', stop='stop', value=None,
include_stop=False):
"""
Construct an interval lookup for the given table. E.g.::
>>> import petl as etl
>>> table = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, 'bar'],
... [4, 9, 'baz']]
>>> lkp = etl.intervallookup(table, 'start', 'stop')
>>> lkp.search(0, 1)
[]
>>> lkp.search(1, 2)
[(1, 4, 'foo')]
>>> lkp.search(2, 4)
[(1, 4, 'foo'), (3, 7, 'bar')]
>>> lkp.search(2, 5)
[(1, 4, 'foo'), (3, 7, 'bar'), (4, 9, 'baz')]
>>> lkp.search(9, 14)
[]
>>> lkp.search(19, 140)
[]
>>> lkp.search(0)
[]
>>> lkp.search(1)
[(1, 4, 'foo')]
>>> lkp.search(2)
[(1, 4, 'foo')]
>>> lkp.search(4)
[(3, 7, 'bar'), (4, 9, 'baz')]
>>> lkp.search(5)
[(3, 7, 'bar'), (4, 9, 'baz')]
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
Some examples using the `include_stop` and `value` keyword arguments::
>>> import petl as etl
>>> table = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, 'bar'],
... [4, 9, 'baz']]
>>> lkp = etl.intervallookup(table, 'start', 'stop', include_stop=True,
... value='value')
>>> lkp.search(0, 1)
['foo']
>>> lkp.search(1, 2)
['foo']
>>> lkp.search(2, 4)
['foo', 'bar', 'baz']
>>> lkp.search(2, 5)
['foo', 'bar', 'baz']
>>> lkp.search(9, 14)
['baz']
>>> lkp.search(19, 140)
[]
>>> lkp.search(0)
[]
>>> lkp.search(1)
['foo']
>>> lkp.search(2)
['foo']
>>> lkp.search(4)
['foo', 'bar', 'baz']
>>> lkp.search(5)
['bar', 'baz']
"""
tree = tupletree(table, start=start, stop=stop, value=value)
return IntervalTreeLookup(tree, include_stop=include_stop)
Table.intervallookup = intervallookup
def _search_tree(tree, start, stop, include_stop):
if stop is None:
if include_stop:
stop = start + 1
start -= 1
args = (start, stop)
else:
args = (start,)
else:
if include_stop:
stop += 1
start -= 1
args = (start, stop)
if len(args) == 2:
results = sorted(tree.overlap(*args))
else:
results = sorted(tree.at(*args))
return results
class IntervalTreeLookup(object):
def __init__(self, tree, include_stop=False):
self.tree = tree
self.include_stop = include_stop
def search(self, start, stop=None):
results = _search_tree(self.tree, start, stop, self.include_stop)
return [r.data for r in results]
find = search
def intervallookupone(table, start='start', stop='stop', value=None,
include_stop=False, strict=True):
"""
Construct an interval lookup for the given table, returning at most one
result for each query. E.g.::
>>> import petl as etl
>>> table = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, 'bar'],
... [4, 9, 'baz']]
>>> lkp = etl.intervallookupone(table, 'start', 'stop', strict=False)
>>> lkp.search(0, 1)
>>> lkp.search(1, 2)
(1, 4, 'foo')
>>> lkp.search(2, 4)
(1, 4, 'foo')
>>> lkp.search(2, 5)
(1, 4, 'foo')
>>> lkp.search(9, 14)
>>> lkp.search(19, 140)
>>> lkp.search(0)
>>> lkp.search(1)
(1, 4, 'foo')
>>> lkp.search(2)
(1, 4, 'foo')
>>> lkp.search(4)
(3, 7, 'bar')
>>> lkp.search(5)
(3, 7, 'bar')
If ``strict=True``, queries returning more than one result will
raise a `DuplicateKeyError`. If ``strict=False`` and there is
more than one result, the first result is returned.
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
"""
tree = tupletree(table, start=start, stop=stop, value=value)
return IntervalTreeLookupOne(tree, strict=strict, include_stop=include_stop)
Table.intervallookupone = intervallookupone
class IntervalTreeLookupOne(object):
def __init__(self, tree, strict=True, include_stop=False):
self.tree = tree
self.strict = strict
self.include_stop = include_stop
def search(self, start, stop=None):
results = _search_tree(self.tree, start, stop, self.include_stop)
if len(results) == 0:
return None
elif len(results) > 1 and self.strict:
raise DuplicateKeyError((start, stop))
else:
return results[0].data
find = search
def intervalrecordlookup(table, start='start', stop='stop', include_stop=False):
"""
As :func:`petl.transform.intervals.intervallookup` but return records
instead of tuples.
"""
tree = recordtree(table, start=start, stop=stop)
return IntervalTreeLookup(tree, include_stop=include_stop)
Table.intervalrecordlookup = intervalrecordlookup
def intervalrecordlookupone(table, start='start', stop='stop',
include_stop=False, strict=True):
"""
As :func:`petl.transform.intervals.intervallookupone` but return records
instead of tuples.
"""
tree = recordtree(table, start=start, stop=stop)
return IntervalTreeLookupOne(tree, include_stop=include_stop, strict=strict)
Table.intervalrecordlookupone = intervalrecordlookupone
def facetintervallookup(table, key, start='start', stop='stop',
value=None, include_stop=False):
"""
Construct a faceted interval lookup for the given table. E.g.::
>>> import petl as etl
>>> table = (('type', 'start', 'stop', 'value'),
... ('apple', 1, 4, 'foo'),
... ('apple', 3, 7, 'bar'),
... ('orange', 4, 9, 'baz'))
>>> lkp = etl.facetintervallookup(table, key='type', start='start', stop='stop')
>>> lkp['apple'].search(1, 2)
[('apple', 1, 4, 'foo')]
>>> lkp['apple'].search(2, 4)
[('apple', 1, 4, 'foo'), ('apple', 3, 7, 'bar')]
>>> lkp['apple'].search(2, 5)
[('apple', 1, 4, 'foo'), ('apple', 3, 7, 'bar')]
>>> lkp['orange'].search(2, 5)
[('orange', 4, 9, 'baz')]
>>> lkp['orange'].search(9, 14)
[]
>>> lkp['orange'].search(19, 140)
[]
>>> lkp['apple'].search(1)
[('apple', 1, 4, 'foo')]
>>> lkp['apple'].search(2)
[('apple', 1, 4, 'foo')]
>>> lkp['apple'].search(4)
[('apple', 3, 7, 'bar')]
>>> lkp['apple'].search(5)
[('apple', 3, 7, 'bar')]
>>> lkp['orange'].search(5)
[('orange', 4, 9, 'baz')]
"""
trees = facettupletrees(table, key, start=start, stop=stop, value=value)
out = dict()
for k in trees:
out[k] = IntervalTreeLookup(trees[k], include_stop=include_stop)
return out
Table.facetintervallookup = facetintervallookup
def facetintervallookupone(table, key, start='start', stop='stop',
value=None, include_stop=False, strict=True):
"""
Construct a faceted interval lookup for the given table, returning at most
one result for each query.
If ``strict=True``, queries returning more than one result will
raise a `DuplicateKeyError`. If ``strict=False`` and there is
more than one result, the first result is returned.
"""
trees = facettupletrees(table, key, start=start, stop=stop, value=value)
out = dict()
for k in trees:
out[k] = IntervalTreeLookupOne(trees[k], include_stop=include_stop,
strict=strict)
return out
Table.facetintervallookupone = facetintervallookupone
def facetintervalrecordlookup(table, key, start='start', stop='stop',
include_stop=False):
"""
As :func:`petl.transform.intervals.facetintervallookup` but return records.
"""
trees = facetrecordtrees(table, key, start=start, stop=stop)
out = dict()
for k in trees:
out[k] = IntervalTreeLookup(trees[k], include_stop=include_stop)
return out
Table.facetintervalrecordlookup = facetintervalrecordlookup
def facetintervalrecordlookupone(table, key, start, stop, include_stop=False,
strict=True):
"""
As :func:`petl.transform.intervals.facetintervallookupone` but return
records.
"""
trees = facetrecordtrees(table, key, start=start, stop=stop)
out = dict()
for k in trees:
out[k] = IntervalTreeLookupOne(trees[k], include_stop=include_stop,
strict=strict)
return out
Table.facetintervalrecordlookupone = facetintervalrecordlookupone
def intervaljoin(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False,
lprefix=None, rprefix=None):
"""
Join two tables by overlapping intervals. E.g.::
>>> import petl as etl
>>> left = [['begin', 'end', 'quux'],
... [1, 2, 'a'],
... [2, 4, 'b'],
... [2, 5, 'c'],
... [9, 14, 'd'],
... [1, 1, 'e'],
... [10, 10, 'f']]
>>> right = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, 'bar'],
... [4, 9, 'baz']]
>>> table1 = etl.intervaljoin(left, right,
... lstart='begin', lstop='end',
... rstart='start', rstop='stop')
>>> table1.lookall()
+-------+-----+------+-------+------+-------+
| begin | end | quux | start | stop | value |
+=======+=====+======+=======+======+=======+
| 1 | 2 | 'a' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 4 | 9 | 'baz' |
+-------+-----+------+-------+------+-------+
>>> # include stop coordinate in intervals
... table2 = etl.intervaljoin(left, right,
... lstart='begin', lstop='end',
... rstart='start', rstop='stop',
... include_stop=True)
>>> table2.lookall()
+-------+-----+------+-------+------+-------+
| begin | end | quux | start | stop | value |
+=======+=====+======+=======+======+=======+
| 1 | 2 | 'a' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 4 | 9 | 'baz' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 4 | 9 | 'baz' |
+-------+-----+------+-------+------+-------+
| 9 | 14 | 'd' | 4 | 9 | 'baz' |
+-------+-----+------+-------+------+-------+
| 1 | 1 | 'e' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
An additional key comparison can be made, e.g.::
>>> import petl as etl
>>> left = (('fruit', 'begin', 'end'),
... ('apple', 1, 2),
... ('apple', 2, 4),
... ('apple', 2, 5),
... ('orange', 2, 5),
... ('orange', 9, 14),
... ('orange', 19, 140),
... ('apple', 1, 1))
>>> right = (('type', 'start', 'stop', 'value'),
... ('apple', 1, 4, 'foo'),
... ('apple', 3, 7, 'bar'),
... ('orange', 4, 9, 'baz'))
>>> table3 = etl.intervaljoin(left, right,
... lstart='begin', lstop='end', lkey='fruit',
... rstart='start', rstop='stop', rkey='type')
>>> table3.lookall()
+----------+-------+-----+----------+-------+------+-------+
| fruit | begin | end | type | start | stop | value |
+==========+=======+=====+==========+=======+======+=======+
| 'apple' | 1 | 2 | 'apple' | 1 | 4 | 'foo' |
+----------+-------+-----+----------+-------+------+-------+
| 'apple' | 2 | 4 | 'apple' | 1 | 4 | 'foo' |
+----------+-------+-----+----------+-------+------+-------+
| 'apple' | 2 | 4 | 'apple' | 3 | 7 | 'bar' |
+----------+-------+-----+----------+-------+------+-------+
| 'apple' | 2 | 5 | 'apple' | 1 | 4 | 'foo' |
+----------+-------+-----+----------+-------+------+-------+
| 'apple' | 2 | 5 | 'apple' | 3 | 7 | 'bar' |
+----------+-------+-----+----------+-------+------+-------+
| 'orange' | 2 | 5 | 'orange' | 4 | 9 | 'baz' |
+----------+-------+-----+----------+-------+------+-------+
"""
assert (lkey is None) == (rkey is None), \
'facet key field must be provided for both or neither table'
return IntervalJoinView(left, right, lstart=lstart, lstop=lstop,
rstart=rstart, rstop=rstop, lkey=lkey,
rkey=rkey, include_stop=include_stop,
lprefix=lprefix, rprefix=rprefix)
Table.intervaljoin = intervaljoin
class IntervalJoinView(Table):
def __init__(self, left, right, lstart='start', lstop='stop',
rstart='start', rstop='stop', lkey=None, rkey=None,
include_stop=False, lprefix=None, rprefix=None):
self.left = left
self.lstart = lstart
self.lstop = lstop
self.lkey = lkey
self.right = right
self.rstart = rstart
self.rstop = rstop
self.rkey = rkey
self.include_stop = include_stop
self.lprefix = lprefix
self.rprefix = rprefix
def __iter__(self):
return iterintervaljoin(
left=self.left,
right=self.right,
lstart=self.lstart,
lstop=self.lstop,
rstart=self.rstart,
rstop=self.rstop,
lkey=self.lkey,
rkey=self.rkey,
include_stop=self.include_stop,
missing=None,
lprefix=self.lprefix,
rprefix=self.rprefix,
leftouter=False
)
def intervalleftjoin(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False,
missing=None, lprefix=None, rprefix=None):
"""
Like :func:`petl.transform.intervals.intervaljoin` but rows from the left
table without a match in the right table are also included. E.g.::
>>> import petl as etl
>>> left = [['begin', 'end', 'quux'],
... [1, 2, 'a'],
... [2, 4, 'b'],
... [2, 5, 'c'],
... [9, 14, 'd'],
... [1, 1, 'e'],
... [10, 10, 'f']]
>>> right = [['start', 'stop', 'value'],
... [1, 4, 'foo'],
... [3, 7, 'bar'],
... [4, 9, 'baz']]
>>> table1 = etl.intervalleftjoin(left, right,
... lstart='begin', lstop='end',
... rstart='start', rstop='stop')
>>> table1.lookall()
+-------+-----+------+-------+------+-------+
| begin | end | quux | start | stop | value |
+=======+=====+======+=======+======+=======+
| 1 | 2 | 'a' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 4 | 'b' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 1 | 4 | 'foo' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 3 | 7 | 'bar' |
+-------+-----+------+-------+------+-------+
| 2 | 5 | 'c' | 4 | 9 | 'baz' |
+-------+-----+------+-------+------+-------+
| 9 | 14 | 'd' | None | None | None |
+-------+-----+------+-------+------+-------+
| 1 | 1 | 'e' | None | None | None |
+-------+-----+------+-------+------+-------+
| 10 | 10 | 'f' | None | None | None |
+-------+-----+------+-------+------+-------+
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
"""
assert (lkey is None) == (rkey is None), \
'facet key field must be provided for both or neither table'
return IntervalLeftJoinView(left, right, lstart=lstart, lstop=lstop,
rstart=rstart, rstop=rstop, lkey=lkey,
rkey=rkey, include_stop=include_stop,
missing=missing, lprefix=lprefix,
rprefix=rprefix)
Table.intervalleftjoin = intervalleftjoin
class IntervalLeftJoinView(Table):
def __init__(self, left, right, lstart='start', lstop='stop',
rstart='start', rstop='stop', lkey=None, rkey=None,
missing=None, include_stop=False, lprefix=None, rprefix=None):
self.left = left
self.lstart = lstart
self.lstop = lstop
self.lkey = lkey
self.right = right
self.rstart = rstart
self.rstop = rstop
self.rkey = rkey
self.missing = missing
self.include_stop = include_stop
self.lprefix = lprefix
self.rprefix = rprefix
def __iter__(self):
return iterintervaljoin(
left=self.left,
right=self.right,
lstart=self.lstart,
lstop=self.lstop,
rstart=self.rstart,
rstop=self.rstop,
lkey=self.lkey,
rkey=self.rkey,
include_stop=self.include_stop,
missing=self.missing,
lprefix=self.lprefix,
rprefix=self.rprefix,
leftouter=True
)
def intervalantijoin(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False,
missing=None):
"""
Return rows from the `left` table with no overlapping rows from the `right`
table.
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
"""
assert (lkey is None) == (rkey is None), \
'facet key field must be provided for both or neither table'
return IntervalAntiJoinView(left, right, lstart=lstart, lstop=lstop,
rstart=rstart, rstop=rstop, lkey=lkey,
rkey=rkey, include_stop=include_stop,
missing=missing)
Table.intervalantijoin = intervalantijoin
class IntervalAntiJoinView(Table):
def __init__(self, left, right, lstart='start', lstop='stop',
rstart='start', rstop='stop', lkey=None, rkey=None,
missing=None, include_stop=False):
self.left = left
self.lstart = lstart
self.lstop = lstop
self.lkey = lkey
self.right = right
self.rstart = rstart
self.rstop = rstop
self.rkey = rkey
self.missing = missing
self.include_stop = include_stop
def __iter__(self):
return iterintervaljoin(
left=self.left,
right=self.right,
lstart=self.lstart,
lstop=self.lstop,
rstart=self.rstart,
rstop=self.rstop,
lkey=self.lkey,
rkey=self.rkey,
include_stop=self.include_stop,
missing=self.missing,
lprefix=None,
rprefix=None,
leftouter=True,
anti=True
)
def iterintervaljoin(left, right, lstart, lstop, rstart, rstop, lkey,
rkey, include_stop, missing, lprefix, rprefix, leftouter,
anti=False):
# create iterators and obtain fields
lit = iter(left)
lhdr = next(lit)
lflds = list(map(text_type, lhdr))
rit = iter(right)
rhdr = next(rit)
rflds = list(map(text_type, rhdr))
# check fields via petl.util.asindices (raises FieldSelectionError if spec
# is not valid)
asindices(lhdr, lstart)
asindices(lhdr, lstop)
if lkey is not None:
asindices(lhdr, lkey)
asindices(rhdr, rstart)
asindices(rhdr, rstop)
if rkey is not None:
asindices(rhdr, rkey)
# determine output fields
if lprefix is None:
outhdr = list(lflds)
if not anti:
outhdr.extend(rflds)
else:
outhdr = list(lprefix + f for f in lflds)
if not anti:
outhdr.extend(rprefix + f for f in rflds)
yield tuple(outhdr)
# create getters for start and stop positions
getlstart = itemgetter(lflds.index(lstart))
getlstop = itemgetter(lflds.index(lstop))
if rkey is None:
# build interval lookup for right table
lookup = intervallookup(right, rstart, rstop, include_stop=include_stop)
search = lookup.search
# main loop
for lrow in lit:
start = getlstart(lrow)
stop = getlstop(lrow)
rrows = search(start, stop)
if rrows:
if not anti:
for rrow in rrows:
outrow = list(lrow)
outrow.extend(rrow)
yield tuple(outrow)
elif leftouter:
outrow = list(lrow)
if not anti:
outrow.extend([missing] * len(rflds))
yield tuple(outrow)
else:
# build interval lookup for right table
lookup = facetintervallookup(right, key=rkey, start=rstart,
stop=rstop, include_stop=include_stop)
search = dict()
for f in lookup:
search[f] = lookup[f].search
# getter for facet key values in left table
getlkey = itemgetter(*asindices(lflds, lkey))
# main loop
for lrow in lit:
lkey = getlkey(lrow)
start = getlstart(lrow)
stop = getlstop(lrow)
try:
rrows = search[lkey](start, stop)
except KeyError:
rrows = None
except AttributeError:
rrows = None
if rrows:
if not anti:
for rrow in rrows:
outrow = list(lrow)
outrow.extend(rrow)
yield tuple(outrow)
elif leftouter:
outrow = list(lrow)
if not anti:
outrow.extend([missing] * len(rflds))
yield tuple(outrow)
def intervaljoinvalues(left, right, value, lstart='start', lstop='stop',
rstart='start', rstop='stop', lkey=None, rkey=None,
include_stop=False):
"""
Convenience function to join the left table with values from a specific
field in the right hand table.
Note start coordinates are included and stop coordinates are excluded
from the interval. Use the `include_stop` keyword argument to include the
upper bound of the interval when finding overlaps.
"""
assert (lkey is None) == (rkey is None), \
'facet key field must be provided for both or neither table'
if lkey is None:
lkp = intervallookup(right, start=rstart, stop=rstop, value=value,
include_stop=include_stop)
f = lambda row: lkp.search(row[lstart], row[lstop])
else:
lkp = facetintervallookup(right, rkey, start=rstart, stop=rstop,
value=value, include_stop=include_stop)
f = lambda row: lkp[row[lkey]].search(row[lstart], row[lstop])
return addfield(left, value, f)
Table.intervaljoinvalues = intervaljoinvalues
def intervalsubtract(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False):
"""
Subtract intervals in the right hand table from intervals in the left hand
table.
"""
assert (lkey is None) == (rkey is None), \
'facet key field must be provided for both or neither table'
return IntervalSubtractView(left, right, lstart=lstart, lstop=lstop,
rstart=rstart, rstop=rstop, lkey=lkey,
rkey=rkey, include_stop=include_stop)
Table.intervalsubtract = intervalsubtract
class IntervalSubtractView(Table):
def __init__(self, left, right, lstart='start', lstop='stop',
rstart='start', rstop='stop', lkey=None, rkey=None,
include_stop=False):
self.left = left
self.lstart = lstart
self.lstop = lstop
self.lkey = lkey
self.right = right
self.rstart = rstart
self.rstop = rstop
self.rkey = rkey
self.include_stop = include_stop
def __iter__(self):
return iterintervalsubtract(self.left, self.right, self.lstart,
self.lstop, self.rstart, self.rstop,
self.lkey, self.rkey, self.include_stop)
def iterintervalsubtract(left, right, lstart, lstop, rstart, rstop, lkey, rkey,
include_stop):
# create iterators and obtain fields
lit = iter(left)
lhdr = next(lit)
lflds = list(map(text_type, lhdr))
rit = iter(right)
rhdr = next(rit)
# check fields via petl.util.asindices (raises FieldSelectionError if spec
# is not valid)
asindices(lhdr, lstart)
asindices(lhdr, lstop)
if lkey is not None:
asindices(lhdr, lkey)
asindices(rhdr, rstart)
asindices(rhdr, rstop)
if rkey is not None:
asindices(rhdr, rkey)
# determine output fields
outhdr = list(lflds)
yield tuple(outhdr)
# create getters for start and stop positions
lstartidx, lstopidx = asindices(lhdr, (lstart, lstop))
getlcoords = itemgetter(lstartidx, lstopidx)
getrcoords = itemgetter(*asindices(rhdr, (rstart, rstop)))
if rkey is None:
# build interval lookup for right table
lookup = intervallookup(right, rstart, rstop, include_stop=include_stop)
search = lookup.search
# main loop
for lrow in lit:
start, stop = getlcoords(lrow)
rrows = search(start, stop)
if not rrows:
yield tuple(lrow)
else:
rivs = sorted([getrcoords(rrow) for rrow in rrows],
key=itemgetter(0)) # sort by start
for x, y in _subtract(start, stop, rivs):
out = list(lrow)
out[lstartidx] = x
out[lstopidx] = y
yield tuple(out)
else:
# build interval lookup for right table
lookup = facetintervallookup(right, key=rkey, start=rstart, stop=rstop,
include_stop=include_stop)
# getter for facet key values in left table
getlkey = itemgetter(*asindices(lhdr, lkey))
# main loop
for lrow in lit:
lkey = getlkey(lrow)
start, stop = getlcoords(lrow)
try:
rrows = lookup[lkey].search(start, stop)
except KeyError:
rrows = None
except AttributeError:
rrows = None
if not rrows:
yield tuple(lrow)
else:
rivs = sorted([getrcoords(rrow) for rrow in rrows],
key=itemgetter(0)) # sort by start
for x, y in _subtract(start, stop, rivs):
out = list(lrow)
out[lstartidx] = x
out[lstopidx] = y
yield tuple(out)
from collections import namedtuple
_Interval = namedtuple('Interval', 'start stop')
def collapsedintervals(table, start='start', stop='stop', key=None):
"""
Utility function to collapse intervals in a table.
If no facet `key` is given, returns an iterator over `(start, stop)` tuples.
If facet `key` is given, returns an iterator over `(key, start, stop)`
tuples.
"""
if key is None:
table = sort(table, key=start)
for iv in _collapse(values(table, (start, stop))):
yield iv
else:
table = sort(table, key=(key, start))
for k, g in rowgroupby(table, key=key, value=(start, stop)):
for iv in _collapse(g):
yield (k,) + iv
Table.collapsedintervals = collapsedintervals
def _collapse(intervals):
"""
Collapse an iterable of intervals sorted by start coord.
"""
span = None
for start, stop in intervals:
if span is None:
span = _Interval(start, stop)
elif start <= span.stop < stop:
span = _Interval(span.start, stop)
elif start > span.stop:
yield span
span = _Interval(start, stop)
if span is not None:
yield span
def _subtract(start, stop, intervals):
"""
Subtract intervals from a spanning interval.
"""
remainder_start = start
sub_stop = None
for sub_start, sub_stop in _collapse(intervals):
if remainder_start < sub_start:
yield _Interval(remainder_start, sub_start)
remainder_start = sub_stop
if sub_stop is not None and sub_stop < stop:
yield _Interval(sub_stop, stop)
|