Skip to content

infixowl

RDFLib Python binding for OWL Abstract Syntax

OWL Constructor DL Syntax Manchester OWL Syntax Example
intersectionOf C ∩ D C AND D Human AND Male
unionOf C ∪ D C OR D Man OR Woman
complementOf ¬C NOT C NOT Male
oneOf {a} ∪ {b}… {a b …} {England Italy Spain}
someValuesFrom ∃ R C R SOME C hasColleague SOME Professor
allValuesFrom ∀ R C R ONLY C hasColleague ONLY Professor
minCardinality ≥ N R R MIN 3 hasColleague MIN 3
maxCardinality ≤ N R R MAX 3 hasColleague MAX 3
cardinality = N R R EXACTLY 3 hasColleague EXACTLY 3
hasValue ∃ R.{a} R VALUE a hasColleague VALUE Matthew

See: - http://www.w3.org/TR/owl-semantics/syntax.html - http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf

3.2.3 Axioms for complete classes without using owl:equivalentClass

Named class description of type 2 (with owl:oneOf) or type 4-6 (with owl:intersectionOf, owl:unionOf or owl:complementOf

Uses Manchester Syntax for __repr__

>>> exNs = Namespace("http://example.com/")
>>> g = Graph()
>>> g.bind("ex", exNs, override=False)

Now we have an empty graph, we can construct OWL classes in it using the Python classes defined in this module

>>> a = Class(exNs.Opera, graph=g)

Now we can assert rdfs:subClassOf and owl:equivalentClass relationships (in the underlying graph) with other classes using the ‘subClassOf’ and ‘equivalentClass’ descriptors which can be set to a list of objects for the corresponding predicates.

>>> a.subClassOf = [exNs.MusicalWork]

We can then access the rdfs:subClassOf relationships

>>> print(list(a.subClassOf))
[Class: ex:MusicalWork ]

This can also be used against already populated graphs:

>>> owlGraph = Graph().parse(str(OWL))
>>> list(Class(OWL.Class, graph=owlGraph).subClassOf)
[Class: rdfs:Class ]

Operators are also available. For instance we can add ex:Opera to the extension of the ex:CreativeWork class via the ‘+=’ operator

>>> a
Class: ex:Opera SubClassOf: ex:MusicalWork
>>> b = Class(exNs.CreativeWork, graph=g)
>>> b += a
>>> print(sorted(a.subClassOf, key=lambda c:c.identifier))
[Class: ex:CreativeWork , Class: ex:MusicalWork ]

And we can then remove it from the extension as well

>>> b -= a
>>> a
Class: ex:Opera SubClassOf: ex:MusicalWork

Boolean class constructions can also be created with Python operators. For example, The | operator can be used to construct a class consisting of a owl:unionOf the operands:

>>> c =  a | b | Class(exNs.Work, graph=g)
>>> c
( ex:Opera OR ex:CreativeWork OR ex:Work )

Boolean class expressions can also be operated as lists (using python list operators)

>>> del c[c.index(Class(exNs.Work, graph=g))]
>>> c
( ex:Opera OR ex:CreativeWork )

The ‘&’ operator can be used to construct class intersection:

>>> woman = Class(exNs.Female, graph=g) & Class(exNs.Human, graph=g)
>>> woman.identifier = exNs.Woman
>>> woman
( ex:Female AND ex:Human )
>>> len(woman)
2

Enumerated classes can also be manipulated

>>> contList = [Class(exNs.Africa, graph=g), Class(exNs.NorthAmerica, graph=g)]
>>> EnumeratedClass(members=contList, graph=g)
{ ex:Africa ex:NorthAmerica }

owl:Restrictions can also be instantiated:

>>> Restriction(exNs.hasParent, graph=g, allValuesFrom=exNs.Human)
( ex:hasParent ONLY ex:Human )

Restrictions can also be created using Manchester OWL syntax in ‘colloquial’ Python

>>> exNs.hasParent @ some @ Class(exNs.Physician, graph=g)
( ex:hasParent SOME ex:Physician )
>>> Property(exNs.hasParent, graph=g) @ max @ Literal(1)
( ex:hasParent MAX 1 )
>>> print(g.serialize(format='pretty-xml'))  # doctest: +SKIP

Classes:

Functions:

Attributes:

ACE_NS module-attribute

ACE_NS = Namespace('http://attempto.ifi.uzh.ch/ace_lexicon#')

BooleanPredicates module-attribute

BooleanPredicates = [intersectionOf, unionOf]

CLASS_RELATIONS module-attribute

CLASS_RELATIONS = difference([onProperty, allValuesFrom, hasValue, someValuesFrom, inverseOf, imports, versionInfo, backwardCompatibleWith, incompatibleWith, unionOf, intersectionOf, oneOf])

PropertyAbstractSyntax module-attribute

PropertyAbstractSyntax = "\n%s( %s { %s }\n%s\n{ 'super(' datavaluedPropertyID ')'} ['Functional']\n{ domain( %s ) } { range( %s ) } )"

__all__ module-attribute

__all__ = ['ACE_NS', 'AllClasses', 'AllDifferent', 'AllProperties', 'AnnotatableTerms', 'BooleanClass', 'CLASS_RELATIONS', 'Callable', 'CastClass', 'Class', 'ClassNamespaceFactory', 'CommonNSBindings', 'ComponentTerms', 'DeepClassClear', 'EnumeratedClass', 'GetIdentifiedClasses', 'Individual', 'Infix', 'MalformedClass', 'MalformedClassError', 'OWLRDFListProxy', 'Ontology', 'Property', 'PropertyAbstractSyntax', 'Restriction', 'classOrIdentifier', 'classOrTerm', 'exactly', 'generateQName', 'manchesterSyntax', 'max', 'min', 'nsBinds', 'only', 'propertyOrIdentifier', 'some', 'value']

exactly module-attribute

exactly = Infix(lambda prop, _class: Restriction(prop, graph=graph, cardinality=_class))

logger module-attribute

logger = getLogger(__name__)

From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122

Python has the wonderful “in” operator and it would be nice to have additional infix operator like this. This recipe shows how (almost) arbitrary infix operators can be defined.

max module-attribute

max = Infix(lambda prop, _class: Restriction(prop, graph=graph, maxCardinality=_class))

min module-attribute

min = Infix(lambda prop, _class: Restriction(prop, graph=graph, minCardinality=_class))

nsBinds module-attribute

nsBinds = {'skos': 'http://www.w3.org/2004/02/skos/core#', 'rdf': RDF, 'rdfs': RDFS, 'owl': OWL, 'list': URIRef('http://www.w3.org/2000/10/swap/list#'), 'dc': 'http://purl.org/dc/elements/1.1/'}

only module-attribute

only = Infix(lambda prop, _class: Restriction(prop, graph=graph, allValuesFrom=_class))

some module-attribute

some = Infix(lambda prop, _class: Restriction(prop, graph=graph, someValuesFrom=_class))

value module-attribute

value = Infix(lambda prop, _class: Restriction(prop, graph=graph, value=_class))

AnnotatableTerms

AnnotatableTerms(identifier, graph=None, nameAnnotation=None, nameIsLabel=False)

Bases: Individual

Terms in an OWL ontology with rdfs:label and rdfs:comment

Interface with ATTEMPTO (http://attempto.ifi.uzh.ch/site)

Verbalisation of OWL entity IRIS

How are OWL entity IRIs verbalized?

The OWL verbalizer maps OWL entity IRIs to ACE content words such that

  • OWL individuals map to ACE proper names (PN)
  • OWL classes map to ACE common nouns (CN)
  • OWL properties map to ACE transitive verbs (TV)

There are 6 morphological categories that determine the surface form of an IRI:

  • singular form of a proper name (e.g. John)
  • singular form of a common noun (e.g. man)
  • plural form of a common noun (e.g. men)
  • singular form of a transitive verb (e.g. mans)
  • plural form of a transitive verb (e.g. man)
  • past participle form a transitive verb (e.g. manned)

The user has full control over the eventual surface forms of the IRIs but has to choose them in terms of the above categories. Furthermore,

  • the surface forms must be legal ACE content words (e.g. they should not contain punctuation symbols);
  • the mapping of IRIs to surface forms must be bidirectional within the same word class, in order to be able to (if needed) parse the verbalization back into OWL in a semantics preserving way.
Using the lexicon

It is possible to specify the mapping of IRIs to surface forms using the following annotation properties:

http://attempto.ifi.uzh.ch/ace_lexicon#PN_sg
http://attempto.ifi.uzh.ch/ace_lexicon#CN_sg
http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl
http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg

For example, the following axioms state that if the IRI “#man” is used as a plural common noun, then the wordform men must be used by the verbalizer. If, however, it is used as a singular transitive verb, then mans must be used.

<AnnotationAssertion>
    <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl"/>
    <IRI>#man</IRI>
    <Literal datatypeIRI="&xsd;string">men</Literal>
</AnnotationAssertion>

<AnnotationAssertion>
    <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg"/>
    <IRI>#man</IRI>
    <Literal datatypeIRI="&xsd;string">mans</Literal>
</AnnotationAssertion>

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(
    self,
    identifier,
    graph=None,
    nameAnnotation=None,  # noqa: N803
    nameIsLabel=False,  # noqa: N803
):
    super(AnnotatableTerms, self).__init__(identifier, graph)
    if nameAnnotation:
        self.setupACEAnnotations()
        self.PN_sgprop.extent = [
            (self.identifier, self.handleAnnotation(nameAnnotation))
        ]
        if nameIsLabel:
            self.label = [nameAnnotation]

comment class-attribute instance-attribute

comment = property(_get_comment, _set_comment, _del_comment)

label class-attribute instance-attribute

label = property(_get_label, _set_label, _delete_label)

seeAlso class-attribute instance-attribute

seeAlso = property(_get_seealso, _set_seealso, _del_seealso)

handleAnnotation

handleAnnotation(val)
Source code in rdflib/extras/infixowl.py
def handleAnnotation(self, val):  # noqa: N802
    return val if isinstance(val, Literal) else Literal(val)

setupACEAnnotations

setupACEAnnotations()
Source code in rdflib/extras/infixowl.py
def setupACEAnnotations(self):  # noqa: N802
    self.graph.bind("ace", ACE_NS, override=False)

    # PN_sg singular form of a proper name ()
    self.PN_sgprop = Property(
        ACE_NS.PN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
    )

    # CN_sg singular form of a common noun
    self.CN_sgprop = Property(
        ACE_NS.CN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
    )

    # CN_pl plural form of a common noun
    self.CN_plprop = Property(
        ACE_NS.CN_pl, baseType=OWL.AnnotationProperty, graph=self.graph
    )

    # singular form of a transitive verb
    self.tv_sgprop = Property(
        ACE_NS.TV_sg, baseType=OWL.AnnotationProperty, graph=self.graph
    )

    # plural form of a transitive verb
    self.tv_plprop = Property(
        ACE_NS.TV_pl, baseType=OWL.AnnotationProperty, graph=self.graph
    )

    # past participle form a transitive verb
    self.tv_vbgprop = Property(
        ACE_NS.TV_vbg, baseType=OWL.AnnotationProperty, graph=self.graph
    )

BooleanClass

BooleanClass(identifier=None, operator=intersectionOf, members=None, graph=None)

Bases: OWLRDFListProxy, Class

See: http://www.w3.org/TR/owl-ref/#Boolean

owl:complementOf is an attribute of Class, however

Methods:

  • __or__

    Adds other to the list and returns self

  • __repr__

    Returns the Manchester Syntax equivalent for this class

  • changeOperator

    Converts a unionOf / intersectionOf class expression into one

  • copy

    Create a copy of this class

  • isPrimitive
  • serialize

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(
    self, identifier=None, operator=OWL.intersectionOf, members=None, graph=None
):
    if operator is None:
        props = []
        for _s, p, _o in graph.triples_choices(
            (identifier, [OWL.intersectionOf, OWL.unionOf], None)
        ):
            props.append(p)
            operator = p
        assert len(props) == 1, repr(props)
    Class.__init__(self, identifier, graph=graph)
    assert operator in [OWL.intersectionOf, OWL.unionOf], str(operator)
    self._operator = operator
    rdf_list = list(self.graph.objects(predicate=operator, subject=self.identifier))
    assert (
        not members or not rdf_list
    ), "This is a previous boolean class description."
    OWLRDFListProxy.__init__(self, rdf_list, members)

getIntersections class-attribute instance-attribute

getIntersections = Callable(getIntersections)

getUnions class-attribute instance-attribute

getUnions = Callable(getUnions)

__or__

__or__(other)

Adds other to the list and returns self

Source code in rdflib/extras/infixowl.py
def __or__(self, other):
    """
    Adds other to the list and returns self
    """
    assert self._operator == OWL.unionOf
    self._rdfList.append(classOrIdentifier(other))
    return self

__repr__

__repr__()

Returns the Manchester Syntax equivalent for this class

Source code in rdflib/extras/infixowl.py
def __repr__(self):
    """
    Returns the Manchester Syntax equivalent for this class
    """
    return manchesterSyntax(
        self._rdfList.uri if isinstance(self._rdfList, Collection) else BNode(),
        self.graph,
        boolean=self._operator,
    )

changeOperator

changeOperator(newOperator)

Converts a unionOf / intersectionOf class expression into one that instead uses the given operator

>>> testGraph = Graph()
>>> Individual.factoryGraph = testGraph
>>> EX = Namespace("http://example.com/")
>>> testGraph.bind("ex", EX, override=False)
>>> fire = Class(EX.Fire)
>>> water = Class(EX.Water)
>>> testClass = BooleanClass(members=[fire,water])
>>> testClass
( ex:Fire AND ex:Water )
>>> testClass.changeOperator(OWL.unionOf)
>>> testClass
( ex:Fire OR ex:Water )
>>> try:
...     testClass.changeOperator(OWL.unionOf)
... except Exception as e:
...     print(e)  # doctest: +SKIP
The new operator is already being used!
Source code in rdflib/extras/infixowl.py
def changeOperator(self, newOperator):  # noqa: N802, N803
    """
    Converts a unionOf / intersectionOf class expression into one
    that instead uses the given operator

    ```python
    >>> testGraph = Graph()
    >>> Individual.factoryGraph = testGraph
    >>> EX = Namespace("http://example.com/")
    >>> testGraph.bind("ex", EX, override=False)
    >>> fire = Class(EX.Fire)
    >>> water = Class(EX.Water)
    >>> testClass = BooleanClass(members=[fire,water])
    >>> testClass
    ( ex:Fire AND ex:Water )
    >>> testClass.changeOperator(OWL.unionOf)
    >>> testClass
    ( ex:Fire OR ex:Water )
    >>> try:
    ...     testClass.changeOperator(OWL.unionOf)
    ... except Exception as e:
    ...     print(e)  # doctest: +SKIP
    The new operator is already being used!

    ```
    """
    assert newOperator != self._operator, "The new operator is already being used!"
    self.graph.remove((self.identifier, self._operator, self._rdfList.uri))
    self.graph.add((self.identifier, newOperator, self._rdfList.uri))
    self._operator = newOperator

copy

copy()

Create a copy of this class

Source code in rdflib/extras/infixowl.py
def copy(self):
    """
    Create a copy of this class
    """
    copy_of_class = BooleanClass(
        operator=self._operator, members=list(self), graph=self.graph
    )
    return copy_of_class

isPrimitive

isPrimitive()
Source code in rdflib/extras/infixowl.py
def isPrimitive(self):  # noqa: N802
    return False

serialize

serialize(graph)
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    clonedlist = Collection(graph, BNode())
    for cl in self._rdfList:
        clonedlist.append(cl)
        CastClass(cl, self.graph).serialize(graph)

    graph.add((self.identifier, self._operator, clonedlist.uri))

    for s, p, o in self.graph.triples((self.identifier, None, None)):
        if p != self._operator:
            graph.add((s, p, o))
    self._serialize(graph)

BooleanClassExtentHelper

BooleanClassExtentHelper(operator)
>>> testGraph = Graph()
>>> Individual.factoryGraph = testGraph
>>> EX = Namespace("http://example.com/")
>>> testGraph.bind("ex", EX, override=False)
>>> fire = Class(EX.Fire)
>>> water = Class(EX.Water)
>>> testClass = BooleanClass(members=[fire, water])
>>> testClass2 = BooleanClass(
...     operator=OWL.unionOf, members=[fire, water])
>>> for c in BooleanClass.getIntersections():
...     print(c)  # doctest: +SKIP
( ex:Fire AND ex:Water )
>>> for c in BooleanClass.getUnions():
...     print(c) #doctest: +SKIP
( ex:Fire OR ex:Water )

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, operator):
    self.operator = operator

operator instance-attribute

operator = operator

__call__

__call__(f)
Source code in rdflib/extras/infixowl.py
def __call__(self, f):
    def _getExtent():  # noqa: N802
        for c in Individual.factoryGraph.subjects(self.operator):
            yield BooleanClass(c, operator=self.operator)

    return _getExtent

Callable

Callable(anycallable)

Methods:

Source code in rdflib/extras/infixowl.py
def __init__(self, anycallable):
    self._callfn = anycallable

__call__

__call__(*args, **kwargs)
Source code in rdflib/extras/infixowl.py
def __call__(self, *args, **kwargs):
    return self._callfn(*args, **kwargs)

Class

Class(identifier=None, subClassOf=None, equivalentClass=None, disjointWith=None, complementOf=None, graph=None, skipOWLClassMembership=False, comment=None, nounAnnotations=None, nameAnnotation=None, nameIsLabel=False)

Bases: AnnotatableTerms

‘General form’ for classes:

The Manchester Syntax (supported in Protege) is used as the basis for the form of this class

See: http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf:

[Annotation]
‘Class:’ classID {Annotation
( (‘SubClassOf:’ ClassExpression)
| (‘EquivalentTo’ ClassExpression)
| (’DisjointWith’ ClassExpression)) }

Appropriate excerpts from OWL Reference:

”.. Subclass axioms provide us with partial definitions: they represent necessary but not sufficient conditions for establishing class membership of an individual.”

”.. A class axiom may contain (multiple) owl:equivalentClass statements”

”..A class axiom may also contain (multiple) owl:disjointWith statements..”

”..An owl:complementOf property links a class to precisely one class description.”

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(
    self,
    identifier=None,
    subClassOf=None,  # noqa: N803
    equivalentClass=None,  # noqa: N803
    disjointWith=None,  # noqa: N803
    complementOf=None,  # noqa: N803
    graph=None,
    skipOWLClassMembership=False,  # noqa: N803
    comment=None,
    nounAnnotations=None,  # noqa: N803
    nameAnnotation=None,  # noqa: N803
    nameIsLabel=False,  # noqa: N803
):
    super(Class, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)

    if nounAnnotations:
        self.setupNounAnnotations(nounAnnotations)
    if (
        not skipOWLClassMembership
        and (self.identifier, RDF.type, OWL.Class) not in self.graph
        and (self.identifier, RDF.type, OWL.Restriction) not in self.graph
    ):
        self.graph.add((self.identifier, RDF.type, OWL.Class))

    self.subClassOf = [] if subClassOf is None else subClassOf
    self.equivalentClass = [] if equivalentClass is None else equivalentClass
    self.disjointWith = [] if disjointWith is None else disjointWith
    if complementOf:
        self.complementOf = complementOf
    self.comment = [] if comment is None else comment

annotation class-attribute instance-attribute

annotation = property(_get_annotation, lambda x: x)

comment instance-attribute

comment = [] if comment is None else comment

complementOf class-attribute instance-attribute

complementOf = property(_get_complementof, _set_complementof, _del_complementof)

disjointWith class-attribute instance-attribute

disjointWith = property(_get_disjointwith, _set_disjointwith, _del_disjointwith)

equivalentClass class-attribute instance-attribute

equivalentClass = property(_get_equivalentclass, _set_equivalentclass, _del_equivalentclass)

extent class-attribute instance-attribute

extent = property(_get_extent, _set_extent, _del_type)

extentQuery class-attribute instance-attribute

extentQuery = property(_get_extentquery, _set_extentquery)

parents class-attribute instance-attribute

parents = property(_get_parents)

subClassOf class-attribute instance-attribute

subClassOf = property(_get_subclassof, _set_subclassof, _del_subclassof)

__and__

__and__(other)

Construct an anonymous class description consisting of the intersection of this class and ‘other’ and return it

Chaining 3 intersections

>>> exNs = Namespace("http://example.com/")
>>> g = Graph()
>>> g.bind("ex", exNs, override=False)
>>> female = Class(exNs.Female, graph=g)
>>> human = Class(exNs.Human, graph=g)
>>> youngPerson = Class(exNs.YoungPerson, graph=g)
>>> youngWoman = female & human & youngPerson
>>> youngWoman  # doctest: +SKIP
ex:YoungPerson THAT ( ex:Female AND ex:Human )
>>> isinstance(youngWoman, BooleanClass)
True
>>> isinstance(youngWoman.identifier, BNode)
True
Source code in rdflib/extras/infixowl.py
def __and__(self, other):
    """
    Construct an anonymous class description consisting of the
    intersection of this class and 'other' and return it

    Chaining 3 intersections

    ```python
    >>> exNs = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", exNs, override=False)
    >>> female = Class(exNs.Female, graph=g)
    >>> human = Class(exNs.Human, graph=g)
    >>> youngPerson = Class(exNs.YoungPerson, graph=g)
    >>> youngWoman = female & human & youngPerson
    >>> youngWoman  # doctest: +SKIP
    ex:YoungPerson THAT ( ex:Female AND ex:Human )
    >>> isinstance(youngWoman, BooleanClass)
    True
    >>> isinstance(youngWoman.identifier, BNode)
    True

    ```
    """
    return BooleanClass(
        operator=OWL.intersectionOf, members=[self, other], graph=self.graph
    )

__eq__

__eq__(other)
Source code in rdflib/extras/infixowl.py
def __eq__(self, other):
    assert isinstance(other, Class), repr(other)
    return self.identifier == other.identifier

__hash__

__hash__()

b = Class(OWL.Restriction) c = Class(OWL.Restriction) len(set([b,c])) 1

Source code in rdflib/extras/infixowl.py
def __hash__(self):
    """
    >>> b = Class(OWL.Restriction)
    >>> c = Class(OWL.Restriction)
    >>> len(set([b,c]))
    1
    """
    return hash(self.identifier)

__iadd__

__iadd__(other)
Source code in rdflib/extras/infixowl.py
def __iadd__(self, other):
    assert isinstance(other, Class)
    other.subClassOf = [self]
    return self

__invert__

__invert__()

Shorthand for Manchester syntax’s not operator

Source code in rdflib/extras/infixowl.py
def __invert__(self):
    """
    Shorthand for Manchester syntax's not operator
    """
    return Class(complementOf=self)

__isub__

__isub__(other)
Source code in rdflib/extras/infixowl.py
def __isub__(self, other):
    assert isinstance(other, Class)
    self.graph.remove((classOrIdentifier(other), RDFS.subClassOf, self.identifier))
    return self

__or__

__or__(other)

Construct an anonymous class description consisting of the union of this class and ‘other’ and return it

Source code in rdflib/extras/infixowl.py
def __or__(self, other):
    """
    Construct an anonymous class description consisting of the union of
    this class and 'other' and return it
    """
    return BooleanClass(
        operator=OWL.unionOf, members=[self, other], graph=self.graph
    )

__repr__

__repr__()
Source code in rdflib/extras/infixowl.py
def __repr__(self):
    return self.manchesterClass(full=False, normalization=True)

isPrimitive

isPrimitive()
Source code in rdflib/extras/infixowl.py
def isPrimitive(self):  # noqa: N802
    if (self.identifier, RDF.type, OWL.Restriction) in self.graph:
        return False
    # sc = list(self.subClassOf)
    ec = list(self.equivalentClass)
    for _boolclass, p, rdf_list in self.graph.triples_choices(
        # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
        (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
    ):
        ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
    for _e in ec:
        return False
    if self.complementOf:
        return False
    return True

manchesterClass

manchesterClass(full=False, normalization=True)

Returns the Manchester Syntax equivalent for this class

Source code in rdflib/extras/infixowl.py
def manchesterClass(self, full=False, normalization=True):  # noqa: N802
    """
    Returns the Manchester Syntax equivalent for this class
    """
    exprs = []
    sc = list(self.subClassOf)
    ec = list(self.equivalentClass)
    for _boolclass, p, rdf_list in self.graph.triples_choices(
        # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
        (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
    ):
        ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
    dc = list(self.disjointWith)
    c = self.complementOf
    if c:
        dc.append(c)
    klasskind = ""
    label = list(self.graph.objects(self.identifier, RDFS.label))
    # type error: Incompatible types in assignment (expression has type "str", variable has type "List[Node]")
    # type error: Unsupported operand types for + ("str" and "Node")
    label = label and "(" + label[0] + ")" or ""  # type: ignore[assignment, operator]
    if sc:
        if full:
            scjoin = "\n                "
        else:
            scjoin = ", "
        nec_statements = [
            isinstance(s, Class)
            and isinstance(self.identifier, BNode)
            and repr(CastClass(s, self.graph))
            or
            # repr(BooleanClass(classOrIdentifier(s),
            #                  operator=None,
            #                  graph=self.graph)) or
            manchesterSyntax(classOrIdentifier(s), self.graph)
            for s in sc
        ]
        if nec_statements:
            klasskind = "Primitive Type %s" % label
        exprs.append(
            "SubClassOf: %s" % scjoin.join([str(n) for n in nec_statements])
        )
        if full:
            exprs[-1] = "\n    " + exprs[-1]
    if ec:
        nec_suff_statements = [
            isinstance(s, str)
            and s
            or manchesterSyntax(classOrIdentifier(s), self.graph)
            for s in ec
        ]
        if nec_suff_statements:
            klasskind = "A Defined Class %s" % label
        exprs.append("EquivalentTo: %s" % ", ".join(nec_suff_statements))
        if full:
            exprs[-1] = "\n    " + exprs[-1]
    if dc:
        exprs.append(
            "DisjointWith %s\n"
            % "\n                 ".join(
                [manchesterSyntax(classOrIdentifier(s), self.graph) for s in dc]
            )
        )
        if full:
            exprs[-1] = "\n    " + exprs[-1]
    descr = list(self.graph.objects(self.identifier, RDFS.comment))
    if full and normalization:
        klassdescr = (
            klasskind
            and "\n    ## %s ##" % klasskind
            + (descr and "\n    %s" % descr[0] or "")
            + " . ".join(exprs)
            or " . ".join(exprs)
        )
    else:
        klassdescr = (
            full
            and (descr and "\n    %s" % descr[0] or "")
            or "" + " . ".join(exprs)
        )
    return (
        isinstance(self.identifier, BNode)
        and "Some Class "
        or "Class: %s " % self.qname
    ) + klassdescr

serialize

serialize(graph)
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    for fact in self.graph.triples((self.identifier, None, None)):
        graph.add(fact)
    self._serialize(graph)

setupNounAnnotations

setupNounAnnotations(noun_annotations)
Source code in rdflib/extras/infixowl.py
def setupNounAnnotations(self, noun_annotations):  # noqa: N802
    if isinstance(noun_annotations, tuple):
        cn_sgprop, cn_plprop = noun_annotations
    else:
        cn_sgprop = noun_annotations
        cn_plprop = noun_annotations

    if cn_sgprop:
        self.CN_sgprop.extent = [
            (self.identifier, self.handleAnnotation(cn_sgprop))
        ]
    if cn_plprop:
        self.CN_plprop.extent = [
            (self.identifier, self.handleAnnotation(cn_plprop))
        ]

subSumpteeIds

subSumpteeIds()
Source code in rdflib/extras/infixowl.py
def subSumpteeIds(self):  # noqa: N802
    for s in self.graph.subjects(predicate=RDFS.subClassOf, object=self.identifier):
        yield s

ClassNamespaceFactory

Bases: Namespace

Methods:

__getattr__

__getattr__(name)
Source code in rdflib/extras/infixowl.py
def __getattr__(self, name):
    if name.startswith("__"):  # ignore any special Python names!
        raise AttributeError
    else:
        return self.term(name)

__getitem__

__getitem__(key, default=None)
Source code in rdflib/extras/infixowl.py
def __getitem__(self, key, default=None):
    return self.term(key)

term

term(name)
Source code in rdflib/extras/infixowl.py
def term(self, name):
    return Class(URIRef(self + name))

EnumeratedClass

EnumeratedClass(identifier=None, members=None, graph=None)

Bases: OWLRDFListProxy, Class

Class for owl:oneOf forms:

OWL Abstract Syntax is used

axiom ::= ‘EnumeratedClass(’ classID [‘Deprecated’] { annotation } { individualID } ‘)’

>>> exNs = Namespace("http://example.com/")
>>> g = Graph()
>>> g.bind("ex", exNs, override=False)
>>> Individual.factoryGraph = g
>>> ogbujiBros = EnumeratedClass(exNs.ogbujicBros,
...                              members=[exNs.chime,
...                                       exNs.uche,
...                                       exNs.ejike])
>>> ogbujiBros  # doctest: +SKIP
{ ex:chime ex:uche ex:ejike }
>>> col = Collection(g, first(
...    g.objects(predicate=OWL.oneOf, subject=ogbujiBros.identifier)))
>>> sorted([g.qname(item) for item in col])
['ex:chime', 'ex:ejike', 'ex:uche']
>>> print(g.serialize(format='n3'))  # doctest: +SKIP
@prefix ex: <http://example.com/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
<BLANKLINE>
ex:ogbujicBros a owl:Class;
    owl:oneOf ( ex:chime ex:uche ex:ejike ) .
<BLANKLINE>
<BLANKLINE>

Methods:

Source code in rdflib/extras/infixowl.py
def __init__(self, identifier=None, members=None, graph=None):
    Class.__init__(self, identifier, graph=graph)
    members = [] if members is None else members
    rdfList = list(  # noqa: N806
        self.graph.objects(predicate=OWL.oneOf, subject=self.identifier)
    )
    OWLRDFListProxy.__init__(self, rdfList, members)

__repr__

__repr__()

Returns the Manchester Syntax equivalent for this class

Source code in rdflib/extras/infixowl.py
def __repr__(self):
    """
    Returns the Manchester Syntax equivalent for this class
    """
    return manchesterSyntax(self._rdfList.uri, self.graph, boolean=self._operator)

isPrimitive

isPrimitive()
Source code in rdflib/extras/infixowl.py
def isPrimitive(self):  # noqa: N802
    return False

serialize

serialize(graph)
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    clonedlist = Collection(graph, BNode())
    for cl in self._rdfList:
        clonedlist.append(cl)
        CastClass(cl, self.graph).serialize(graph)

    graph.add((self.identifier, self._operator, clonedlist.uri))
    for s, p, o in self.graph.triples((self.identifier, None, None)):
        if p != self._operator:
            graph.add((s, p, o))
    self._serialize(graph)

Individual

Individual(identifier=None, graph=None)

A typed individual, the base class of the InfixOWL classes.

Methods:

  • clearInDegree

    Remove references to this individual as an object in the

  • clearOutDegree

    Remove all statements to this individual as a subject in the

  • delete

    Delete the individual from the graph, clearing the in and

  • replace

    Replace the individual in the graph with the given other,

  • serialize

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, identifier=None, graph=None):
    self.__identifier = identifier is not None and identifier or BNode()
    if graph is None:
        self.graph = self.factoryGraph
    else:
        self.graph = graph
    self.qname = None
    if not isinstance(self.identifier, BNode):
        try:
            prefix, uri, localname = self.graph.compute_qname(self.identifier)
            self.qname = ":".join([prefix, localname])
        except Exception:  # pragma: no cover
            pass  # pragma: no cover

__identifier instance-attribute

__identifier = identifier is not None and identifier or BNode()

factoryGraph class-attribute instance-attribute

factoryGraph = Graph()

graph instance-attribute

graph = factoryGraph

identifier class-attribute instance-attribute

identifier = property(_get_identifier, _set_identifier)

qname instance-attribute

qname = join([prefix, localname])

sameAs class-attribute instance-attribute

sameAs = property(_get_sameAs, _set_sameAs, _delete_sameAs)

type class-attribute instance-attribute

type = property(_get_type, _set_type, _delete_type)

clearInDegree

clearInDegree()

Remove references to this individual as an object in the backing store.

Source code in rdflib/extras/infixowl.py
def clearInDegree(self):  # noqa: N802
    """
    Remove references to this individual as an object in the
    backing store.
    """
    self.graph.remove((None, None, self.identifier))

clearOutDegree

clearOutDegree()

Remove all statements to this individual as a subject in the backing store. Note that this only removes the statements themselves, not the blank node closure so there is a chance that this will cause orphaned blank nodes to remain in the graph.

Source code in rdflib/extras/infixowl.py
def clearOutDegree(self):  # noqa: N802
    """
    Remove all statements to this individual as a subject in the
    backing store. Note that this only removes the statements
    themselves, not the blank node closure so there is a chance
    that this will cause orphaned blank nodes to remain in the
    graph.
    """
    self.graph.remove((self.identifier, None, None))

delete

delete()

Delete the individual from the graph, clearing the in and out degrees.

Source code in rdflib/extras/infixowl.py
def delete(self):
    """
    Delete the individual from the graph, clearing the in and
    out degrees.
    """
    self.clearInDegree()
    self.clearOutDegree()

replace

replace(other)

Replace the individual in the graph with the given other, causing all triples that refer to it to be changed and then delete the individual.

>>> g = Graph()
>>> b = Individual(OWL.Restriction, g)
>>> b.type = RDFS.Resource
>>> len(list(b.type))
1
>>> del b.type
>>> len(list(b.type))
0
Source code in rdflib/extras/infixowl.py
def replace(self, other):
    """
    Replace the individual in the graph with the given other,
    causing all triples that refer to it to be changed and then
    delete the individual.

    ```python
    >>> g = Graph()
    >>> b = Individual(OWL.Restriction, g)
    >>> b.type = RDFS.Resource
    >>> len(list(b.type))
    1
    >>> del b.type
    >>> len(list(b.type))
    0

    ```
    """
    for s, p, _o in self.graph.triples((None, None, self.identifier)):
        self.graph.add((s, p, classOrIdentifier(other)))
    self.delete()

serialize

serialize(graph)
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    for fact in self.factoryGraph.triples((self.identifier, None, None)):
        graph.add(fact)

Infix

Infix(function)

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, function):
    self.function = function

function instance-attribute

function = function

__call__

__call__(value1, value2)
Source code in rdflib/extras/infixowl.py
def __call__(self, value1, value2):
    return self.function(value1, value2)  # pragma: no cover

__matmul__

__matmul__(other)
Source code in rdflib/extras/infixowl.py
def __matmul__(self, other):
    return self.function(other)

__rlshift__

__rlshift__(other)
Source code in rdflib/extras/infixowl.py
def __rlshift__(self, other):
    return Infix(lambda x, self=self, other=other: self.function(other, x))

__rmatmul__

__rmatmul__(other)
Source code in rdflib/extras/infixowl.py
def __rmatmul__(self, other):
    return Infix(lambda x, self=self, other=other: self.function(other, x))

__rshift__

__rshift__(other)
Source code in rdflib/extras/infixowl.py
def __rshift__(self, other):
    return self.function(other)

MalformedClass

Bases: ValueError

Deprecated

This class will be removed in version 7.0.0.

MalformedClassError

MalformedClassError(msg)

Bases: MalformedClass

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, msg):
    self.msg = msg

