orange-bioinformatics / _bioinformatics / obiOntology.py

   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
"""
===========
obiOntology
===========

This module provides an interface for parsing, creating and manipulating of
OBO ontologies (http://www.obofoundry.org/)

Construct an ontology from scratch with custom terms ::

    >>> term = OBOObject("Term", id="foo:bar", name="Foo bar")
    >>> print term
    [Term]
    id: foo:bar
    name: Foo bar

    >>> ontology = OBOOntology()
    >>> ontology.add_object(term)
    >>> ontology.add_header_tag("created-by", "ales") # add a header tag
    >>> from StringIO import StringIO
    >>> buffer = StringIO()
    >>> ontology.dump(buffer) # Save the ontology to a file like object
    >>> print buffer.getvalue() # Print the contents of the buffer
    created-by: ales
    <BLANKLINE>
    [Term]
    id: foo:bar
    name: Foo bar
    <BLANKLINE>

To load an ontology from a file pass the file or filename to the
:class:`OBOOntology` constructor or call its load method ::

    >>> buffer.seek(0) # rewind
    >>> ontology = OBOOntology(buffer)
    >>> # Or equivalently
    >>> buffer.seek(0) # rewind
    >>> ontology = OBOOntology()
    >>> ontology.load(buffer)


See http://www.geneontology.org/GO.format.obo-1_2.shtml for the definition
of the .obo file format.

"""

import re
import urllib2
import warnings
from collections import defaultdict
from StringIO import StringIO


#: These are builtin OBO objects present in any ontology by default.
BUILTIN_OBO_OBJECTS = [
"""[Typedef]
id: is_a
name: is_a
range: OBO:TERM_OR_TYPE
domain: OBO:TERM_OR_TYPE
definition: The basic subclassing relationship [OBO:defs]""",

"""[Typedef]
id: disjoint_from
name: disjoint_from
range: OBO:TERM
domain: OBO:TERM
definition: Indicates that two classes are disjoint [OBO:defs]""",

"""[Typedef]
id: instance_of
name: instance_of
range: OBO:TERM
domain: OBO:INSTANCE
definition: Indicates the type of an instance [OBO:defs]""",

"""[Typedef]
id: inverse_of
name: inverse_of
range: OBO:TYPE
domain: OBO:TYPE
definition: Indicates that one relationship type is the inverse of another [OBO:defs]""",

"""[Typedef]
id: union_of
name: union_of
range: OBO:TERM
domain: OBO:TERM
definition: Indicates that a term is the union of several others [OBO:defs]""",

"""[Typedef]
id: intersection_of
name: intersection_of
range: OBO:TERM
domain: OBO:TERM
definition: Indicates that a term is the intersection of several others [OBO:defs]"""
]


def _split_and_strip(string, sep):
    """
    Split the `string` by separator `sep` in to two parts and strip
    any whitespace between the inner parts.

    """
    head, tail = string.split(sep, 1)
    return head.rstrip(" "), tail.lstrip(" ")


class OBOObject(object):
    """
    Represents a generic OBO object (e.g. Term, Typedef, Instance, ...)
    Example::

        >>> term = OBOObject(stanza_type="Term", id="FOO:001", name="bar")

        >>> term = OBOObject(
        ...     stanza_type="Term",
        ...     id="FOO:001",
        ...     name="bar",
        ...     def_="Example definition { modifier=frob } ! Comment"
        ... )
        ...

    An alternative way to specify tags in the constructor::

        >>> term = OBOObject(stanza_type="Term", id="FOO:001", name="bar",
        ...                  def_=("Example definition",
        ...                        [("modifier", "frob")],
        ...                        "Comment"))
        ...

    .. note::
        Note the use of ``def_`` to define the 'def' tag. This is to
        avoid the name clash with the python's ``def`` keyword.

    """
    def __init__(self, stanza_type="Term", **kwargs):
        """
        Initialize from keyword arguments.
        """
        self.stanza_type = stanza_type

        self.modifiers = []
        self.comments = []
        self.tag_values = []
        self.values = {}

        sorted_tags = sorted(
            kwargs.iteritems(),
            key=lambda key_val: chr(1) if key_val[0] == "id" else key_val[0]
        )

        for tag, value in sorted_tags:
            if isinstance(value, basestring):
                tag, value, modifiers, comment = \
                    self.parse_tag_value(self.name_demangle(tag), value)
            elif isinstance(value, tuple):
                tag, value, modifiers, comment = \
                    ((self.name_demangle(tag),) + value + (None, None))[:4]
            self.add_tag(tag, value, modifiers, comment)

        self.related = set()

    @property
    def is_annonymous(self):
        """
        Is this object anonymous.
        """
        value = self.get_value("is_annonymous")
        return bool(value)

    def name_mangle(self, tag):
        """
        Mangle tag name if it conflicts with python keyword.

        Example::

            >>> term.name_mangle("def"), term.name_mangle("class")
            ('def_', 'class_')

        """
        if tag in ["def", "class", "in", "not"]:
            return tag + "_"
        else:
            return tag

    def name_demangle(self, tag):
        """
        Reverse of `name_mangle`.
        """
        if tag in ["def_", "class_", "in_", "not_"]:
            return tag[:-1]
        else:
            return tag

    def add_tag(self, tag, value, modifiers=None, comment=None):
        """
        Add `tag`, `value` pair to the object with optional modifiers and
        comment.

        Example::

            >>> term = OBOObject("Term")
            >>> term.add_tag("id", "FOO:002", comment="This is an id")
            >>> print term
            [Term]
            id: FOO:002 ! This is an id

        """
        tag = intern(tag)  # a small speed and memory benefit
        self.tag_values.append((tag, value))
        self.modifiers.append(modifiers)
        self.comments.append(comment)
        self.values.setdefault(tag, []).append(value)

        #  TODO: fix multiple tags grouping
        if hasattr(self, tag):
            if isinstance(getattr(self, tag), list):
                getattr(self, tag).append(value)
            else:
                setattr(self, tag, [getattr(self, tag)] + [value])
        else:
            setattr(self, self.name_mangle(tag), value)

    def update(self, other):
        """
        Update the term with tag value pairs from `other`
        (:class:`OBOObject`). The tag value pairs are appended to the
        end except for the `id` tag.

        """
        for (tag, value), modifiers, comment in \
                zip(other.tag_values, other.modifiers, other.comments):
            if tag != "id":
                self.add_tag(tag, value, modifiers, comment)

    def get_value(self, tag, group=True):
        if group:
            pairs = [pair for pair in self.tag_values if pair[0] == tag]
            return pairs
        else:
            tag = self.name_mangle(tag)
            if tag in self.__dict__:
                return self.__dict__[tag]
            else:
                raise ValueError("No value for tag: %s" % tag)

    def tag_count(self):
        """
        Return the number of tags in this object.
        """
        return len(self.tag_values)

    def tags(self):
        """
        Return an iterator over the (tag, value) pairs.
        """
        for i in range(self.tag_count()):
            yield self.tag_values[i] + (self.modifiers[i], self.comments[i])

    def format_single_tag(self, index):
        """
        Return a formated string representing index-th tag pair value

        Example::

            >>> term = OBOObject(
            ...     "Term", id="FOO:001", name="bar",
            ...      def_="Example definition {modifier=frob} ! Comment")
            ...
            >>> term.format_single_tag(0)
            'id: FOO:001'
            >>> term.format_single_tag(1)
            'def: Example definition { modifier=frob } ! Comment'

        ..
            Why by index, and not by tag?

        """
        tag, value = self.tag_values[index]
        modifiers = self.modifiers[index]
        comment = self.comments[index]
        res = ["%s: %s" % (tag, value)]
        if modifiers:
            res.append("{ %s }" % modifiers)
        if comment:
            res.append("! " + comment)
        return " ".join(res)

    def format_stanza(self):
        """
        Return a string stanza representation of this object.
        """
        stanza = ["[%s]" % self.stanza_type]
        for i in range(self.tag_count()):
            stanza.append(self.format_single_tag(i))
        return "\n".join(stanza)

    @classmethod
    def parse_stanza(cls, stanza):
        r"""
        Parse and return an OBOObject instance from a stanza string.

        Example::

            >>> term = OBOObject.parse_stanza("[Term]\nid: FOO:001\nname:bar")
            >>> print term.id, term.name
            FOO:001 bar

        """
        lines = stanza.splitlines()
        stanza_type = lines[0].strip("[]")
        tag_values = []
        for line in lines[1:]:
            if ":" in line:
                tag_values.append(cls.parse_tag_value(line))

        obo = OBOObject(stanza_type)
        for tag, value, modifiers, comment in tag_values:
            obo.add_tag(tag, value, modifiers, comment)
        return obo

    @classmethod
    def parse_tag_value_1(cls, tag_value_pair, *args):
        """
        Parse and return a four-tuple containing a tag, value, a
        list of modifier pairs, comment. If no modifiers or comments
        are present the corresponding entries will be ``None``.

        Example::

            >>> OBOObject.parse_tag_value("foo: bar {modifier=frob} ! Comment")
            ('foo', 'bar', 'modifier=frob', 'Comment')
            >>> OBOObject.parse_tag_value("foo: bar")
            ('foo', 'bar', None, None)
            >>> # Can also pass tag, value pair already split
            >>> OBOObject.parse_tag_value("foo", "bar {modifier=frob} ! Comment")
            ('foo', 'bar', 'modifier=frob', 'Comment')

        """
        if args and ":" not in tag_value_pair:
            tag, rest = tag_value_pair, args[0]
        else:
            tag, rest = _split_and_strip(tag_value_pair, ":")
        value, modifiers, comment = None, None, None

        if "{" in rest:
            value, rest = _split_and_strip(rest, "{",)
            modifiers, rest = _split_and_strip(rest, "}")
        if "!" in rest:
            if value is None:
                value, comment = _split_and_strip(rest, "!")
            else:
                _, comment = _split_and_strip(rest, "!")
        if value is None:
            value = rest

        if modifiers is not None:
            modifiers = modifiers  # TODO: split modifiers in a list

        return tag, value, modifiers, comment

    _RE_TAG_VALUE = re.compile(r"^(?P<tag>.+?[^\\])\s*:\s*(?P<value>.+?)\s*(?P<modifiers>[^\\]{.+?[^\\]})?\s*(?P<comment>[^\\]!.*)?$")
    _RE_VALUE = re.compile(r"^\s*(?P<value>.+?)\s*(?P<modifiers>[^\\]{.+?[^\\]})?\s*(?P<comment>[^\\]!.*)?$")

    @classmethod
    def parse_tag_value(cls, tag_value_pair, arg=None):
        """
        Parse and return a four-tuple containing a tag, value, a list
        of modifier pairs, comment. If no modifiers or comments are
        present the corresponding entries will be None.

        Example::
            >>> OBOObject.parse_tag_value("foo: bar {modifier=frob} ! Comment")
            ('foo', 'bar', 'modifier=frob', 'Comment')
            >>> OBOObject.parse_tag_value("foo: bar")
            ('foo', 'bar', None, None)
            >>> #  Can also pass tag, value pair already split
            >>> OBOObject.parse_tag_value("foo", "bar {modifier=frob} ! Comment")
            ('foo', 'bar', 'modifier=frob', 'Comment')

        .. warning: This function assumes comment an modifiers are prefixed
            with a whitespace i.e. 'tag: bla! comment' will be parsed
            incorrectly!

        """
        if arg is not None:  # tag_value_pair is actually a tag only
            tag = tag_value_pair
            value, modifiers, comment = cls._RE_VALUE.findall(arg)[0]
        else:
            tag, value, modifiers, comment = \
                cls._RE_TAG_VALUE.findall(tag_value_pair)[0]
        none_if_empyt = lambda val: None if not val.strip() else val.strip()
        modifiers = modifiers.strip(" {}")
        comment = comment.lstrip(" !")
        return (none_if_empyt(tag), none_if_empyt(value),
                none_if_empyt(modifiers), none_if_empyt(comment))

    def related_objects(self):
        """
        Return a list of tuple pairs where the first element is
        relationship (typedef id) and the second object id whom the
        relationship applies to.

        """
        result = [(type_id, id)
                  for type_id in ["is_a"]  # TODO add other defined Typedef ids
                  for id in self.values.get(type_id, [])]

        result = result + [tuple(r.split(None, 1))
                           for r in self.values.get("relationship", [])]
        return result

    def __repr__(self):
        """
        Return a string representation of the object in OBO format
        """
        return self.format_stanza()

    def __iter__(self):
        """
        Iterates over sub terms
        """
        return iter(self.related_objects())