msg instance-attribute

msg = msg

__repr__

__repr__()
Source code in rdflib/extras/infixowl.py
def __repr__(self):
    return self.msg

OWLRDFListProxy

OWLRDFListProxy(rdf_list, members=None, graph=None)

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, rdf_list, members=None, graph=None):
    if graph:
        self.graph = graph
    members = [] if members is None else members
    if rdf_list:
        self._rdfList = Collection(self.graph, rdf_list[0])
        for member in members:
            if member not in self._rdfList:
                self._rdfList.append(classOrIdentifier(member))
    else:
        self._rdfList = Collection(
            self.graph, BNode(), [classOrIdentifier(m) for m in members]
        )
        # type error: "OWLRDFListProxy" has no attribute "identifier"
        # type error: "OWLRDFListProxy" has no attribute "_operator"
        self.graph.add((self.identifier, self._operator, self._rdfList.uri))  # type: ignore[attr-defined]

graph instance-attribute

graph = graph

__contains__

__contains__(item)
Source code in rdflib/extras/infixowl.py
def __contains__(self, item):
    for i in self._rdfList:
        if i == classOrIdentifier(item):
            return 1
    return 0

__delitem__

__delitem__(key)
Source code in rdflib/extras/infixowl.py
def __delitem__(self, key):
    del self._rdfList[key]