class Term(OBOObject):
    """
    A 'Term' object in the ontology.
    """
    def __init__(self, *args, **kwargs):
        OBOObject.__init__(self, "Term", *args, **kwargs)


class Typedef(OBOObject):
    """
    A 'Typedef' object in the ontology.
    """
    def __init__(self, *args, **kwargs):
        OBOObject.__init__(self, "Typedef", *args, **kwargs)


class Instance(OBOObject):
    """
    An 'Instance' object in the ontology
    """
    def __init__(self, *args, **kwargs):
        OBOObject.__init__(self, "Instance", *args, **kwargs)


class OBOParser(object):
    r""" A simple parser for .obo files (inspired by xml.dom.pulldom)

    Example::

        >>> from StringIO import StringIO
        >>> file = StringIO("header_tag: header_value\n[Term]\nid: "
        ...                 "FOO { modifier=bar } ! comment\n\n")
        ...
        >>> parser = OBOParser(file)
        >>> for event, value in parser:
        ...     print event, value
        ...
        HEADER_TAG ['header_tag', 'header_value']
        START_STANZA Term
        TAG_VALUE ('id', 'FOO', 'modifier=bar', 'comment')
        CLOSE_STANZA None

    """
    def __init__(self, file):
        self.file = file

    def parse(self, progress_callback=None):
        """
        Parse the file and yield parse events.

        .. todo List events and values

        """
        data = self.file.read()
        header = data[: data.index("\n[")]
        body = data[data.index("\n[") + 1:]
        for line in header.splitlines():
            if line.strip():
                yield "HEADER_TAG", line.split(": ", 1)

        current = None
        #  For speed make these functions local
        startswith = str.startswith
        endswith = str.endswith
        parse_tag_value = OBOObject.parse_tag_value

        for line in body.splitlines():
            if startswith(line, "[") and endswith(line, "]"):
                yield "START_STANZA", line.strip("[]")
                current = line
            elif startswith(line, "!"):
                yield "COMMENT", line[1:]
            elif line:
                yield "TAG_VALUE", parse_tag_value(line)
            else:  # empty line is the end of a term
                yield "CLOSE_STANZA", None
                current = None
        if current is not None:
            yield "CLOSE_STANZA", None

    def __iter__(self):
        """
        Iterate over parse events (same as parse())
        """
        return self.parse()


class OBOOntology(object):
    """
    An class for representing OBO ontologies.

    :param file-like file:
        A optional file like object describing the ontology in obo format.

    """

    BUILTINS = BUILTIN_OBO_OBJECTS

    def __init__(self, file=None):
        """
        Initialize an ontology instance from a file like object (.obo format)
        """
        self.objects = []
        self.header_tags = []
        self.id2term = {}
        self.alt2id = {}
        self._resolved_imports = []
        self._invalid_cache_flag = False
        self._related_to = {}

        # First load the built in OBO objects
        builtins = StringIO("\n" + "\n\n".join(self.BUILTINS) + "\n")
        self.load(builtins)
        if file:
            self.load(file)

    def add_object(self, object):
        """
        Add an :class:`OBOObject` instance to this ontology.
        """
        if object.id in self.id2term:
            raise ValueError("OBOObject with id: %s already in "
                             "the ontology" % object.id)
        self.objects.append(object)
        self.id2term[object.id] = object
        self._invalid_cache_flag = True

    def add_header_tag(self, tag, value):
        """
        Add header tag, value pair to this ontology.
        """
        self.header_tags.append((tag, value))

    def load(self, file, progress_callback=None):
        """
        Load terms from a file.

        :param file-like file:
            A file-like like object describing the ontology in obo format.
        :param function progress_callback:
            An optional function callback to report on the progress.

        """
        if isinstance(file, basestring):
            file = open(file, "rb")

        parser = OBOParser(file)
        current = None
        for event, value in parser.parse(progress_callback=progress_callback):
            if event == "TAG_VALUE":
                current.add_tag(*value)
            elif event == "START_STANZA":
                current = OBOObject(value)
            elif event == "CLOSE_STANZA":
                self.add_object(current)
                current = None
            elif event == "HEADER_TAG":
                self.add_header_tag(*value)
            elif event != "COMMENT":
                raise Exception("Parse Error! Unknown parse "
                                "event {0}".format(event))

        imports = [value for tag, value in self.header_tags
                   if tag == "import"]

        if imports:
            warnings.warn("Import header tags are not supported")