__eq__

__eq__(other)

Equivalence of boolean class constructors is determined by equivalence of its members

Source code in rdflib/extras/infixowl.py
def __eq__(self, other):
    """
    Equivalence of boolean class constructors is determined by
    equivalence of its members
    """
    assert isinstance(other, Class), repr(other) + repr(type(other))
    if isinstance(other, BooleanClass):
        length = len(self)
        if length != len(other):
            return False
        else:
            for idx in range(length):
                if self[idx] != other[idx]:
                    return False
                return True
    else:
        # type error: "OWLRDFListProxy" has no attribute "identifier"
        return self.identifier == other.identifier  # type: ignore[attr-defined]

__getitem__

__getitem__(key)
Source code in rdflib/extras/infixowl.py
def __getitem__(self, key):
    return self._rdfList[key]

__iadd__

__iadd__(other)
Source code in rdflib/extras/infixowl.py
def __iadd__(self, other):
    self._rdfList.append(classOrIdentifier(other))
    return self

__iter__

__iter__()
Source code in rdflib/extras/infixowl.py
def __iter__(self):
    for item in self._rdfList:
        yield item

__len__

__len__()
Source code in rdflib/extras/infixowl.py
def __len__(self):
    return len(self._rdfList)

__setitem__

__setitem__(key, value)
Source code in rdflib/extras/infixowl.py
def __setitem__(self, key, value):
    self._rdfList[key] = classOrIdentifier(value)