#        while imports:
#            url = imports.pop(0)
#            if uri not in self._resolved_imports:
#                imported = self.parse_file(open(url, "rb"))
#                ontology.update(imported)
#                self._resolved_imports.append(uri)

    def dump(self, file):
        """
        Dump the contents of the ontology to a `file` in .obo format.

        :param file-like file:
            A file like object.

        """
        if isinstance(file, basestring):
            file = open(file, "wb")

        for key, value in self.header_tags:
            file.write(key + ": " + value + "\n")

        # Skip the builtins
        for object in self.objects[len(self.BUILTINS):]:
            file.write("\n")
            file.write(object.format_stanza())
            file.write("\n")

    def update(self, other):
        """
        Update this ontology with the terms from `other`.
        """
        for term in other:
            if term.id in self:
                if not term.is_annonymous:
                    self.term(term.id).update(term)
                else:  # Do nothing
                    pass
            else:
                self.add_object(term)
        self._invalid_cache_flag = True

    def _cache_validate(self, force=False):
        """
        Update the relations cache if `self._invalid_cache` flag is set.
        """
        if self._invalid_cache_flag or force:
            self._cache_relations()

    def _cache_relations(self):
        """
        Collect all relations from parent to a child and store it in
        `self._related_to` member.

        """
        related_to = defaultdict(list)
        for obj in self.objects:
            for rel_type, id in self.related_terms(obj):
                term = self.term(id)
                related_to[term].append((rel_type, obj))

        self._related_to = related_to
        self._invalid_cache_flag = False

    def term(self, id):
        """
        Return the :class:`OBOObject` associated with this id.

        :param str id:
            Term id string.

        """
        if isinstance(id, basestring):
            if id in self.id2term:
                return self.id2term[id]
            elif id in self.alt2id:
                return self.id2term[self.alt2id[id]]
            else:
                raise ValueError("Unknown term id: %r" % id)
        elif isinstance(id, OBOObject):
            return id

    def terms(self):
        """
        Return all :class:`Term` instances in the ontology.
        """
        return [obj for obj in self.objects if obj.stanza_type == "Term"]

    def term_by_name(self, name):
        """
        Return the term with name `name`.
        """
        terms = [t for t in self.terms() if t.name == name]
        if len(terms) != 1:
            raise ValueError("Unknown term name: %r" % name)
        return terms[0]

    def typedefs(self):
        """
        Return all :class:`Typedef` instances in the ontology.
        """
        return [obj for obj in self.objects if obj.stanza_type == "Typedef"]

    def instances(self):
        """
        Return all :class:`Instance` instances in the ontology.
        """
        return [obj for obj in self.objects if obj.stanza_type == "Instance"]

    def related_terms(self, term):
        """
        Return a list of (`rel_type`, `term_id`) tuples where `rel_type` is
        relationship type (e.g. 'is_a', 'has_part', ...) and `term_id` is
        the id of the term in the relationship.

        """
        term = self.term(term) if not isinstance(term, OBOObject) else term
        related = [(tag, value)
                   for tag in ["is_a"]  # TODO: add other typedef ids
                   for value in term.values.get(tag, [])]
        relationships = term.values.get("relationship", [])
        for rel in relationships:
            related.append(tuple(rel.split(None, 1)))
        return related

    def edge_types(self):
        """
        Return a list of all edge types in the ontology.
        """
        return [obj.id for obj in self.objects if obj.stanza_type == "Typedef"]

    def parent_edges(self, term):
        """
        Return a list of (rel_type, parent_term) tuples.
        """
        term = self.term(term)
        parents = []
        for rel_type, parent in self.related_terms(term):
            parents.append((rel_type, self.term(parent)))
        return parents

    def child_edges(self, term):
        """
        Return a list of (rel_type, source_term) tuples.
        """
        self._cache_validate()
        term = self.term(term)
        return self._related_to.get(term, [])

    def super_terms(self, term):
        """
        Return a set of all super terms of `term` up to the most general one.
        """
        terms = self.parent_terms(term)
        visited = set()
        queue = set(terms)
        while queue:
            term = queue.pop()
            visited.add(term)
            queue.update(self.parent_terms(term) - visited)
        return visited

    def sub_terms(self, term):
        """
        Return a set of all sub terms for `term`.
        """
        terms = self.child_terms(term)
        visited = set()
        queue = set(terms)
        while queue:
            term = queue.pop()
            visited.add(term)
            queue.update(self.child_terms(term) - visited)
        return visited

    def child_terms(self, term):
        """
        Return a set of all child terms for this `term`.
        """
        self._cache_validate()
        term = self.term(term)
        children = []
        for rel_type, term in self.child_edges(term):
            children.append(term)
        return set(children)

    def parent_terms(self, term):
        """
        Return a set of all parent terms for this `term`
        """
        term = self.term(term)
        parents = []
        for rel_type, id in self.parent_edges(term):
            parents.append(self.term(id))
        return set(parents)

    def relations(self):
        """
        Return a list of all relations in the ontology.
        """
        relations = []
        for obj in self.objects:
            for type_id, id in  obj.related:
                target_term = self.term(id)
            relations.append((obj, type_id, target_term))
        return relations

    def __len__(self):
        return len(self.objects)

    def __iter__(self):
        return iter(self.objects)

    def __contains__(self, obj):
        if isinstance(obj, basestring):
            return obj in self.id2term
        else:
            return obj in self.objects

    def __getitem__(self, key):
        return self.id2term[key]

    def has_key(self, key):
        return key in self.id2term

    def traverse_bf(self, term):
        """
        BF traverse of the ontology down from term.
        """
        queue = list(self.child_terms(term))
        while queue:
            term = queue.pop(0)
            queue.extend(self.child_terms(term))
            yield term

    def traverse_df(self, term, depth=1e30):
        """
        DF traverse of the ontology down from term.
        """
        if depth >= 1:
            for child in self.child_terms(term):
                yield child
                for t in self.traverse_df(child, depth - 1):
                    yield t

    def to_network(self, terms=None):
        """
        Return an Orange.network.Network instance constructed from
        this ontology.

        """
        edge_types = self.edge_types()
        terms = self.terms()
        from Orange.orng import orngNetwork
        import orange

        network = orngNetwork.Network(len(terms), True, len(edge_types))
        network.objects = dict([(term.id, i) for i, term in enumerate(terms)])

        edges = defaultdict(set)
        for term in self.terms():
            related = self.related_terms(term)
            for relType, relTerm in related:
                edges[(term.id, relTerm)].add(relType)

        edgeitems = edges.items()
        for (src, dst), eTypes in edgeitems:
            network[src, dst] = [1 if e in eTypes else 0 for e in edge_types]

        domain = orange.Domain([orange.StringVariable("id"),
                                orange.StringVariable("name"),
                                orange.StringVariable("def"),
                                ], False)

        items = orange.ExampleTable(domain)
        for term in terms:
            ex = orange.Example(domain, [term.id, term.name, term.values.get("def", [""])[0]])
            items.append(ex)

        relationships = set([", ".join(sorted(eTypes)) for (_, _), eTypes in edgeitems])
        domain = orange.Domain([orange.FloatVariable("u"),
                                orange.FloatVariable("v"),
                                orange.EnumVariable("relationship", values=list(edge_types))
                                ], False)

        id2index = dict([(term.id, i + 1) for i, term in enumerate(terms)])
        links = orange.ExampleTable(domain)
        for (src, dst), eTypes in edgeitems:
            ex = orange.Example(domain, [id2index[src], id2index[dst], eTypes.pop()])
            links.append(ex)

        network.items = items
        network.links = links
        network.optimization = None
        return network

    def to_networkx(self, terms=None):
        """
        Return a NetworkX graph of this ontology.
        """
        import networkx
        graph = networkx.Graph()

        edge_types = self.edge_types()

        edge_colors = {"is_a": "red"}

        if terms is None:
            terms = self.terms()
        else:
            terms = [self.term(term) for term in terms]
            super_terms = [self.super_terms(term) for term in terms]
            terms = reduce(set.union, super_terms, set(terms))

        for term in terms:
            graph.add_node(term.id, name=term.name)

        for term in terms:
            for rel_type, rel_term in self.related_terms(term):
                rel_term = self.term(rel_term)
                if rel_term in terms:
                    graph.add_edge(term.id, rel_term.id, label=rel_type,
                                   color=edge_colors.get(rel_type, "blue"))

        return graph

    def to_graphviz(self, terms=None):
        """
        Return an pygraphviz.AGraph representation of the ontology.
        If `terms` is not `None` it must be a list of terms in the ontology.
        The graph will in this case contain only the super graph of those
        terms.

        """
        import pygraphviz as pgv
        graph = pgv.AGraph(directed=True, name="ontology")

        edge_types = self.edge_types()

        edge_colors = {"is_a": "red"}

        if terms is None:
            terms = self.terms()
        else:
            terms = [self.term(term) for term in terms]
            super_terms = [self.super_terms(term) for term in terms]
            terms = reduce(set.union, super_terms, set(terms))

        for term in terms:
            graph.add_node(term.id, name=term.name)

        for term in terms:
            for rel_type, rel_term in self.related_terms(term):
                rel_term = self.term(rel_term)
                if rel_term in terms:
                    graph.add_edge(term.id, rel_term.id, label=rel_type,
                                   color=edge_colors.get(rel_type, "blue"))

        return graph


def load(file):
    """
    Load an ontology from a .obo file
    """
    return OBOOntology(file)


def foundry_ontologies():
    """
    Return a list of ontologies available from the OBOFoundry `website
    <http://www.obofoundry.org/>`_. The list contains a tuples of the form
    `(title, url)` for instance
    ``('Biological process', 'http://purl.obolibrary.org/obo/go.obo')``

    """
    stream = urllib2.urlopen("http://www.obofoundry.org/")
    text = stream.read()
    pattern = r'<td class=".+?">\s*<a href=".+?">(.+?)</a>\s*</td>\s*<td class=".+?">.*?</td>\s*<td class=".+?">.*?</td>\s*?<td class=".+?">\s*<a href="(.+?obo)">.+?</a>'
    return re.findall(pattern, text)


if __name__ == "__main__":
    import doctest
    stanza = '''[Term]
id: FOO:001
name: bar
'''
    seinfeld = StringIO("""
[Typedef]
id: parent

[Typedef]
id: child
inverse_of: parent ! not actually used yet

[Term]
id: 001
name: George

[Term]
id: 002
name: Estelle
relationship: parent 001 ! George

[Term]
id: 003
name: Frank
relationship: parent 001 ! George

""")  # TODO: fill the ontology with all characters
    term = OBOObject.parse_stanza(stanza)

    seinfeld = OBOOntology(seinfeld)
    print seinfeld.child_edges("001")

    doctest.testmod(extraglobs={"stanza": stanza, "term": term},
                    optionflags=doctest.ELLIPSIS)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.