append

append(item)
Source code in rdflib/extras/infixowl.py
def append(self, item):
    self._rdfList.append(item)

clear

clear()
Source code in rdflib/extras/infixowl.py
def clear(self):
    self._rdfList.clear()

index

index(item)
Source code in rdflib/extras/infixowl.py
def index(self, item):
    return self._rdfList.index(classOrIdentifier(item))

Ontology

Ontology(identifier=None, imports=None, comment=None, graph=None)

Bases: AnnotatableTerms

The owl ontology metadata

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, identifier=None, imports=None, comment=None, graph=None):
    super(Ontology, self).__init__(identifier, graph)
    self.imports = [] if imports is None else imports
    self.comment = [] if comment is None else comment
    if (self.identifier, RDF.type, OWL.Ontology) not in self.graph:
        self.graph.add((self.identifier, RDF.type, OWL.Ontology))

comment instance-attribute

comment = [] if comment is None else comment

imports class-attribute instance-attribute

imports = property(_get_imports, _set_imports, _del_imports)

setVersion

setVersion(version)
Source code in rdflib/extras/infixowl.py
def setVersion(self, version):  # noqa: N802
    self.graph.set((self.identifier, OWL.versionInfo, version))

Property

Property(identifier=None, graph=None, baseType=ObjectProperty, subPropertyOf=None, domain=None, range=None, inverseOf=None, otherType=None, equivalentProperty=None, comment=None, verbAnnotations=None, nameAnnotation=None, nameIsLabel=False)

Bases: AnnotatableTerms

axiom ::= 'DatatypeProperty(' datavaluedPropertyID ['Deprecated']
            { annotation }
            { 'super(' datavaluedPropertyID ')'} ['Functional']
            { 'domain(' description ')' } { 'range(' dataRange ')' } ')'
            | 'ObjectProperty(' individualvaluedPropertyID ['Deprecated']
            { annotation }
            { 'super(' individualvaluedPropertyID ')' }
            [ 'inverseOf(' individualvaluedPropertyID ')' ] [ 'Symmetric' ]
            [ 'Functional' | 'InverseFunctional' |
            'Functional' 'InverseFunctional' |
            'Transitive' ]
            { 'domain(' description ')' } { 'range(' description ')' } ')

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(
    self,
    identifier=None,
    graph=None,
    baseType=OWL.ObjectProperty,  # noqa: N803
    subPropertyOf=None,  # noqa: N803
    domain=None,
    range=None,
    inverseOf=None,  # noqa: N803
    otherType=None,  # noqa: N803
    equivalentProperty=None,  # noqa: N803
    comment=None,
    verbAnnotations=None,  # noqa: N803
    nameAnnotation=None,  # noqa: N803
    nameIsLabel=False,  # noqa: N803
):
    super(Property, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)
    if verbAnnotations:
        self.setupVerbAnnotations(verbAnnotations)

    assert not isinstance(self.identifier, BNode)
    if baseType is None:
        # None give, determine via introspection
        self._baseType = first(Individual(self.identifier, graph=self.graph).type)
    else:
        if (self.identifier, RDF.type, baseType) not in self.graph:
            self.graph.add((self.identifier, RDF.type, baseType))
        self._baseType = baseType
    self.subPropertyOf = subPropertyOf
    self.inverseOf = inverseOf
    self.domain = domain
    self.range = range
    self.comment = [] if comment is None else comment

comment instance-attribute

comment = [] if comment is None else comment

domain class-attribute instance-attribute

domain = property(_get_domain, _set_domain, _del_domain)

extent class-attribute instance-attribute

extent = property(_get_extent, _set_extent)

inverseOf class-attribute instance-attribute

inverseOf = property(_get_inverseof, _set_inverseof, _del_inverseof)

range class-attribute instance-attribute

range = property(_get_range, _set_range, _del_range)

subPropertyOf class-attribute instance-attribute

subPropertyOf = property(_get_subpropertyof, _set_subpropertyof, _del_subpropertyof)

__repr__

__repr__()
Source code in rdflib/extras/infixowl.py
def __repr__(self):
    rt = []
    if OWL.ObjectProperty in self.type:
        rt.append(
            "ObjectProperty( %s annotation(%s)"
            % (self.qname, first(self.comment) and first(self.comment) or "")
        )
        if first(self.inverseOf):
            # type error: Item "None" of "Optional[Any]" has no attribute "inverseOf"
            two_link_inverse = first(first(self.inverseOf).inverseOf)  # type: ignore[union-attr]
            if two_link_inverse and two_link_inverse.identifier == self.identifier:
                # type error: Item "None" of "Optional[Any]" has no attribute "qname"
                inverserepr = first(self.inverseOf).qname  # type: ignore[union-attr]
            else:
                inverserepr = repr(first(self.inverseOf))
            rt.append(
                "  inverseOf( %s )%s"
                % (
                    inverserepr,
                    OWL.SymmetricProperty in self.type and " Symmetric" or "",
                )
            )
        for _s, _p, roletype in self.graph.triples_choices(
            # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, URIRef, List[URIRef]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
            (  # type: ignore[arg-type]
                self.identifier,
                RDF.type,
                [
                    OWL.FunctionalProperty,
                    OWL.InverseFunctionalProperty,
                    OWL.TransitiveProperty,
                ],
            )
        ):
            # type error: "Node" has no attribute "split"
            rt.append(str(roletype.split(str(OWL))[-1]))  # type: ignore[attr-defined]
    else:
        rt.append(
            "DatatypeProperty( %s %s"
            % (self.qname, first(self.comment) and first(self.comment) or "")
        )
        for _s, _p, roletype in self.graph.triples(
            (self.identifier, RDF.type, OWL.FunctionalProperty)
        ):
            rt.append("   Functional")

    def canonicalName(term, g):  # noqa: N802
        normalized_name = classOrIdentifier(term)
        if isinstance(normalized_name, BNode):
            return term
        elif normalized_name.startswith(XSD):
            return str(term)
        elif first(
            g.triples_choices(
                (normalized_name, [OWL.unionOf, OWL.intersectionOf], None)
            )
        ):
            return repr(term)
        else:
            return str(term.qname)

    rt.append(
        " ".join(
            [
                "   super( %s )" % canonicalName(super_property, self.graph)
                for super_property in self.subPropertyOf
            ]
        )
    )
    rt.append(
        " ".join(
            [
                "   domain( %s )" % canonicalName(domain, self.graph)
                for domain in self.domain
            ]
        )
    )
    rt.append(
        " ".join(
            [
                "   range( %s )" % canonicalName(range, self.graph)
                for range in self.range
            ]
        )
    )
    # type error: Incompatible types in assignment (expression has type "str", variable has type "List[str]")
    rt = "\n".join([expr for expr in rt if expr])  # type: ignore[assignment]
    rt += "\n)"
    return rt

replace

replace(other)
Source code in rdflib/extras/infixowl.py
def replace(self, other):
    # extension = []
    for s, _p, o in self.extent:
        self.graph.add((s, propertyOrIdentifier(other), o))
    self.graph.remove((None, self.identifier, None))

serialize

serialize(graph)
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    for fact in self.graph.triples((self.identifier, None, None)):
        graph.add(fact)
    for p in itertools.chain(self.subPropertyOf, self.inverseOf):
        p.serialize(graph)
    for c in itertools.chain(self.domain, self.range):
        CastClass(c, self.graph).serialize(graph)

setupVerbAnnotations

setupVerbAnnotations(verb_annotations)

OWL properties map to ACE transitive verbs (TV)

There are 6 morphological categories that determine the surface form of an IRI:

  • singular form of a transitive verb (e.g. mans)
  • plural form of a transitive verb (e.g. man)
  • past participle form a transitive verb (e.g. manned)
  • http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
  • http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
  • http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg
Source code in rdflib/extras/infixowl.py
def setupVerbAnnotations(self, verb_annotations):  # noqa: N802
    """OWL properties map to ACE transitive verbs (TV)

    There are 6 morphological categories that determine the surface form
    of an IRI:

    - singular form of a transitive verb (e.g. mans)
    - plural form of a transitive verb (e.g. man)
    - past participle form a transitive verb (e.g. manned)
    - http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
    - http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
    - http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg
    """

    if isinstance(verb_annotations, tuple):
        tv_sgprop, tv_plprop, tv_vbg = verb_annotations
    else:
        tv_sgprop = verb_annotations
        tv_plprop = verb_annotations
        tv_vbg = verb_annotations
    if tv_sgprop:
        self.tv_sgprop.extent = [
            (self.identifier, self.handleAnnotation(tv_sgprop))
        ]
    if tv_plprop:
        self.tv_plprop.extent = [
            (self.identifier, self.handleAnnotation(tv_plprop))
        ]
    if tv_vbg:
        self.tv_vbgprop.extent = [(self.identifier, self.handleAnnotation(tv_vbg))]

Restriction

Restriction(onProperty, graph=None, allValuesFrom=None, someValuesFrom=None, value=None, cardinality=None, maxCardinality=None, minCardinality=None, identifier=None)

Bases: Class

restriction ::= 'restriction('
datavaluedPropertyID dataRestrictionComponent
{ dataRestrictionComponent } ')'
| 'restriction(' individualvaluedPropertyID
individualRestrictionComponent
{ individualRestrictionComponent } ')'

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(
    self,
    onProperty,  # noqa: N803
    graph=None,
    allValuesFrom=None,  # noqa: N803
    someValuesFrom=None,  # noqa: N803
    value=None,
    cardinality=None,
    maxCardinality=None,  # noqa: N803
    minCardinality=None,  # noqa: N803
    identifier=None,
):
    graph = Graph() if graph is None else graph
    super(Restriction, self).__init__(
        identifier, graph=graph, skipOWLClassMembership=True
    )
    if (
        self.identifier,
        OWL.onProperty,
        propertyOrIdentifier(onProperty),
    ) not in graph:
        graph.add(
            (self.identifier, OWL.onProperty, propertyOrIdentifier(onProperty))
        )
    self.onProperty = onProperty
    restr_types = [
        (allValuesFrom, OWL.allValuesFrom),
        (someValuesFrom, OWL.someValuesFrom),
        (value, OWL.hasValue),
        (cardinality, OWL.cardinality),
        (maxCardinality, OWL.maxCardinality),
        (minCardinality, OWL.minCardinality),
    ]
    valid_restr_props = [(i, oterm) for (i, oterm) in restr_types if i is not None]
    if not len(valid_restr_props):
        raise ValueError(
            "Missing value. One of: allValuesFrom, someValuesFrom,"
            "value, cardinality, maxCardinality or minCardinality"
            "must have a value."
        )
    restriction_range, restriction_type = valid_restr_props.pop()
    self.restrictionType = restriction_type
    if isinstance(restriction_range, Identifier):
        self.restrictionRange = restriction_range
    elif isinstance(restriction_range, Class):
        self.restrictionRange = classOrIdentifier(restriction_range)
    else:
        # error: Incompatible types in assignment (expression has type "Optional[Identifier]", variable has type "Identifier")
        self.restrictionRange = first(  # type: ignore[assignment]
            # type error: Argument 1 to "first" has incompatible type "Generator[Node, None, None]"; expected "Iterable[Identifier]"
            self.graph.objects(self.identifier, restriction_type)  # type: ignore[arg-type]
        )
    if (
        self.identifier,
        restriction_type,
        self.restrictionRange,
    ) not in self.graph:
        self.graph.add((self.identifier, restriction_type, self.restrictionRange))
    assert self.restrictionRange is not None, Class(self.identifier)
    if (self.identifier, RDF.type, OWL.Restriction) not in self.graph:
        self.graph.add((self.identifier, RDF.type, OWL.Restriction))
        self.graph.remove((self.identifier, RDF.type, OWL.Class))

allValuesFrom class-attribute instance-attribute

allValuesFrom = property(_get_allvaluesfrom, _set_allvaluesfrom, _del_allvaluesfrom)

cardinality class-attribute instance-attribute

cardinality = property(_get_cardinality, _set_cardinality, _del_cardinality)

hasValue class-attribute instance-attribute

hasValue = property(_get_hasvalue, _set_hasvalue, _del_hasvalue)

maxCardinality class-attribute instance-attribute

maxCardinality = property(_get_maxcardinality, _set_maxcardinality, _del_maxcardinality)

minCardinality class-attribute instance-attribute

minCardinality = property(_get_mincardinality, _set_mincardinality, _del_mincardinality)

onProperty class-attribute instance-attribute

onProperty = property(_get_onproperty, _set_onproperty, _del_onproperty)

restrictionKinds class-attribute instance-attribute

restrictionKinds = [allValuesFrom, someValuesFrom, hasValue, cardinality, maxCardinality, minCardinality]

restrictionRange instance-attribute

restrictionRange = restriction_range

restrictionType instance-attribute

restrictionType = restriction_type

someValuesFrom class-attribute instance-attribute

someValuesFrom = property(_get_somevaluesfrom, _set_somevaluesfrom, _del_somevaluesfrom)

__eq__

__eq__(other)

Equivalence of restrictions is determined by equivalence of the property in question and the restriction ‘range’

Source code in rdflib/extras/infixowl.py
def __eq__(self, other):
    """
    Equivalence of restrictions is determined by equivalence of the
    property in question and the restriction 'range'
    """
    assert isinstance(other, Class), repr(other) + repr(type(other))
    if isinstance(other, Restriction):
        return (
            other.onProperty == self.onProperty
            # type error: "Restriction" has no attribute "restriction_range"; maybe "restrictionRange"?
            and other.restriction_range == self.restrictionRange  # type: ignore[attr-defined]
        )
    else:
        return False

__hash__

__hash__()
Source code in rdflib/extras/infixowl.py
def __hash__(self):
    return hash((self.onProperty, self.restrictionRange))

__repr__

__repr__()

Returns the Manchester Syntax equivalent for this restriction

Source code in rdflib/extras/infixowl.py
def __repr__(self):
    """
    Returns the Manchester Syntax equivalent for this restriction
    """
    return manchesterSyntax(self.identifier, self.graph)

isPrimitive

isPrimitive()
Source code in rdflib/extras/infixowl.py
def isPrimitive(self):  # noqa: N802
    return False

restrictionKind

restrictionKind()
Source code in rdflib/extras/infixowl.py
def restrictionKind(self):  # noqa: N802
    for s, p, o in self.graph.triples_choices(
        # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
        (self.identifier, self.restrictionKinds, None)  # type: ignore[arg-type]
    ):
        # type error: "Node" has no attribute "split"
        return p.split(str(OWL))[-1]  # type: ignore[attr-defined]
    return None

serialize

serialize(graph)
>>> g1 = Graph()
>>> g2 = Graph()
>>> EX = Namespace("http://example.com/")
>>> g1.bind("ex", EX, override=False)
>>> g2.bind("ex", EX, override=False)
>>> Individual.factoryGraph = g1
>>> prop = Property(EX.someProp, baseType=OWL.DatatypeProperty)
>>> restr1 = (Property(
...    EX.someProp,
...    baseType=OWL.DatatypeProperty)) @ some @ (Class(EX.Foo))
>>> restr1  # doctest: +SKIP
( ex:someProp SOME ex:Foo )
>>> restr1.serialize(g2)
>>> Individual.factoryGraph = g2
>>> list(Property(
...     EX.someProp,baseType=None).type
... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
[rdflib.term.URIRef(
    'http://www.w3.org/2002/07/owl#DatatypeProperty')]
Source code in rdflib/extras/infixowl.py
def serialize(self, graph):
    """
    ```python
    >>> g1 = Graph()
    >>> g2 = Graph()
    >>> EX = Namespace("http://example.com/")
    >>> g1.bind("ex", EX, override=False)
    >>> g2.bind("ex", EX, override=False)
    >>> Individual.factoryGraph = g1
    >>> prop = Property(EX.someProp, baseType=OWL.DatatypeProperty)
    >>> restr1 = (Property(
    ...    EX.someProp,
    ...    baseType=OWL.DatatypeProperty)) @ some @ (Class(EX.Foo))
    >>> restr1  # doctest: +SKIP
    ( ex:someProp SOME ex:Foo )
    >>> restr1.serialize(g2)
    >>> Individual.factoryGraph = g2
    >>> list(Property(
    ...     EX.someProp,baseType=None).type
    ... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
    [rdflib.term.URIRef(
        'http://www.w3.org/2002/07/owl#DatatypeProperty')]

    ```
    """
    Property(self.onProperty, graph=self.graph, baseType=None).serialize(graph)
    for s, p, o in self.graph.triples((self.identifier, None, None)):
        graph.add((s, p, o))
        if p in [OWL.allValuesFrom, OWL.someValuesFrom]:
            CastClass(o, self.graph).serialize(graph)

TermDeletionHelper

TermDeletionHelper(prop)

Methods:

Attributes:

Source code in rdflib/extras/infixowl.py
def __init__(self, prop):
    self.prop = prop

prop instance-attribute

prop = prop

__call__

__call__(f)
Source code in rdflib/extras/infixowl.py
def __call__(self, f):
    def _remover(inst):
        inst.graph.remove((inst.identifier, self.prop, None))

    return _remover

AllClasses

AllClasses(graph)
Source code in rdflib/extras/infixowl.py
def AllClasses(graph):  # noqa: N802
    for c in set(graph.subjects(predicate=RDF.type, object=OWL.Class)):
        yield Class(c)

AllDifferent

AllDifferent(members)

TODO: implement this function

DisjointClasses(’ description description { description } ‘)’

Source code in rdflib/extras/infixowl.py
def AllDifferent(members):  # noqa: N802
    """
    TODO: implement this function

    DisjointClasses(' description description { description } ')'
    """
    pass  # pragma: no cover

AllProperties

AllProperties(graph)
Source code in rdflib/extras/infixowl.py
def AllProperties(graph):  # noqa: N802
    prevprops = set()
    for s, _p, o in graph.triples_choices(
        (
            None,
            RDF.type,
            [
                OWL.SymmetricProperty,
                OWL.FunctionalProperty,
                OWL.InverseFunctionalProperty,
                OWL.TransitiveProperty,
                OWL.DatatypeProperty,
                OWL.ObjectProperty,
                OWL.AnnotationProperty,
            ],
        )
    ):
        if o in [
            OWL.SymmetricProperty,
            OWL.InverseFunctionalProperty,
            OWL.TransitiveProperty,
            OWL.ObjectProperty,
        ]:
            bType = OWL.ObjectProperty  # noqa: N806
        else:
            bType = OWL.DatatypeProperty  # noqa: N806
        if s not in prevprops:
            prevprops.add(s)
            yield Property(s, graph=graph, baseType=bType)

CastClass

CastClass(c, graph=None)
Source code in rdflib/extras/infixowl.py
def CastClass(c, graph=None):  # noqa: N802
    graph = graph is None and c.factoryGraph or graph
    for kind in graph.objects(subject=classOrIdentifier(c), predicate=RDF.type):
        if kind == OWL.Restriction:
            kwargs = {"identifier": classOrIdentifier(c), "graph": graph}
            for _s, p, o in graph.triples((classOrIdentifier(c), None, None)):
                if p != RDF.type:
                    if p == OWL.onProperty:
                        kwargs["onProperty"] = o
                    else:
                        if p not in Restriction.restrictionKinds:
                            continue
                        kwargs[str(p.split(str(OWL))[-1])] = o
            if not set(
                [str(i.split(str(OWL))[-1]) for i in Restriction.restrictionKinds]
            ).intersection(kwargs):
                raise MalformedClassError("Malformed owl:Restriction")
            return Restriction(**kwargs)
        else:
            for _s, p, _o in graph.triples_choices(
                (
                    classOrIdentifier(c),
                    [OWL.intersectionOf, OWL.unionOf, OWL.oneOf],
                    None,
                )
            ):
                if p == OWL.oneOf:
                    return EnumeratedClass(classOrIdentifier(c), graph=graph)
                else:
                    return BooleanClass(classOrIdentifier(c), operator=p, graph=graph)
            # assert (classOrIdentifier(c),RDF.type,OWL.Class) in graph
            return Class(classOrIdentifier(c), graph=graph, skipOWLClassMembership=True)

CommonNSBindings

CommonNSBindings(graph, additionalNS=None)

Takes a graph and binds the common namespaces (rdf,rdfs, & owl)

Source code in rdflib/extras/infixowl.py
def CommonNSBindings(graph, additionalNS=None):  # noqa: N802, N803
    """
    Takes a graph and binds the common namespaces (rdf,rdfs, & owl)
    """
    additional_ns = {} if additionalNS is None else additionalNS
    namespace_manager = NamespaceManager(graph)
    namespace_manager.bind("rdfs", RDFS)
    namespace_manager.bind("rdf", RDF)
    namespace_manager.bind("owl", OWL)
    for prefix, uri in list(additional_ns.items()):
        namespace_manager.bind(prefix, uri, override=False)
    graph.namespace_manager = namespace_manager

ComponentTerms

ComponentTerms(cls)

Takes a Class instance and returns a generator over the classes that are involved in its definition, ignoring unnamed classes

Source code in rdflib/extras/infixowl.py
def ComponentTerms(cls):  # noqa: N802
    """
    Takes a Class instance and returns a generator over the classes that
    are involved in its definition, ignoring unnamed classes
    """
    if OWL.Restriction in cls.type:
        try:
            cls = CastClass(cls, Individual.factoryGraph)
            for _s, _p, inner_class_id in cls.factoryGraph.triples_choices(
                (cls.identifier, [OWL.allValuesFrom, OWL.someValuesFrom], None)
            ):
                inner_class = Class(inner_class_id, skipOWLClassMembership=True)
                if isinstance(inner_class_id, BNode):
                    for _c in ComponentTerms(inner_class):
                        yield _c
                else:
                    yield inner_class
        except Exception:  # pragma: no cover
            pass  # pragma: no cover
    else:
        cls = CastClass(cls, Individual.factoryGraph)
        if isinstance(cls, BooleanClass):
            for _cls in cls:
                _cls = Class(_cls, skipOWLClassMembership=True)
                if isinstance(_cls.identifier, BNode):
                    for _c in ComponentTerms(_cls):
                        yield _c
                else:
                    yield _cls
        else:
            for inner_class in cls.subClassOf:
                if isinstance(inner_class.identifier, BNode):
                    for _c in ComponentTerms(inner_class):
                        yield _c
                else:
                    yield inner_class
            for _s, _p, o in cls.factoryGraph.triples_choices(
                (classOrIdentifier(cls), CLASS_RELATIONS, None)
            ):
                if isinstance(o, BNode):
                    for _c in ComponentTerms(CastClass(o, Individual.factoryGraph)):
                        yield _c
                else:
                    yield inner_class

DeepClassClear

DeepClassClear(class_to_prune)

Recursively clear the given class, continuing where any related class is an anonymous class

>>> EX = Namespace("http://example.com/")
>>> g = Graph()
>>> g.bind("ex", EX, override=False)
>>> Individual.factoryGraph = g
>>> classB = Class(EX.B)
>>> classC = Class(EX.C)
>>> classD = Class(EX.D)
>>> classE = Class(EX.E)
>>> classF = Class(EX.F)
>>> anonClass = EX.someProp @ some @ classD
>>> classF += anonClass
>>> list(anonClass.subClassOf)
[Class: ex:F ]
>>> classA = classE | classF | anonClass
>>> classB += classA
>>> classA.equivalentClass = [Class()]
>>> classB.subClassOf = [EX.someProp @ some @ classC]
>>> classA
( ex:E OR ex:F OR ( ex:someProp SOME ex:D ) )
>>> DeepClassClear(classA)
>>> classA
(  )
>>> list(anonClass.subClassOf)
[]
>>> classB
Class: ex:B SubClassOf: ( ex:someProp SOME ex:C )

>>> otherClass = classD | anonClass
>>> otherClass
( ex:D OR ( ex:someProp SOME ex:D ) )
>>> DeepClassClear(otherClass)
>>> otherClass
(  )
>>> otherClass.delete()
>>> list(g.triples((otherClass.identifier, None, None)))
[]
Source code in rdflib/extras/infixowl.py
def DeepClassClear(class_to_prune):  # noqa: N802
    """
    Recursively clear the given class, continuing
    where any related class is an anonymous class

    ```python
    >>> EX = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", EX, override=False)
    >>> Individual.factoryGraph = g
    >>> classB = Class(EX.B)
    >>> classC = Class(EX.C)
    >>> classD = Class(EX.D)
    >>> classE = Class(EX.E)
    >>> classF = Class(EX.F)
    >>> anonClass = EX.someProp @ some @ classD
    >>> classF += anonClass
    >>> list(anonClass.subClassOf)
    [Class: ex:F ]
    >>> classA = classE | classF | anonClass
    >>> classB += classA
    >>> classA.equivalentClass = [Class()]
    >>> classB.subClassOf = [EX.someProp @ some @ classC]
    >>> classA
    ( ex:E OR ex:F OR ( ex:someProp SOME ex:D ) )
    >>> DeepClassClear(classA)
    >>> classA
    (  )
    >>> list(anonClass.subClassOf)
    []
    >>> classB
    Class: ex:B SubClassOf: ( ex:someProp SOME ex:C )

    >>> otherClass = classD | anonClass
    >>> otherClass
    ( ex:D OR ( ex:someProp SOME ex:D ) )
    >>> DeepClassClear(otherClass)
    >>> otherClass
    (  )
    >>> otherClass.delete()
    >>> list(g.triples((otherClass.identifier, None, None)))
    []

    ```
    """

    def deepClearIfBNode(_class):  # noqa: N802
        if isinstance(classOrIdentifier(_class), BNode):
            DeepClassClear(_class)

    class_to_prune = CastClass(class_to_prune, Individual.factoryGraph)
    for c in class_to_prune.subClassOf:
        deepClearIfBNode(c)
    class_to_prune.graph.remove((class_to_prune.identifier, RDFS.subClassOf, None))
    for c in class_to_prune.equivalentClass:
        deepClearIfBNode(c)
    class_to_prune.graph.remove((class_to_prune.identifier, OWL.equivalentClass, None))
    inverse_class = class_to_prune.complementOf
    if inverse_class:
        class_to_prune.graph.remove((class_to_prune.identifier, OWL.complementOf, None))
        deepClearIfBNode(inverse_class)
    if isinstance(class_to_prune, BooleanClass):
        for c in class_to_prune:
            deepClearIfBNode(c)
        class_to_prune.clear()
        class_to_prune.graph.remove(
            (class_to_prune.identifier, class_to_prune._operator, None)
        )

GetIdentifiedClasses

GetIdentifiedClasses(graph)
Source code in rdflib/extras/infixowl.py
def GetIdentifiedClasses(graph):  # noqa: N802
    for c in graph.subjects(predicate=RDF.type, object=OWL.Class):
        if isinstance(c, URIRef):
            yield Class(c)

classOrIdentifier

classOrIdentifier(thing)
Source code in rdflib/extras/infixowl.py
def classOrIdentifier(thing):  # noqa: N802
    if isinstance(thing, (Property, Class)):
        return thing.identifier
    else:
        assert isinstance(thing, (URIRef, BNode)), (
            "Expecting a Class, Property, URIRef, or BNode.. not a %s" % thing
        )
        return thing

classOrTerm

classOrTerm(thing)
Source code in rdflib/extras/infixowl.py
def classOrTerm(thing):  # noqa: N802
    if isinstance(thing, Class):
        return thing.identifier
    else:
        assert isinstance(thing, (URIRef, BNode, Literal))
        return thing

generateQName

generateQName(graph, uri)
Source code in rdflib/extras/infixowl.py
def generateQName(graph, uri):  # noqa: N802
    prefix, uri, localname = graph.compute_qname(classOrIdentifier(uri))
    return ":".join([prefix, localname])

manchesterSyntax

manchesterSyntax(thing, store, boolean=None, transientList=False)

Core serialization thing is a Class and is processed as a subject store is an RDFLib Graph to be queried about thing

Source code in rdflib/extras/infixowl.py
def manchesterSyntax(  # noqa: N802
    thing, store, boolean=None, transientList=False  # noqa: N803
):
    """
    Core serialization
    thing is a Class and is processed as a subject
    store is an RDFLib Graph to be queried about thing
    """
    assert thing is not None
    if boolean:
        if transientList:
            livechildren = iter(thing)
            children = [manchesterSyntax(child, store) for child in thing]
        else:
            livechildren = iter(Collection(store, thing))
            children = [
                manchesterSyntax(child, store) for child in Collection(store, thing)
            ]
        if boolean == OWL.intersectionOf:
            childlist = []
            named = []
            for child in livechildren:
                if isinstance(child, URIRef):
                    named.append(child)
                else:
                    childlist.append(child)
            if named:

                def castToQName(x):  # noqa: N802
                    prefix, uri, localname = store.compute_qname(x)
                    return ":".join([prefix, localname])

                if len(named) > 1:
                    prefix = "( " + " AND ".join(map(castToQName, named)) + " )"
                else:
                    prefix = manchesterSyntax(named[0], store)
                if childlist:
                    return (
                        str(prefix)
                        + " THAT "
                        + " AND ".join(
                            [str(manchesterSyntax(x, store)) for x in childlist]
                        )
                    )
                else:
                    return prefix
            else:
                return "( " + " AND ".join([str(c) for c in children]) + " )"
        elif boolean == OWL.unionOf:
            return "( " + " OR ".join([str(c) for c in children]) + " )"
        elif boolean == OWL.oneOf:
            return "{ " + " ".join([str(c) for c in children]) + " }"
        else:
            assert boolean == OWL.complementOf
    elif OWL.Restriction in store.objects(subject=thing, predicate=RDF.type):
        prop = list(store.objects(subject=thing, predicate=OWL.onProperty))[0]
        prefix, uri, localname = store.compute_qname(prop)
        propstring = ":".join([prefix, localname])
        label = first(store.objects(subject=prop, predicate=RDFS.label))
        if label:
            propstring = "'%s'" % label
        for onlyclass in store.objects(subject=thing, predicate=OWL.allValuesFrom):
            return "( %s ONLY %s )" % (propstring, manchesterSyntax(onlyclass, store))
        for val in store.objects(subject=thing, predicate=OWL.hasValue):
            return "( %s VALUE %s )" % (propstring, manchesterSyntax(val, store))
        for someclass in store.objects(subject=thing, predicate=OWL.someValuesFrom):
            return "( %s SOME %s )" % (propstring, manchesterSyntax(someclass, store))
        cardlookup = {
            OWL.maxCardinality: "MAX",
            OWL.minCardinality: "MIN",
            OWL.cardinality: "EQUALS",
        }
        for _s, p, o in store.triples_choices((thing, list(cardlookup.keys()), None)):
            return "( %s %s %s )" % (propstring, cardlookup[p], o)
    # is thing a complement of anything
    compl = list(store.objects(subject=thing, predicate=OWL.complementOf))
    if compl:
        return "( NOT %s )" % (manchesterSyntax(compl[0], store))
    else:
        prolog = "\n".join(["PREFIX %s: <%s>" % (k, nsBinds[k]) for k in nsBinds])
        qstr = (
            prolog
            + "\nSELECT ?p ?bool WHERE {?class a owl:Class; ?p ?bool ."
            + "?bool rdf:first ?foo }"
        )
        initb = {Variable("?class"): thing}
        for boolprop, col in store.query(qstr, processor="sparql", initBindings=initb):
            if not isinstance(thing, URIRef):
                return manchesterSyntax(col, store, boolean=boolprop)
        try:
            prefix, uri, localname = store.compute_qname(thing)
            qname = ":".join([prefix, localname])
        except Exception:
            if isinstance(thing, BNode):
                return thing.n3()
            # Expect the unexpected
            return thing.identifier if not isinstance(thing, str) else thing
        label = first(Class(thing, graph=store).label)
        if label:
            return label
        else:
            return qname

propertyOrIdentifier

propertyOrIdentifier(thing)
Source code in rdflib/extras/infixowl.py
def propertyOrIdentifier(thing):  # noqa: N802
    if isinstance(thing, Property):
        return thing.identifier
    else:
        assert isinstance(thing, URIRef)
        return thing