Source code

Download source archive ↓

src/rdflib/extras/infixowl.py

1"""RDFLib Python binding for OWL Abstract Syntax
2
3| OWL Constructor   | DL Syntax     | Manchester OWL Syntax | Example                          |
4|------------------|---------------|------------------------|----------------------------------|
5| `intersectionOf` | C ∩ D         | C AND D                | Human AND Male                   |
6| `unionOf`        | C ∪ D         | C OR D                 | Man OR Woman                     |
7| `complementOf`   | ¬C            | NOT C                  | NOT Male                         |
8| `oneOf`          | {a} ∪ {b}...  | {a b ...}              | {England Italy Spain}           |
9| `someValuesFrom` | ∃ R C         | R SOME C               | hasColleague SOME Professor      |
10| `allValuesFrom`  | ∀ R C         | R ONLY C               | hasColleague ONLY Professor      |
11| `minCardinality` | ≥ N R         | R MIN 3                | hasColleague MIN 3               |
12| `maxCardinality` | ≤ N R         | R MAX 3                | hasColleague MAX 3               |
13| `cardinality`    | = N R         | R EXACTLY 3            | hasColleague EXACTLY 3           |
14| `hasValue`       | ∃ R.{a}       | R VALUE a              | hasColleague VALUE Matthew       |
15
16See:
17- http://www.w3.org/TR/owl-semantics/syntax.html
18- http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf
19
203.2.3 Axioms for complete classes without using owl:equivalentClass
21
22Named class description of type 2 (with owl:oneOf) or type 4-6
23(with owl:intersectionOf, owl:unionOf or owl:complementOf
24
25Uses Manchester Syntax for `__repr__`
26
27```python
28>>> exNs = Namespace("http://example.com/")
29>>> g = Graph()
30>>> g.bind("ex", exNs, override=False)
31
32```
33
34Now we have an empty graph, we can construct OWL classes in it
35using the Python classes defined in this module
36
37```python
38>>> a = Class(exNs.Opera, graph=g)
39
40```
41
42Now we can assert rdfs:subClassOf and owl:equivalentClass relationships
43(in the underlying graph) with other classes using the 'subClassOf'
44and 'equivalentClass' descriptors which can be set to a list
45of objects for the corresponding predicates.
46
47```python
48>>> a.subClassOf = [exNs.MusicalWork]
49
50```
51
52We can then access the rdfs:subClassOf relationships
53
54```python
55>>> print(list(a.subClassOf))
56[Class: ex:MusicalWork ]
57
58```
59
60This can also be used against already populated graphs:
61
62```python
63>>> owlGraph = Graph().parse(str(OWL))
64>>> list(Class(OWL.Class, graph=owlGraph).subClassOf)
65[Class: rdfs:Class ]
66
67```
68
69Operators are also available. For instance we can add ex:Opera to the extension
70of the ex:CreativeWork class via the '+=' operator
71
72```python
73>>> a
74Class: ex:Opera SubClassOf: ex:MusicalWork
75>>> b = Class(exNs.CreativeWork, graph=g)
76>>> b += a
77>>> print(sorted(a.subClassOf, key=lambda c:c.identifier))
78[Class: ex:CreativeWork , Class: ex:MusicalWork ]
79
80```
81
82And we can then remove it from the extension as well
83
84```python
85>>> b -= a
86>>> a
87Class: ex:Opera SubClassOf: ex:MusicalWork
88
89```
90
91Boolean class constructions can also  be created with Python operators.
92For example, The | operator can be used to construct a class consisting of a
93owl:unionOf the operands:
94
95```python
96>>> c =  a | b | Class(exNs.Work, graph=g)
97>>> c
98( ex:Opera OR ex:CreativeWork OR ex:Work )
99
100```
101
102Boolean class expressions can also be operated as lists (using python list
103operators)
104
105```python
106>>> del c[c.index(Class(exNs.Work, graph=g))]
107>>> c
108( ex:Opera OR ex:CreativeWork )
109
110```
111
112The '&' operator can be used to construct class intersection:
113
114```python
115>>> woman = Class(exNs.Female, graph=g) & Class(exNs.Human, graph=g)
116>>> woman.identifier = exNs.Woman
117>>> woman
118( ex:Female AND ex:Human )
119>>> len(woman)
1202
121
122```
123
124Enumerated classes can also be manipulated
125
126```python
127>>> contList = [Class(exNs.Africa, graph=g), Class(exNs.NorthAmerica, graph=g)]
128>>> EnumeratedClass(members=contList, graph=g)
129{ ex:Africa ex:NorthAmerica }
130
131```
132
133owl:Restrictions can also be instantiated:
134
135```python
136>>> Restriction(exNs.hasParent, graph=g, allValuesFrom=exNs.Human)
137( ex:hasParent ONLY ex:Human )
138
139```
140
141Restrictions can also be created using Manchester OWL syntax in 'colloquial' Python
142
143```python
144>>> exNs.hasParent @ some @ Class(exNs.Physician, graph=g)
145( ex:hasParent SOME ex:Physician )
146>>> Property(exNs.hasParent, graph=g) @ max @ Literal(1)
147( ex:hasParent MAX 1 )
148>>> print(g.serialize(format='pretty-xml'))  # doctest: +SKIP
149```
150"""
151
152from __future__ import annotations
153
154import itertools
155import logging
156from typing import Iterable, Union
157
158from rdflib.collection import Collection
159from rdflib.graph import Graph, _ObjectType
160from rdflib.namespace import OWL, RDF, RDFS, XSD, Namespace, NamespaceManager
161from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
162from rdflib.util import first
163
164logger = logging.getLogger(__name__)
165
166
167"""
168From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
169
170Python has the wonderful "in" operator and it would be nice to have additional
171infix operator like this. This recipe shows how (almost) arbitrary infix
172operators can be defined.
173"""
174
175__all__ = [
176    "ACE_NS",
177    "AllClasses",
178    "AllDifferent",
179    "AllProperties",
180    "AnnotatableTerms",
181    "BooleanClass",
182    "CLASS_RELATIONS",
183    "Callable",
184    "CastClass",
185    "Class",
186    "ClassNamespaceFactory",
187    "CommonNSBindings",
188    "ComponentTerms",
189    "DeepClassClear",
190    "EnumeratedClass",
191    "GetIdentifiedClasses",
192    "Individual",
193    "Infix",
194    "MalformedClass",
195    "MalformedClassError",
196    "OWLRDFListProxy",
197    "Ontology",
198    "Property",
199    "PropertyAbstractSyntax",
200    "Restriction",
201    "classOrIdentifier",
202    "classOrTerm",
203    "exactly",
204    "generateQName",
205    "manchesterSyntax",
206    "max",
207    "min",
208    "nsBinds",
209    "only",
210    "propertyOrIdentifier",
211    "some",
212    "value",
213]
214
215# definition of an Infix operator class
216# this recipe also works in jython
217# calling sequence for the infix is:
218#  x @ op @ y
219
220
221class Infix:
222    def __init__(self, function):
223        self.function = function
224
225    def __rlshift__(self, other):
226        return Infix(lambda x, self=self, other=other: self.function(other, x))
227
228    def __rshift__(self, other):
229        return self.function(other)
230
231    def __rmatmul__(self, other):
232        return Infix(lambda x, self=self, other=other: self.function(other, x))
233
234    def __matmul__(self, other):
235        return self.function(other)
236
237    def __call__(self, value1, value2):
238        return self.function(value1, value2)  # pragma: no cover
239
240
241nsBinds = {  # noqa: N816
242    "skos": "http://www.w3.org/2004/02/skos/core#",
243    "rdf": RDF,
244    "rdfs": RDFS,
245    "owl": OWL,
246    "list": URIRef("http://www.w3.org/2000/10/swap/list#"),
247    "dc": "http://purl.org/dc/elements/1.1/",
248}
249
250
251def generateQName(graph, uri):  # noqa: N802
252    prefix, uri, localname = graph.compute_qname(classOrIdentifier(uri))
253    return ":".join([prefix, localname])
254
255
256def classOrTerm(thing):  # noqa: N802
257    if isinstance(thing, Class):
258        return thing.identifier
259    else:
260        assert isinstance(thing, (URIRef, BNode, Literal))
261        return thing
262
263
264def classOrIdentifier(thing):  # noqa: N802
265    if isinstance(thing, (Property, Class)):
266        return thing.identifier
267    else:
268        assert isinstance(thing, (URIRef, BNode)), (
269            "Expecting a Class, Property, URIRef, or BNode.. not a %s" % thing
270        )
271        return thing
272
273
274def propertyOrIdentifier(thing):  # noqa: N802
275    if isinstance(thing, Property):
276        return thing.identifier
277    else:
278        assert isinstance(thing, URIRef)
279        return thing
280
281
282def manchesterSyntax(  # noqa: N802
283    thing, store, boolean=None, transientList=False  # noqa: N803
284):
285    """
286    Core serialization
287    thing is a Class and is processed as a subject
288    store is an RDFLib Graph to be queried about thing
289    """
290    assert thing is not None
291    if boolean:
292        if transientList:
293            livechildren = iter(thing)
294            children = [manchesterSyntax(child, store) for child in thing]
295        else:
296            livechildren = iter(Collection(store, thing))
297            children = [
298                manchesterSyntax(child, store) for child in Collection(store, thing)
299            ]
300        if boolean == OWL.intersectionOf:
301            childlist = []
302            named = []
303            for child in livechildren:
304                if isinstance(child, URIRef):
305                    named.append(child)
306                else:
307                    childlist.append(child)
308            if named:
309
310                def castToQName(x):  # noqa: N802
311                    prefix, uri, localname = store.compute_qname(x)
312                    return ":".join([prefix, localname])
313
314                if len(named) > 1:
315                    prefix = "( " + " AND ".join(map(castToQName, named)) + " )"
316                else:
317                    prefix = manchesterSyntax(named[0], store)
318                if childlist:
319                    return (
320                        str(prefix)
321                        + " THAT "
322                        + " AND ".join(
323                            [str(manchesterSyntax(x, store)) for x in childlist]
324                        )
325                    )
326                else:
327                    return prefix
328            else:
329                return "( " + " AND ".join([str(c) for c in children]) + " )"
330        elif boolean == OWL.unionOf:
331            return "( " + " OR ".join([str(c) for c in children]) + " )"
332        elif boolean == OWL.oneOf:
333            return "{ " + " ".join([str(c) for c in children]) + " }"
334        else:
335            assert boolean == OWL.complementOf
336    elif OWL.Restriction in store.objects(subject=thing, predicate=RDF.type):
337        prop = list(store.objects(subject=thing, predicate=OWL.onProperty))[0]
338        prefix, uri, localname = store.compute_qname(prop)
339        propstring = ":".join([prefix, localname])
340        label = first(store.objects(subject=prop, predicate=RDFS.label))
341        if label:
342            propstring = "'%s'" % label
343        for onlyclass in store.objects(subject=thing, predicate=OWL.allValuesFrom):
344            return "( %s ONLY %s )" % (propstring, manchesterSyntax(onlyclass, store))
345        for val in store.objects(subject=thing, predicate=OWL.hasValue):
346            return "( %s VALUE %s )" % (propstring, manchesterSyntax(val, store))
347        for someclass in store.objects(subject=thing, predicate=OWL.someValuesFrom):
348            return "( %s SOME %s )" % (propstring, manchesterSyntax(someclass, store))
349        cardlookup = {
350            OWL.maxCardinality: "MAX",
351            OWL.minCardinality: "MIN",
352            OWL.cardinality: "EQUALS",
353        }
354        for _s, p, o in store.triples_choices((thing, list(cardlookup.keys()), None)):
355            return "( %s %s %s )" % (propstring, cardlookup[p], o)
356    # is thing a complement of anything
357    compl = list(store.objects(subject=thing, predicate=OWL.complementOf))
358    if compl:
359        return "( NOT %s )" % (manchesterSyntax(compl[0], store))
360    else:
361        prolog = "\n".join(["PREFIX %s: <%s>" % (k, nsBinds[k]) for k in nsBinds])
362        qstr = (
363            prolog
364            + "\nSELECT ?p ?bool WHERE {?class a owl:Class; ?p ?bool ."
365            + "?bool rdf:first ?foo }"
366        )
367        initb = {Variable("?class"): thing}
368        for boolprop, col in store.query(qstr, processor="sparql", initBindings=initb):
369            if not isinstance(thing, URIRef):
370                return manchesterSyntax(col, store, boolean=boolprop)
371        try:
372            prefix, uri, localname = store.compute_qname(thing)
373            qname = ":".join([prefix, localname])
374        except Exception:
375            if isinstance(thing, BNode):
376                return thing.n3()
377            # Expect the unexpected
378            return thing.identifier if not isinstance(thing, str) else thing
379        label = first(Class(thing, graph=store).label)
380        if label:
381            return label
382        else:
383            return qname
384
385
386def GetIdentifiedClasses(graph):  # noqa: N802
387    for c in graph.subjects(predicate=RDF.type, object=OWL.Class):
388        if isinstance(c, URIRef):
389            yield Class(c)
390
391
392class TermDeletionHelper:
393    def __init__(self, prop):
394        self.prop = prop
395
396    def __call__(self, f):
397        def _remover(inst):
398            inst.graph.remove((inst.identifier, self.prop, None))
399
400        return _remover
401
402
403class Individual:
404    """
405    A typed individual, the base class of the InfixOWL classes.
406    """
407
408    factoryGraph = Graph()  # noqa: N815
409
410    def serialize(self, graph):
411        for fact in self.factoryGraph.triples((self.identifier, None, None)):
412            graph.add(fact)
413
414    def __init__(self, identifier=None, graph=None):
415        self.__identifier = identifier is not None and identifier or BNode()
416        if graph is None:
417            self.graph = self.factoryGraph
418        else:
419            self.graph = graph
420        self.qname = None
421        if not isinstance(self.identifier, BNode):
422            try:
423                prefix, uri, localname = self.graph.compute_qname(self.identifier)
424                self.qname = ":".join([prefix, localname])
425            except Exception:  # pragma: no cover
426                pass  # pragma: no cover
427
428    def clearInDegree(self):  # noqa: N802
429        """
430        Remove references to this individual as an object in the
431        backing store.
432        """
433        self.graph.remove((None, None, self.identifier))
434
435    def clearOutDegree(self):  # noqa: N802
436        """
437        Remove all statements to this individual as a subject in the
438        backing store. Note that this only removes the statements
439        themselves, not the blank node closure so there is a chance
440        that this will cause orphaned blank nodes to remain in the
441        graph.
442        """
443        self.graph.remove((self.identifier, None, None))
444
445    def delete(self):
446        """
447        Delete the individual from the graph, clearing the in and
448        out degrees.
449        """
450        self.clearInDegree()
451        self.clearOutDegree()
452
453    def replace(self, other):
454        """
455        Replace the individual in the graph with the given other,
456        causing all triples that refer to it to be changed and then
457        delete the individual.
458
459        ```python
460        >>> g = Graph()
461        >>> b = Individual(OWL.Restriction, g)
462        >>> b.type = RDFS.Resource
463        >>> len(list(b.type))
464        1
465        >>> del b.type
466        >>> len(list(b.type))
467        0
468
469        ```
470        """
471        for s, p, _o in self.graph.triples((None, None, self.identifier)):
472            self.graph.add((s, p, classOrIdentifier(other)))
473        self.delete()
474
475    def _get_type(self) -> Iterable[_ObjectType]:
476        for _t in self.graph.objects(subject=self.identifier, predicate=RDF.type):
477            yield _t
478
479    def _set_type(self, kind: Union[Individual, Identifier, Iterable[_ObjectType]]):
480        if not kind:
481            return
482        if isinstance(kind, (Individual, Identifier)):
483            self.graph.add((self.identifier, RDF.type, classOrIdentifier(kind)))
484        else:
485            for c in kind:
486                assert isinstance(c, (Individual, Identifier))
487                self.graph.add((self.identifier, RDF.type, classOrIdentifier(c)))
488
489    @TermDeletionHelper(RDF.type)
490    def _delete_type(self):
491        """
492        ```python
493        >>> g = Graph()
494        >>> b = Individual(OWL.Restriction, g)
495        >>> b.type = RDFS.Resource
496        >>> len(list(b.type))
497        1
498        >>> del b.type
499        >>> len(list(b.type))
500        0
501
502        ```
503        """
504        pass  # pragma: no cover
505
506    type = property(_get_type, _set_type, _delete_type)
507
508    def _get_identifier(self) -> Identifier:
509        return self.__identifier
510
511    def _set_identifier(self, i: Identifier):
512        assert i
513        if i != self.__identifier:
514            oldstatements_out = [
515                (p, o)
516                for s, p, o in self.graph.triples((self.__identifier, None, None))
517            ]
518            oldstatements_in = [
519                (s, p)
520                for s, p, o in self.graph.triples((None, None, self.__identifier))
521            ]
522            for p1, o1 in oldstatements_out:
523                self.graph.remove((self.__identifier, p1, o1))
524            for s1, p1 in oldstatements_in:
525                self.graph.remove((s1, p1, self.__identifier))
526            self.__identifier = i
527            self.graph.addN([(i, p1, o1, self.graph) for p1, o1 in oldstatements_out])
528            self.graph.addN([(s1, p1, i, self.graph) for s1, p1 in oldstatements_in])
529        if not isinstance(i, BNode):
530            try:
531                prefix, uri, localname = self.graph.compute_qname(i)
532                self.qname = ":".join([prefix, localname])
533            except Exception:  # pragma: no cover
534                pass  # pragma: no cover
535
536    identifier = property(_get_identifier, _set_identifier)
537
538    def _get_sameAs(self) -> Iterable[_ObjectType]:  # noqa: N802
539        for _t in self.graph.objects(subject=self.identifier, predicate=OWL.sameAs):
540            yield _t
541
542    def _set_sameAs(  # noqa: N802
543        self, term: Union[Individual, Identifier, Iterable[_ObjectType]]
544    ):
545        # if not kind:
546        #     return
547        if isinstance(term, (Individual, Identifier)):
548            self.graph.add((self.identifier, OWL.sameAs, classOrIdentifier(term)))
549        else:
550            for c in term:
551                assert isinstance(c, (Individual, Identifier))
552                self.graph.add((self.identifier, OWL.sameAs, classOrIdentifier(c)))
553
554    @TermDeletionHelper(OWL.sameAs)
555    def _delete_sameAs(self):  # noqa: N802
556        pass  # pragma: no cover
557
558    sameAs = property(_get_sameAs, _set_sameAs, _delete_sameAs)  # noqa: N815
559
560
561ACE_NS = Namespace("http://attempto.ifi.uzh.ch/ace_lexicon#")
562
563
564class AnnotatableTerms(Individual):
565    """Terms in an OWL ontology with rdfs:label and rdfs:comment
566
567    Interface with ATTEMPTO (http://attempto.ifi.uzh.ch/site)
568
569    ## Verbalisation of OWL entity IRIS
570
571    ### How are OWL entity IRIs verbalized?
572
573    The OWL verbalizer maps OWL entity IRIs to ACE content words such
574    that
575
576    - OWL individuals map to ACE proper names (PN)
577    - OWL classes map to ACE common nouns (CN)
578    - OWL properties map to ACE transitive verbs (TV)
579
580    There are 6 morphological categories that determine the surface form
581    of an IRI:
582
583    - singular form of a proper name (e.g. John)
584    - singular form of a common noun (e.g. man)
585    - plural form of a common noun (e.g. men)
586    - singular form of a transitive verb (e.g. mans)
587    - plural form of a transitive verb (e.g. man)
588    - past participle form a transitive verb (e.g. manned)
589
590    The user has full control over the eventual surface forms of the IRIs
591    but has to choose them in terms of the above categories.
592    Furthermore,
593
594    - the surface forms must be legal ACE content words (e.g. they
595      should not contain punctuation symbols);
596    - the mapping of IRIs to surface forms must be bidirectional
597      within the same word class, in order to be able to (if needed)
598      parse the verbalization back into OWL in a semantics preserving
599      way.
600
601    ### Using the lexicon
602
603    It is possible to specify the mapping of IRIs to surface forms using
604    the following annotation properties:
605
606    ```
607    http://attempto.ifi.uzh.ch/ace_lexicon#PN_sg
608    http://attempto.ifi.uzh.ch/ace_lexicon#CN_sg
609    http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl
610    http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
611    http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
612    http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg
613    ```
614
615    For example, the following axioms state that if the IRI "#man" is used
616    as a plural common noun, then the wordform men must be used by the
617    verbalizer. If, however, it is used as a singular transitive verb,
618    then mans must be used.
619
620    ```xml
621    <AnnotationAssertion>
622        <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl"/>
623        <IRI>#man</IRI>
624        <Literal datatypeIRI="&xsd;string">men</Literal>
625    </AnnotationAssertion>
626
627    <AnnotationAssertion>
628        <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg"/>
629        <IRI>#man</IRI>
630        <Literal datatypeIRI="&xsd;string">mans</Literal>
631    </AnnotationAssertion>
632    ```
633    """
634
635    def __init__(
636        self,
637        identifier,
638        graph=None,
639        nameAnnotation=None,  # noqa: N803
640        nameIsLabel=False,  # noqa: N803
641    ):
642        super(AnnotatableTerms, self).__init__(identifier, graph)
643        if nameAnnotation:
644            self.setupACEAnnotations()
645            self.PN_sgprop.extent = [
646                (self.identifier, self.handleAnnotation(nameAnnotation))
647            ]
648            if nameIsLabel:
649                self.label = [nameAnnotation]
650
651    def handleAnnotation(self, val):  # noqa: N802
652        return val if isinstance(val, Literal) else Literal(val)
653
654    def setupACEAnnotations(self):  # noqa: N802
655        self.graph.bind("ace", ACE_NS, override=False)
656
657        # PN_sg singular form of a proper name ()
658        self.PN_sgprop = Property(
659            ACE_NS.PN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
660        )
661
662        # CN_sg singular form of a common noun
663        self.CN_sgprop = Property(
664            ACE_NS.CN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
665        )
666
667        # CN_pl plural form of a common noun
668        self.CN_plprop = Property(
669            ACE_NS.CN_pl, baseType=OWL.AnnotationProperty, graph=self.graph
670        )
671
672        # singular form of a transitive verb
673        self.tv_sgprop = Property(
674            ACE_NS.TV_sg, baseType=OWL.AnnotationProperty, graph=self.graph
675        )
676
677        # plural form of a transitive verb
678        self.tv_plprop = Property(
679            ACE_NS.TV_pl, baseType=OWL.AnnotationProperty, graph=self.graph
680        )
681
682        # past participle form a transitive verb
683        self.tv_vbgprop = Property(
684            ACE_NS.TV_vbg, baseType=OWL.AnnotationProperty, graph=self.graph
685        )
686
687    def _get_comment(self):
688        for comment in self.graph.objects(
689            subject=self.identifier, predicate=RDFS.comment
690        ):
691            yield comment
692
693    def _set_comment(self, comment):
694        if not comment:
695            return
696        if isinstance(comment, Identifier):
697            self.graph.add((self.identifier, RDFS.comment, comment))
698        else:
699            for c in comment:
700                self.graph.add((self.identifier, RDFS.comment, c))
701
702    @TermDeletionHelper(RDFS.comment)
703    def _del_comment(self):
704        pass  # pragma: no cover
705
706    comment = property(_get_comment, _set_comment, _del_comment)
707
708    def _get_seealso(self):
709        for seealso in self.graph.objects(
710            subject=self.identifier, predicate=RDFS.seeAlso
711        ):
712            yield seealso
713
714    def _set_seealso(self, seealsos):
715        if not seealsos:
716            return
717        for s in seealsos:
718            self.graph.add((self.identifier, RDFS.seeAlso, s))
719
720    @TermDeletionHelper(RDFS.seeAlso)
721    def _del_seealso(self):
722        pass  # pragma: no cover
723
724    seeAlso = property(_get_seealso, _set_seealso, _del_seealso)  # noqa: N815
725
726    def _get_label(self):
727        for label in self.graph.objects(subject=self.identifier, predicate=RDFS.label):
728            yield label
729
730    def _set_label(self, label):
731        if not label:
732            return
733        if isinstance(label, Identifier):
734            self.graph.add((self.identifier, RDFS.label, label))
735        else:
736            for l_ in label:
737                self.graph.add((self.identifier, RDFS.label, l_))
738
739    @TermDeletionHelper(RDFS.label)
740    def _delete_label(self):
741        """
742        ```python
743        >>> g = Graph()
744        >>> b = Individual(OWL.Restriction,g)
745        >>> b.label = Literal('boo')
746        >>> len(list(b.label))
747        1
748        >>> del b.label
749        >>> len(list(b.label))
750        0
751
752        ```
753        """
754        pass  # pragma: no cover
755
756    label = property(_get_label, _set_label, _delete_label)
757
758
759class Ontology(AnnotatableTerms):
760    """The owl ontology metadata"""
761
762    def __init__(self, identifier=None, imports=None, comment=None, graph=None):
763        super(Ontology, self).__init__(identifier, graph)
764        self.imports = [] if imports is None else imports
765        self.comment = [] if comment is None else comment
766        if (self.identifier, RDF.type, OWL.Ontology) not in self.graph:
767            self.graph.add((self.identifier, RDF.type, OWL.Ontology))
768
769    def setVersion(self, version):  # noqa: N802
770        self.graph.set((self.identifier, OWL.versionInfo, version))
771
772    def _get_imports(self):
773        for owl in self.graph.objects(
774            subject=self.identifier, predicate=OWL["imports"]
775        ):
776            yield owl
777
778    def _set_imports(self, other):
779        if not other:
780            return
781        for o in other:
782            self.graph.add((self.identifier, OWL["imports"], o))
783
784    @TermDeletionHelper(OWL["imports"])
785    def _del_imports(self):
786        pass  # pragma: no cover
787
788    imports = property(_get_imports, _set_imports, _del_imports)
789
790
791def AllClasses(graph):  # noqa: N802
792    for c in set(graph.subjects(predicate=RDF.type, object=OWL.Class)):
793        yield Class(c)
794
795
796def AllProperties(graph):  # noqa: N802
797    prevprops = set()
798    for s, _p, o in graph.triples_choices(
799        (
800            None,
801            RDF.type,
802            [
803                OWL.SymmetricProperty,
804                OWL.FunctionalProperty,
805                OWL.InverseFunctionalProperty,
806                OWL.TransitiveProperty,
807                OWL.DatatypeProperty,
808                OWL.ObjectProperty,
809                OWL.AnnotationProperty,
810            ],
811        )
812    ):
813        if o in [
814            OWL.SymmetricProperty,
815            OWL.InverseFunctionalProperty,
816            OWL.TransitiveProperty,
817            OWL.ObjectProperty,
818        ]:
819            bType = OWL.ObjectProperty  # noqa: N806
820        else:
821            bType = OWL.DatatypeProperty  # noqa: N806
822        if s not in prevprops:
823            prevprops.add(s)
824            yield Property(s, graph=graph, baseType=bType)
825
826
827class ClassNamespaceFactory(Namespace):
828    def term(self, name):
829        return Class(URIRef(self + name))
830
831    def __getitem__(self, key, default=None):
832        return self.term(key)
833
834    def __getattr__(self, name):
835        if name.startswith("__"):  # ignore any special Python names!
836            raise AttributeError
837        else:
838            return self.term(name)
839
840
841CLASS_RELATIONS = set(
842    Namespace("http://www.w3.org/2002/07/owl#resourceProperties")
843).difference(
844    [
845        OWL.onProperty,
846        OWL.allValuesFrom,
847        OWL.hasValue,
848        OWL.someValuesFrom,
849        OWL.inverseOf,
850        OWL.imports,
851        OWL.versionInfo,
852        OWL.backwardCompatibleWith,
853        OWL.incompatibleWith,
854        OWL.unionOf,
855        OWL.intersectionOf,
856        OWL.oneOf,
857    ]
858)
859
860
861def ComponentTerms(cls):  # noqa: N802
862    """
863    Takes a Class instance and returns a generator over the classes that
864    are involved in its definition, ignoring unnamed classes
865    """
866    if OWL.Restriction in cls.type:
867        try:
868            cls = CastClass(cls, Individual.factoryGraph)
869            for _s, _p, inner_class_id in cls.factoryGraph.triples_choices(
870                (cls.identifier, [OWL.allValuesFrom, OWL.someValuesFrom], None)
871            ):
872                inner_class = Class(inner_class_id, skipOWLClassMembership=True)
873                if isinstance(inner_class_id, BNode):
874                    for _c in ComponentTerms(inner_class):
875                        yield _c
876                else:
877                    yield inner_class
878        except Exception:  # pragma: no cover
879            pass  # pragma: no cover
880    else:
881        cls = CastClass(cls, Individual.factoryGraph)
882        if isinstance(cls, BooleanClass):
883            for _cls in cls:
884                _cls = Class(_cls, skipOWLClassMembership=True)
885                if isinstance(_cls.identifier, BNode):
886                    for _c in ComponentTerms(_cls):
887                        yield _c
888                else:
889                    yield _cls
890        else:
891            for inner_class in cls.subClassOf:
892                if isinstance(inner_class.identifier, BNode):
893                    for _c in ComponentTerms(inner_class):
894                        yield _c
895                else:
896                    yield inner_class
897            for _s, _p, o in cls.factoryGraph.triples_choices(
898                (classOrIdentifier(cls), CLASS_RELATIONS, None)
899            ):
900                if isinstance(o, BNode):
901                    for _c in ComponentTerms(CastClass(o, Individual.factoryGraph)):
902                        yield _c
903                else:
904                    yield inner_class
905
906
907def DeepClassClear(class_to_prune):  # noqa: N802
908    """
909    Recursively clear the given class, continuing
910    where any related class is an anonymous class
911
912    ```python
913    >>> EX = Namespace("http://example.com/")
914    >>> g = Graph()
915    >>> g.bind("ex", EX, override=False)
916    >>> Individual.factoryGraph = g
917    >>> classB = Class(EX.B)
918    >>> classC = Class(EX.C)
919    >>> classD = Class(EX.D)
920    >>> classE = Class(EX.E)
921    >>> classF = Class(EX.F)
922    >>> anonClass = EX.someProp @ some @ classD
923    >>> classF += anonClass
924    >>> list(anonClass.subClassOf)
925    [Class: ex:F ]
926    >>> classA = classE | classF | anonClass
927    >>> classB += classA
928    >>> classA.equivalentClass = [Class()]
929    >>> classB.subClassOf = [EX.someProp @ some @ classC]
930    >>> classA
931    ( ex:E OR ex:F OR ( ex:someProp SOME ex:D ) )
932    >>> DeepClassClear(classA)
933    >>> classA
934    (  )
935    >>> list(anonClass.subClassOf)
936    []
937    >>> classB
938    Class: ex:B SubClassOf: ( ex:someProp SOME ex:C )
939
940    >>> otherClass = classD | anonClass
941    >>> otherClass
942    ( ex:D OR ( ex:someProp SOME ex:D ) )
943    >>> DeepClassClear(otherClass)
944    >>> otherClass
945    (  )
946    >>> otherClass.delete()
947    >>> list(g.triples((otherClass.identifier, None, None)))
948    []
949
950    ```
951    """
952
953    def deepClearIfBNode(_class):  # noqa: N802
954        if isinstance(classOrIdentifier(_class), BNode):
955            DeepClassClear(_class)
956
957    class_to_prune = CastClass(class_to_prune, Individual.factoryGraph)
958    for c in class_to_prune.subClassOf:
959        deepClearIfBNode(c)
960    class_to_prune.graph.remove((class_to_prune.identifier, RDFS.subClassOf, None))
961    for c in class_to_prune.equivalentClass:
962        deepClearIfBNode(c)
963    class_to_prune.graph.remove((class_to_prune.identifier, OWL.equivalentClass, None))
964    inverse_class = class_to_prune.complementOf
965    if inverse_class:
966        class_to_prune.graph.remove((class_to_prune.identifier, OWL.complementOf, None))
967        deepClearIfBNode(inverse_class)
968    if isinstance(class_to_prune, BooleanClass):
969        for c in class_to_prune:
970            deepClearIfBNode(c)
971        class_to_prune.clear()
972        class_to_prune.graph.remove(
973            (class_to_prune.identifier, class_to_prune._operator, None)
974        )
975
976
977class MalformedClass(ValueError):  # noqa: N818
978    """
979    !!! warning "Deprecated"
980        This class will be removed in version `7.0.0`.
981    """
982
983    pass
984
985
986class MalformedClassError(MalformedClass):
987    def __init__(self, msg):
988        self.msg = msg
989
990    def __repr__(self):
991        return self.msg
992
993
994def CastClass(c, graph=None):  # noqa: N802
995    graph = graph is None and c.factoryGraph or graph
996    for kind in graph.objects(subject=classOrIdentifier(c), predicate=RDF.type):
997        if kind == OWL.Restriction:
998            kwargs = {"identifier": classOrIdentifier(c), "graph": graph}
999            for _s, p, o in graph.triples((classOrIdentifier(c), None, None)):
1000                if p != RDF.type:
1001                    if p == OWL.onProperty:
1002                        kwargs["onProperty"] = o
1003                    else:
1004                        if p not in Restriction.restrictionKinds:
1005                            continue
1006                        kwargs[str(p.split(str(OWL))[-1])] = o
1007            if not set(
1008                [str(i.split(str(OWL))[-1]) for i in Restriction.restrictionKinds]
1009            ).intersection(kwargs):
1010                raise MalformedClassError("Malformed owl:Restriction")
1011            return Restriction(**kwargs)
1012        else:
1013            for _s, p, _o in graph.triples_choices(
1014                (
1015                    classOrIdentifier(c),
1016                    [OWL.intersectionOf, OWL.unionOf, OWL.oneOf],
1017                    None,
1018                )
1019            ):
1020                if p == OWL.oneOf:
1021                    return EnumeratedClass(classOrIdentifier(c), graph=graph)
1022                else:
1023                    return BooleanClass(classOrIdentifier(c), operator=p, graph=graph)
1024            # assert (classOrIdentifier(c),RDF.type,OWL.Class) in graph
1025            return Class(classOrIdentifier(c), graph=graph, skipOWLClassMembership=True)
1026
1027
1028class Class(AnnotatableTerms):
1029    """'General form' for classes:
1030
1031    The Manchester Syntax (supported in Protege) is used as the basis for the
1032    form of this class
1033
1034    See: http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf:
1035
1036    ```
1037    [Annotation]
1038    ‘Class:’ classID {Annotation
1039    ( (‘SubClassOf:’ ClassExpression)
1040    | (‘EquivalentTo’ ClassExpression)
1041    | (’DisjointWith’ ClassExpression)) }
1042    ```
1043
1044    Appropriate excerpts from OWL Reference:
1045
1046    ".. Subclass axioms provide us with partial definitions: they represent
1047     necessary but not sufficient conditions for establishing class
1048     membership of an individual."
1049
1050    ".. A class axiom may contain (multiple) owl:equivalentClass statements"
1051
1052    "..A class axiom may also contain (multiple) owl:disjointWith statements.."
1053
1054    "..An owl:complementOf property links a class to precisely one class
1055      description."
1056    """
1057
1058    def _serialize(self, graph):
1059        for cl in self.subClassOf:
1060            CastClass(cl, self.graph).serialize(graph)
1061        for cl in self.equivalentClass:
1062            CastClass(cl, self.graph).serialize(graph)
1063        for cl in self.disjointWith:
1064            CastClass(cl, self.graph).serialize(graph)
1065        if self.complementOf:
1066            CastClass(self.complementOf, self.graph).serialize(graph)
1067
1068    def serialize(self, graph):
1069        for fact in self.graph.triples((self.identifier, None, None)):
1070            graph.add(fact)
1071        self._serialize(graph)
1072
1073    def setupNounAnnotations(self, noun_annotations):  # noqa: N802
1074        if isinstance(noun_annotations, tuple):
1075            cn_sgprop, cn_plprop = noun_annotations
1076        else:
1077            cn_sgprop = noun_annotations
1078            cn_plprop = noun_annotations
1079
1080        if cn_sgprop:
1081            self.CN_sgprop.extent = [
1082                (self.identifier, self.handleAnnotation(cn_sgprop))
1083            ]
1084        if cn_plprop:
1085            self.CN_plprop.extent = [
1086                (self.identifier, self.handleAnnotation(cn_plprop))
1087            ]
1088
1089    def __init__(
1090        self,
1091        identifier=None,
1092        subClassOf=None,  # noqa: N803
1093        equivalentClass=None,  # noqa: N803
1094        disjointWith=None,  # noqa: N803
1095        complementOf=None,  # noqa: N803
1096        graph=None,
1097        skipOWLClassMembership=False,  # noqa: N803
1098        comment=None,
1099        nounAnnotations=None,  # noqa: N803
1100        nameAnnotation=None,  # noqa: N803
1101        nameIsLabel=False,  # noqa: N803
1102    ):
1103        super(Class, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)
1104
1105        if nounAnnotations:
1106            self.setupNounAnnotations(nounAnnotations)
1107        if (
1108            not skipOWLClassMembership
1109            and (self.identifier, RDF.type, OWL.Class) not in self.graph
1110            and (self.identifier, RDF.type, OWL.Restriction) not in self.graph
1111        ):
1112            self.graph.add((self.identifier, RDF.type, OWL.Class))
1113
1114        self.subClassOf = [] if subClassOf is None else subClassOf
1115        self.equivalentClass = [] if equivalentClass is None else equivalentClass
1116        self.disjointWith = [] if disjointWith is None else disjointWith
1117        if complementOf:
1118            self.complementOf = complementOf
1119        self.comment = [] if comment is None else comment
1120
1121    def _get_extent(self, graph=None):
1122        for member in (graph is None and self.graph or graph).subjects(
1123            predicate=RDF.type, object=self.identifier
1124        ):
1125            yield member
1126
1127    def _set_extent(self, other):
1128        if not other:
1129            return
1130        for m in other:
1131            self.graph.add((classOrIdentifier(m), RDF.type, self.identifier))
1132
1133    @TermDeletionHelper(RDF.type)
1134    def _del_type(self):
1135        pass  # pragma: no cover
1136
1137    extent = property(_get_extent, _set_extent, _del_type)
1138
1139    def _get_annotation(self, term=RDFS.label):
1140        for annotation in self.graph.objects(subject=self.identifier, predicate=term):
1141            yield annotation
1142
1143    annotation = property(_get_annotation, lambda x: x)  # type: ignore[arg-type,misc]
1144
1145    def _get_extentquery(self):
1146        return (Variable("CLASS"), RDF.type, self.identifier)
1147
1148    def _set_extentquery(self, other):
1149        pass  # pragma: no cover
1150
1151    extentQuery = property(_get_extentquery, _set_extentquery)  # noqa: N815
1152
1153    def __hash__(self):
1154        """
1155        >>> b = Class(OWL.Restriction)
1156        >>> c = Class(OWL.Restriction)
1157        >>> len(set([b,c]))
1158        1
1159        """
1160        return hash(self.identifier)
1161
1162    def __eq__(self, other):
1163        assert isinstance(other, Class), repr(other)
1164        return self.identifier == other.identifier
1165
1166    def __iadd__(self, other):
1167        assert isinstance(other, Class)
1168        other.subClassOf = [self]
1169        return self
1170
1171    def __isub__(self, other):
1172        assert isinstance(other, Class)
1173        self.graph.remove((classOrIdentifier(other), RDFS.subClassOf, self.identifier))
1174        return self
1175
1176    def __invert__(self):
1177        """
1178        Shorthand for Manchester syntax's not operator
1179        """
1180        return Class(complementOf=self)
1181
1182    def __or__(self, other):
1183        """
1184        Construct an anonymous class description consisting of the union of
1185        this class and 'other' and return it
1186        """
1187        return BooleanClass(
1188            operator=OWL.unionOf, members=[self, other], graph=self.graph
1189        )
1190
1191    def __and__(self, other):
1192        """
1193        Construct an anonymous class description consisting of the
1194        intersection of this class and 'other' and return it
1195
1196        Chaining 3 intersections
1197
1198        ```python
1199        >>> exNs = Namespace("http://example.com/")
1200        >>> g = Graph()
1201        >>> g.bind("ex", exNs, override=False)
1202        >>> female = Class(exNs.Female, graph=g)
1203        >>> human = Class(exNs.Human, graph=g)
1204        >>> youngPerson = Class(exNs.YoungPerson, graph=g)
1205        >>> youngWoman = female & human & youngPerson
1206        >>> youngWoman  # doctest: +SKIP
1207        ex:YoungPerson THAT ( ex:Female AND ex:Human )
1208        >>> isinstance(youngWoman, BooleanClass)
1209        True
1210        >>> isinstance(youngWoman.identifier, BNode)
1211        True
1212
1213        ```
1214        """
1215        return BooleanClass(
1216            operator=OWL.intersectionOf, members=[self, other], graph=self.graph
1217        )
1218
1219    def _get_subclassof(self):
1220        for anc in self.graph.objects(
1221            subject=self.identifier, predicate=RDFS.subClassOf
1222        ):
1223            yield Class(anc, graph=self.graph, skipOWLClassMembership=True)
1224
1225    def _set_subclassof(self, other):
1226        if not other:
1227            return
1228        for sc in other:
1229            self.graph.add((self.identifier, RDFS.subClassOf, classOrIdentifier(sc)))
1230
1231    @TermDeletionHelper(RDFS.subClassOf)
1232    def _del_subclassof(self):
1233        pass  # pragma: no cover
1234
1235    subClassOf = property(  # noqa: N815
1236        _get_subclassof, _set_subclassof, _del_subclassof
1237    )
1238
1239    def _get_equivalentclass(self):
1240        for ec in self.graph.objects(
1241            subject=self.identifier, predicate=OWL.equivalentClass
1242        ):
1243            yield Class(ec, graph=self.graph)
1244
1245    def _set_equivalentclass(self, other):
1246        if not other:
1247            return
1248        for sc in other:
1249            self.graph.add(
1250                (self.identifier, OWL.equivalentClass, classOrIdentifier(sc))
1251            )
1252
1253    @TermDeletionHelper(OWL.equivalentClass)
1254    def _del_equivalentclass(self):
1255        pass  # pragma: no cover
1256
1257    equivalentClass = property(  # noqa: N815
1258        _get_equivalentclass, _set_equivalentclass, _del_equivalentclass
1259    )
1260
1261    def _get_disjointwith(self):
1262        for dc in self.graph.objects(
1263            subject=self.identifier, predicate=OWL.disjointWith
1264        ):
1265            yield Class(dc, graph=self.graph)
1266
1267    def _set_disjointwith(self, other):
1268        if not other:
1269            return
1270        for c in other:
1271            self.graph.add((self.identifier, OWL.disjointWith, classOrIdentifier(c)))
1272
1273    @TermDeletionHelper(OWL.disjointWith)
1274    def _del_disjointwith(self):
1275        pass  # pragma: no cover
1276
1277    disjointWith = property(  # noqa: N815
1278        _get_disjointwith, _set_disjointwith, _del_disjointwith
1279    )
1280
1281    def _get_complementof(self):
1282        comp = list(
1283            self.graph.objects(subject=self.identifier, predicate=OWL.complementOf)
1284        )
1285        if not comp:
1286            return None
1287        elif len(comp) == 1:
1288            return Class(comp[0], graph=self.graph)
1289        else:
1290            raise Exception(len(comp))
1291
1292    def _set_complementof(self, other):
1293        if not other:
1294            return
1295        self.graph.add((self.identifier, OWL.complementOf, classOrIdentifier(other)))
1296
1297    @TermDeletionHelper(OWL.complementOf)
1298    def _del_complementof(self):
1299        pass  # pragma: no cover
1300
1301    complementOf = property(  # noqa: N815
1302        _get_complementof, _set_complementof, _del_complementof
1303    )
1304
1305    def _get_parents(self):
1306        """
1307        computed attributes that returns a generator over taxonomic 'parents'
1308        by disjunction, conjunction, and subsumption
1309
1310        ```python
1311        >>> from rdflib.util import first
1312        >>> exNs = Namespace('http://example.com/')
1313        >>> g = Graph()
1314        >>> g.bind("ex", exNs, override=False)
1315        >>> Individual.factoryGraph = g
1316        >>> brother = Class(exNs.Brother)
1317        >>> sister = Class(exNs.Sister)
1318        >>> sibling = brother | sister
1319        >>> sibling.identifier = exNs.Sibling
1320        >>> sibling
1321        ( ex:Brother OR ex:Sister )
1322        >>> first(brother.parents)
1323        Class: ex:Sibling EquivalentTo: ( ex:Brother OR ex:Sister )
1324        >>> parent = Class(exNs.Parent)
1325        >>> male = Class(exNs.Male)
1326        >>> father = parent & male
1327        >>> father.identifier = exNs.Father
1328        >>> list(father.parents)
1329        [Class: ex:Parent , Class: ex:Male ]
1330
1331        ```
1332        """
1333        for parent in itertools.chain(self.subClassOf, self.equivalentClass):
1334            yield parent
1335
1336        link = first(self.factoryGraph.subjects(RDF.first, self.identifier))
1337        if link:
1338            siblingslist = list(self.factoryGraph.transitive_subjects(RDF.rest, link))
1339            if siblingslist:
1340                collectionhead = siblingslist[-1]
1341            else:
1342                collectionhead = link
1343            for disjointclass in self.factoryGraph.subjects(
1344                OWL.unionOf, collectionhead
1345            ):
1346                if isinstance(disjointclass, URIRef):
1347                    yield Class(disjointclass, skipOWLClassMembership=True)
1348        for rdf_list in self.factoryGraph.objects(self.identifier, OWL.intersectionOf):
1349            for member in OWLRDFListProxy([rdf_list], graph=self.factoryGraph):
1350                if isinstance(member, URIRef):
1351                    yield Class(member, skipOWLClassMembership=True)
1352
1353    parents = property(_get_parents)
1354
1355    def isPrimitive(self):  # noqa: N802
1356        if (self.identifier, RDF.type, OWL.Restriction) in self.graph:
1357            return False
1358        # sc = list(self.subClassOf)
1359        ec = list(self.equivalentClass)
1360        for _boolclass, p, rdf_list in self.graph.triples_choices(
1361            # 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]]]"
1362            (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
1363        ):
1364            ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
1365        for _e in ec:
1366            return False
1367        if self.complementOf:
1368            return False
1369        return True
1370
1371    def subSumpteeIds(self):  # noqa: N802
1372        for s in self.graph.subjects(predicate=RDFS.subClassOf, object=self.identifier):
1373            yield s
1374
1375    # def __iter__(self):
1376    #     for s in self.graph.subjects(
1377    #        predicate=RDFS.subClassOf,object=self.identifier):
1378    #         yield Class(s,skipOWLClassMembership=True)
1379
1380    def __repr__(self):
1381        return self.manchesterClass(full=False, normalization=True)
1382
1383    def manchesterClass(self, full=False, normalization=True):  # noqa: N802
1384        """
1385        Returns the Manchester Syntax equivalent for this class
1386        """
1387        exprs = []
1388        sc = list(self.subClassOf)
1389        ec = list(self.equivalentClass)
1390        for _boolclass, p, rdf_list in self.graph.triples_choices(
1391            # 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]]]"
1392            (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
1393        ):
1394            ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
1395        dc = list(self.disjointWith)
1396        c = self.complementOf
1397        if c:
1398            dc.append(c)
1399        klasskind = ""
1400        label = list(self.graph.objects(self.identifier, RDFS.label))
1401        # type error: Incompatible types in assignment (expression has type "str", variable has type "List[Node]")
1402        # type error: Unsupported operand types for + ("str" and "Node")
1403        label = label and "(" + label[0] + ")" or ""  # type: ignore[assignment, operator]
1404        if sc:
1405            if full:
1406                scjoin = "\n                "
1407            else:
1408                scjoin = ", "
1409            nec_statements = [
1410                isinstance(s, Class)
1411                and isinstance(self.identifier, BNode)
1412                and repr(CastClass(s, self.graph))
1413                or
1414                # repr(BooleanClass(classOrIdentifier(s),
1415                #                  operator=None,
1416                #                  graph=self.graph)) or
1417                manchesterSyntax(classOrIdentifier(s), self.graph)
1418                for s in sc
1419            ]
1420            if nec_statements:
1421                klasskind = "Primitive Type %s" % label
1422            exprs.append(
1423                "SubClassOf: %s" % scjoin.join([str(n) for n in nec_statements])
1424            )
1425            if full:
1426                exprs[-1] = "\n    " + exprs[-1]
1427        if ec:
1428            nec_suff_statements = [
1429                isinstance(s, str)
1430                and s
1431                or manchesterSyntax(classOrIdentifier(s), self.graph)
1432                for s in ec
1433            ]
1434            if nec_suff_statements:
1435                klasskind = "A Defined Class %s" % label
1436            exprs.append("EquivalentTo: %s" % ", ".join(nec_suff_statements))
1437            if full:
1438                exprs[-1] = "\n    " + exprs[-1]
1439        if dc:
1440            exprs.append(
1441                "DisjointWith %s\n"
1442                % "\n                 ".join(
1443                    [manchesterSyntax(classOrIdentifier(s), self.graph) for s in dc]
1444                )
1445            )
1446            if full:
1447                exprs[-1] = "\n    " + exprs[-1]
1448        descr = list(self.graph.objects(self.identifier, RDFS.comment))
1449        if full and normalization:
1450            klassdescr = (
1451                klasskind
1452                and "\n    ## %s ##" % klasskind
1453                + (descr and "\n    %s" % descr[0] or "")
1454                + " . ".join(exprs)
1455                or " . ".join(exprs)
1456            )
1457        else:
1458            klassdescr = (
1459                full
1460                and (descr and "\n    %s" % descr[0] or "")
1461                or "" + " . ".join(exprs)
1462            )
1463        return (
1464            isinstance(self.identifier, BNode)
1465            and "Some Class "
1466            or "Class: %s " % self.qname
1467        ) + klassdescr
1468
1469
1470class OWLRDFListProxy:
1471    def __init__(self, rdf_list, members=None, graph=None):
1472        if graph:
1473            self.graph = graph
1474        members = [] if members is None else members
1475        if rdf_list:
1476            self._rdfList = Collection(self.graph, rdf_list[0])
1477            for member in members:
1478                if member not in self._rdfList:
1479                    self._rdfList.append(classOrIdentifier(member))
1480        else:
1481            self._rdfList = Collection(
1482                self.graph, BNode(), [classOrIdentifier(m) for m in members]
1483            )
1484            # type error: "OWLRDFListProxy" has no attribute "identifier"
1485            # type error: "OWLRDFListProxy" has no attribute "_operator"
1486            self.graph.add((self.identifier, self._operator, self._rdfList.uri))  # type: ignore[attr-defined]
1487
1488    def __eq__(self, other):
1489        """
1490        Equivalence of boolean class constructors is determined by
1491        equivalence of its members
1492        """
1493        assert isinstance(other, Class), repr(other) + repr(type(other))
1494        if isinstance(other, BooleanClass):
1495            length = len(self)
1496            if length != len(other):
1497                return False
1498            else:
1499                for idx in range(length):
1500                    if self[idx] != other[idx]:
1501                        return False
1502                    return True
1503        else:
1504            # type error: "OWLRDFListProxy" has no attribute "identifier"
1505            return self.identifier == other.identifier  # type: ignore[attr-defined]
1506
1507    # Redirect python list accessors to the underlying Collection instance
1508    def __len__(self):
1509        return len(self._rdfList)
1510
1511    def index(self, item):
1512        return self._rdfList.index(classOrIdentifier(item))
1513
1514    def __getitem__(self, key):
1515        return self._rdfList[key]
1516
1517    def __setitem__(self, key, value):
1518        self._rdfList[key] = classOrIdentifier(value)
1519
1520    def __delitem__(self, key):
1521        del self._rdfList[key]
1522
1523    def clear(self):
1524        self._rdfList.clear()
1525
1526    def __iter__(self):
1527        for item in self._rdfList:
1528            yield item
1529
1530    def __contains__(self, item):
1531        for i in self._rdfList:
1532            if i == classOrIdentifier(item):
1533                return 1
1534        return 0
1535
1536    def append(self, item):
1537        self._rdfList.append(item)
1538
1539    def __iadd__(self, other):
1540        self._rdfList.append(classOrIdentifier(other))
1541        return self
1542
1543
1544class EnumeratedClass(OWLRDFListProxy, Class):
1545    """Class for owl:oneOf forms:
1546
1547    OWL Abstract Syntax is used
1548
1549    axiom ::= 'EnumeratedClass('
1550        classID ['Deprecated'] { annotation } { individualID } ')'
1551
1552    ```python
1553    >>> exNs = Namespace("http://example.com/")
1554    >>> g = Graph()
1555    >>> g.bind("ex", exNs, override=False)
1556    >>> Individual.factoryGraph = g
1557    >>> ogbujiBros = EnumeratedClass(exNs.ogbujicBros,
1558    ...                              members=[exNs.chime,
1559    ...                                       exNs.uche,
1560    ...                                       exNs.ejike])
1561    >>> ogbujiBros  # doctest: +SKIP
1562    { ex:chime ex:uche ex:ejike }
1563    >>> col = Collection(g, first(
1564    ...    g.objects(predicate=OWL.oneOf, subject=ogbujiBros.identifier)))
1565    >>> sorted([g.qname(item) for item in col])
1566    ['ex:chime', 'ex:ejike', 'ex:uche']
1567    >>> print(g.serialize(format='n3'))  # doctest: +SKIP
1568    @prefix ex: <http://example.com/> .
1569    @prefix owl: <http://www.w3.org/2002/07/owl#> .
1570    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
1571    <BLANKLINE>
1572    ex:ogbujicBros a owl:Class;
1573        owl:oneOf ( ex:chime ex:uche ex:ejike ) .
1574    <BLANKLINE>
1575    <BLANKLINE>
1576
1577    ```
1578    """
1579
1580    _operator = OWL.oneOf
1581
1582    def isPrimitive(self):  # noqa: N802
1583        return False
1584
1585    def __init__(self, identifier=None, members=None, graph=None):
1586        Class.__init__(self, identifier, graph=graph)
1587        members = [] if members is None else members
1588        rdfList = list(  # noqa: N806
1589            self.graph.objects(predicate=OWL.oneOf, subject=self.identifier)
1590        )
1591        OWLRDFListProxy.__init__(self, rdfList, members)
1592
1593    def __repr__(self):
1594        """
1595        Returns the Manchester Syntax equivalent for this class
1596        """
1597        return manchesterSyntax(self._rdfList.uri, self.graph, boolean=self._operator)
1598
1599    def serialize(self, graph):
1600        clonedlist = Collection(graph, BNode())
1601        for cl in self._rdfList:
1602            clonedlist.append(cl)
1603            CastClass(cl, self.graph).serialize(graph)
1604
1605        graph.add((self.identifier, self._operator, clonedlist.uri))
1606        for s, p, o in self.graph.triples((self.identifier, None, None)):
1607            if p != self._operator:
1608                graph.add((s, p, o))
1609        self._serialize(graph)
1610
1611
1612BooleanPredicates = [OWL.intersectionOf, OWL.unionOf]
1613
1614
1615class BooleanClassExtentHelper:
1616    """
1617    ```python
1618    >>> testGraph = Graph()
1619    >>> Individual.factoryGraph = testGraph
1620    >>> EX = Namespace("http://example.com/")
1621    >>> testGraph.bind("ex", EX, override=False)
1622    >>> fire = Class(EX.Fire)
1623    >>> water = Class(EX.Water)
1624    >>> testClass = BooleanClass(members=[fire, water])
1625    >>> testClass2 = BooleanClass(
1626    ...     operator=OWL.unionOf, members=[fire, water])
1627    >>> for c in BooleanClass.getIntersections():
1628    ...     print(c)  # doctest: +SKIP
1629    ( ex:Fire AND ex:Water )
1630    >>> for c in BooleanClass.getUnions():
1631    ...     print(c) #doctest: +SKIP
1632    ( ex:Fire OR ex:Water )
1633
1634    ```
1635    """
1636
1637    def __init__(self, operator):
1638        self.operator = operator
1639
1640    def __call__(self, f):
1641        def _getExtent():  # noqa: N802
1642            for c in Individual.factoryGraph.subjects(self.operator):
1643                yield BooleanClass(c, operator=self.operator)
1644
1645        return _getExtent
1646
1647
1648class Callable:
1649    def __init__(self, anycallable):
1650        self._callfn = anycallable
1651
1652    def __call__(self, *args, **kwargs):
1653        return self._callfn(*args, **kwargs)
1654
1655
1656class BooleanClass(OWLRDFListProxy, Class):
1657    """
1658    See: http://www.w3.org/TR/owl-ref/#Boolean
1659
1660    owl:complementOf is an attribute of Class, however
1661    """
1662
1663    @BooleanClassExtentHelper(OWL.intersectionOf)
1664    @Callable
1665    def getIntersections():  # type: ignore[misc]  # noqa: N802
1666        pass  # pragma: no cover
1667
1668    getIntersections = Callable(getIntersections)  # noqa: N815
1669
1670    @BooleanClassExtentHelper(OWL.unionOf)
1671    @Callable
1672    def getUnions():  # type: ignore[misc]  # noqa: N802
1673        pass  # pragma: no cover
1674
1675    getUnions = Callable(getUnions)  # noqa: N815
1676
1677    def __init__(
1678        self, identifier=None, operator=OWL.intersectionOf, members=None, graph=None
1679    ):
1680        if operator is None:
1681            props = []
1682            for _s, p, _o in graph.triples_choices(
1683                (identifier, [OWL.intersectionOf, OWL.unionOf], None)
1684            ):
1685                props.append(p)
1686                operator = p
1687            assert len(props) == 1, repr(props)
1688        Class.__init__(self, identifier, graph=graph)
1689        assert operator in [OWL.intersectionOf, OWL.unionOf], str(operator)
1690        self._operator = operator
1691        rdf_list = list(self.graph.objects(predicate=operator, subject=self.identifier))
1692        assert (
1693            not members or not rdf_list
1694        ), "This is a previous boolean class description."
1695        OWLRDFListProxy.__init__(self, rdf_list, members)
1696
1697    def copy(self):
1698        """
1699        Create a copy of this class
1700        """
1701        copy_of_class = BooleanClass(
1702            operator=self._operator, members=list(self), graph=self.graph
1703        )
1704        return copy_of_class
1705
1706    def serialize(self, graph):
1707        clonedlist = Collection(graph, BNode())
1708        for cl in self._rdfList:
1709            clonedlist.append(cl)
1710            CastClass(cl, self.graph).serialize(graph)
1711
1712        graph.add((self.identifier, self._operator, clonedlist.uri))
1713
1714        for s, p, o in self.graph.triples((self.identifier, None, None)):
1715            if p != self._operator:
1716                graph.add((s, p, o))
1717        self._serialize(graph)
1718
1719    def isPrimitive(self):  # noqa: N802
1720        return False
1721
1722    def changeOperator(self, newOperator):  # noqa: N802, N803
1723        """
1724        Converts a unionOf / intersectionOf class expression into one
1725        that instead uses the given operator
1726
1727        ```python
1728        >>> testGraph = Graph()
1729        >>> Individual.factoryGraph = testGraph
1730        >>> EX = Namespace("http://example.com/")
1731        >>> testGraph.bind("ex", EX, override=False)
1732        >>> fire = Class(EX.Fire)
1733        >>> water = Class(EX.Water)
1734        >>> testClass = BooleanClass(members=[fire,water])
1735        >>> testClass
1736        ( ex:Fire AND ex:Water )
1737        >>> testClass.changeOperator(OWL.unionOf)
1738        >>> testClass
1739        ( ex:Fire OR ex:Water )
1740        >>> try:
1741        ...     testClass.changeOperator(OWL.unionOf)
1742        ... except Exception as e:
1743        ...     print(e)  # doctest: +SKIP
1744        The new operator is already being used!
1745
1746        ```
1747        """
1748        assert newOperator != self._operator, "The new operator is already being used!"
1749        self.graph.remove((self.identifier, self._operator, self._rdfList.uri))
1750        self.graph.add((self.identifier, newOperator, self._rdfList.uri))
1751        self._operator = newOperator
1752
1753    def __repr__(self):
1754        """
1755        Returns the Manchester Syntax equivalent for this class
1756        """
1757        return manchesterSyntax(
1758            self._rdfList.uri if isinstance(self._rdfList, Collection) else BNode(),
1759            self.graph,
1760            boolean=self._operator,
1761        )
1762
1763    def __or__(self, other):
1764        """
1765        Adds other to the list and returns self
1766        """
1767        assert self._operator == OWL.unionOf
1768        self._rdfList.append(classOrIdentifier(other))
1769        return self
1770
1771
1772def AllDifferent(members):  # noqa: N802
1773    """
1774    TODO: implement this function
1775
1776    DisjointClasses(' description description { description } ')'
1777    """
1778    pass  # pragma: no cover
1779
1780
1781class Restriction(Class):
1782    """
1783    ```
1784    restriction ::= 'restriction('
1785    datavaluedPropertyID dataRestrictionComponent
1786    { dataRestrictionComponent } ')'
1787    | 'restriction(' individualvaluedPropertyID
1788    individualRestrictionComponent
1789    { individualRestrictionComponent } ')'
1790    ```
1791    """
1792
1793    restrictionKinds = [  # noqa: N815
1794        OWL.allValuesFrom,
1795        OWL.someValuesFrom,
1796        OWL.hasValue,
1797        OWL.cardinality,
1798        OWL.maxCardinality,
1799        OWL.minCardinality,
1800    ]
1801
1802    def __init__(
1803        self,
1804        onProperty,  # noqa: N803
1805        graph=None,
1806        allValuesFrom=None,  # noqa: N803
1807        someValuesFrom=None,  # noqa: N803
1808        value=None,
1809        cardinality=None,
1810        maxCardinality=None,  # noqa: N803
1811        minCardinality=None,  # noqa: N803
1812        identifier=None,
1813    ):
1814        graph = Graph() if graph is None else graph
1815        super(Restriction, self).__init__(
1816            identifier, graph=graph, skipOWLClassMembership=True
1817        )
1818        if (
1819            self.identifier,
1820            OWL.onProperty,
1821            propertyOrIdentifier(onProperty),
1822        ) not in graph:
1823            graph.add(
1824                (self.identifier, OWL.onProperty, propertyOrIdentifier(onProperty))
1825            )
1826        self.onProperty = onProperty
1827        restr_types = [
1828            (allValuesFrom, OWL.allValuesFrom),
1829            (someValuesFrom, OWL.someValuesFrom),
1830            (value, OWL.hasValue),
1831            (cardinality, OWL.cardinality),
1832            (maxCardinality, OWL.maxCardinality),
1833            (minCardinality, OWL.minCardinality),
1834        ]
1835        valid_restr_props = [(i, oterm) for (i, oterm) in restr_types if i is not None]
1836        if not len(valid_restr_props):
1837            raise ValueError(
1838                "Missing value. One of: allValuesFrom, someValuesFrom,"
1839                "value, cardinality, maxCardinality or minCardinality"
1840                "must have a value."
1841            )
1842        restriction_range, restriction_type = valid_restr_props.pop()
1843        self.restrictionType = restriction_type
1844        if isinstance(restriction_range, Identifier):
1845            self.restrictionRange = restriction_range
1846        elif isinstance(restriction_range, Class):
1847            self.restrictionRange = classOrIdentifier(restriction_range)
1848        else:
1849            # error: Incompatible types in assignment (expression has type "Optional[Identifier]", variable has type "Identifier")
1850            self.restrictionRange = first(  # type: ignore[assignment]
1851                # type error: Argument 1 to "first" has incompatible type "Generator[Node, None, None]"; expected "Iterable[Identifier]"
1852                self.graph.objects(self.identifier, restriction_type)  # type: ignore[arg-type]
1853            )
1854        if (
1855            self.identifier,
1856            restriction_type,
1857            self.restrictionRange,
1858        ) not in self.graph:
1859            self.graph.add((self.identifier, restriction_type, self.restrictionRange))
1860        assert self.restrictionRange is not None, Class(self.identifier)
1861        if (self.identifier, RDF.type, OWL.Restriction) not in self.graph:
1862            self.graph.add((self.identifier, RDF.type, OWL.Restriction))
1863            self.graph.remove((self.identifier, RDF.type, OWL.Class))
1864
1865    def serialize(self, graph):
1866        """
1867        ```python
1868        >>> g1 = Graph()
1869        >>> g2 = Graph()
1870        >>> EX = Namespace("http://example.com/")
1871        >>> g1.bind("ex", EX, override=False)
1872        >>> g2.bind("ex", EX, override=False)
1873        >>> Individual.factoryGraph = g1
1874        >>> prop = Property(EX.someProp, baseType=OWL.DatatypeProperty)
1875        >>> restr1 = (Property(
1876        ...    EX.someProp,
1877        ...    baseType=OWL.DatatypeProperty)) @ some @ (Class(EX.Foo))
1878        >>> restr1  # doctest: +SKIP
1879        ( ex:someProp SOME ex:Foo )
1880        >>> restr1.serialize(g2)
1881        >>> Individual.factoryGraph = g2
1882        >>> list(Property(
1883        ...     EX.someProp,baseType=None).type
1884        ... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
1885        [rdflib.term.URIRef(
1886            'http://www.w3.org/2002/07/owl#DatatypeProperty')]
1887
1888        ```
1889        """
1890        Property(self.onProperty, graph=self.graph, baseType=None).serialize(graph)
1891        for s, p, o in self.graph.triples((self.identifier, None, None)):
1892            graph.add((s, p, o))
1893            if p in [OWL.allValuesFrom, OWL.someValuesFrom]:
1894                CastClass(o, self.graph).serialize(graph)
1895
1896    def isPrimitive(self):  # noqa: N802
1897        return False
1898
1899    def __hash__(self):
1900        return hash((self.onProperty, self.restrictionRange))
1901
1902    def __eq__(self, other):
1903        """
1904        Equivalence of restrictions is determined by equivalence of the
1905        property in question and the restriction 'range'
1906        """
1907        assert isinstance(other, Class), repr(other) + repr(type(other))
1908        if isinstance(other, Restriction):
1909            return (
1910                other.onProperty == self.onProperty
1911                # type error: "Restriction" has no attribute "restriction_range"; maybe "restrictionRange"?
1912                and other.restriction_range == self.restrictionRange  # type: ignore[attr-defined]
1913            )
1914        else:
1915            return False
1916
1917    def _get_onproperty(self):
1918        return list(
1919            self.graph.objects(subject=self.identifier, predicate=OWL.onProperty)
1920        )[0]
1921
1922    def _set_onproperty(self, prop):
1923        if not prop:
1924            return
1925        triple = (self.identifier, OWL.onProperty, propertyOrIdentifier(prop))
1926        if triple in self.graph:
1927            return
1928        else:
1929            self.graph.set(triple)
1930
1931    @TermDeletionHelper(OWL.onProperty)
1932    def _del_onproperty(self):
1933        pass  # pragma: no cover
1934
1935    onProperty = property(  # noqa: N815
1936        _get_onproperty, _set_onproperty, _del_onproperty
1937    )
1938
1939    def _get_allvaluesfrom(self):
1940        for i in self.graph.objects(
1941            subject=self.identifier, predicate=OWL.allValuesFrom
1942        ):
1943            return Class(i, graph=self.graph)
1944        return None
1945
1946    def _set_allvaluesfrom(self, other):
1947        if not other:
1948            return
1949        triple = (self.identifier, OWL.allValuesFrom, classOrIdentifier(other))
1950        if triple in self.graph:
1951            return
1952        else:
1953            self.graph.set(triple)
1954
1955    @TermDeletionHelper(OWL.allValuesFrom)
1956    def _del_allvaluesfrom(self):
1957        pass  # pragma: no cover
1958
1959    allValuesFrom = property(  # noqa: N815
1960        _get_allvaluesfrom, _set_allvaluesfrom, _del_allvaluesfrom
1961    )
1962
1963    def _get_somevaluesfrom(self):
1964        for i in self.graph.objects(
1965            subject=self.identifier, predicate=OWL.someValuesFrom
1966        ):
1967            return Class(i, graph=self.graph)
1968        return None
1969
1970    def _set_somevaluesfrom(self, other):
1971        if not other:
1972            return
1973        triple = (self.identifier, OWL.someValuesFrom, classOrIdentifier(other))
1974        if triple in self.graph:
1975            return
1976        else:
1977            self.graph.set(triple)
1978
1979    @TermDeletionHelper(OWL.someValuesFrom)
1980    def _del_somevaluesfrom(self):
1981        pass  # pragma: no cover
1982
1983    someValuesFrom = property(  # noqa: N815
1984        _get_somevaluesfrom, _set_somevaluesfrom, _del_somevaluesfrom
1985    )
1986
1987    def _get_hasvalue(self):
1988        for i in self.graph.objects(subject=self.identifier, predicate=OWL.hasValue):
1989            return Class(i, graph=self.graph)
1990        return None
1991
1992    def _set_hasvalue(self, other):
1993        if not other:
1994            return
1995        triple = (self.identifier, OWL.hasValue, classOrIdentifier(other))
1996        if triple in self.graph:
1997            return
1998        else:
1999            self.graph.set(triple)
2000
2001    @TermDeletionHelper(OWL.hasValue)
2002    def _del_hasvalue(self):
2003        pass  # pragma: no cover
2004
2005    hasValue = property(_get_hasvalue, _set_hasvalue, _del_hasvalue)  # noqa: N815
2006
2007    def _get_cardinality(self):
2008        for i in self.graph.objects(subject=self.identifier, predicate=OWL.cardinality):
2009            return Class(i, graph=self.graph)
2010        return None
2011
2012    def _set_cardinality(self, other):
2013        if not other:
2014            return
2015        triple = (self.identifier, OWL.cardinality, classOrTerm(other))
2016        if triple in self.graph:
2017            return
2018        else:
2019            self.graph.set(triple)
2020
2021    @TermDeletionHelper(OWL.cardinality)
2022    def _del_cardinality(self):
2023        pass  # pragma: no cover
2024
2025    cardinality = property(_get_cardinality, _set_cardinality, _del_cardinality)
2026
2027    def _get_maxcardinality(self):
2028        for i in self.graph.objects(
2029            subject=self.identifier, predicate=OWL.maxCardinality
2030        ):
2031            return Class(i, graph=self.graph)
2032        return None
2033
2034    def _set_maxcardinality(self, other):
2035        if not other:
2036            return
2037        triple = (self.identifier, OWL.maxCardinality, classOrTerm(other))
2038        if triple in self.graph:
2039            return
2040        else:
2041            self.graph.set(triple)
2042
2043    @TermDeletionHelper(OWL.maxCardinality)
2044    def _del_maxcardinality(self):
2045        pass  # pragma: no cover
2046
2047    maxCardinality = property(  # noqa: N815
2048        _get_maxcardinality, _set_maxcardinality, _del_maxcardinality
2049    )
2050
2051    def _get_mincardinality(self):
2052        for i in self.graph.objects(
2053            subject=self.identifier, predicate=OWL.minCardinality
2054        ):
2055            return Class(i, graph=self.graph)
2056        return None
2057
2058    def _set_mincardinality(self, other):
2059        if not other:
2060            return
2061        triple = (self.identifier, OWL.minCardinality, classOrIdentifier(other))
2062        if triple in self.graph:
2063            return
2064        else:
2065            self.graph.set(triple)
2066
2067    @TermDeletionHelper(OWL.minCardinality)
2068    def _del_mincardinality(self):
2069        pass  # pragma: no cover
2070
2071    minCardinality = property(  # noqa: N815
2072        _get_mincardinality, _set_mincardinality, _del_mincardinality
2073    )
2074
2075    def restrictionKind(self):  # noqa: N802
2076        for s, p, o in self.graph.triples_choices(
2077            # 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]]]"
2078            (self.identifier, self.restrictionKinds, None)  # type: ignore[arg-type]
2079        ):
2080            # type error: "Node" has no attribute "split"
2081            return p.split(str(OWL))[-1]  # type: ignore[attr-defined]
2082        return None
2083
2084    def __repr__(self):
2085        """
2086        Returns the Manchester Syntax equivalent for this restriction
2087        """
2088        return manchesterSyntax(self.identifier, self.graph)
2089
2090
2091# Infix Operators #
2092
2093
2094some = Infix(
2095    lambda prop, _class: Restriction(prop, graph=_class.graph, someValuesFrom=_class)
2096)
2097only = Infix(
2098    lambda prop, _class: Restriction(prop, graph=_class.graph, allValuesFrom=_class)
2099)
2100max = Infix(
2101    lambda prop, _class: Restriction(prop, graph=prop.graph, maxCardinality=_class)
2102)
2103min = Infix(
2104    lambda prop, _class: Restriction(prop, graph=prop.graph, minCardinality=_class)
2105)
2106exactly = Infix(
2107    lambda prop, _class: Restriction(prop, graph=prop.graph, cardinality=_class)
2108)
2109value = Infix(lambda prop, _class: Restriction(prop, graph=prop.graph, value=_class))
2110
2111# Unused
2112PropertyAbstractSyntax = """
2113%s( %s { %s }
2114%s
2115{ 'super(' datavaluedPropertyID ')'} ['Functional']
2116{ domain( %s ) } { range( %s ) } )"""
2117
2118
2119class Property(AnnotatableTerms):
2120    """
2121    ```
2122    axiom ::= 'DatatypeProperty(' datavaluedPropertyID ['Deprecated']
2123                { annotation }
2124                { 'super(' datavaluedPropertyID ')'} ['Functional']
2125                { 'domain(' description ')' } { 'range(' dataRange ')' } ')'
2126                | 'ObjectProperty(' individualvaluedPropertyID ['Deprecated']
2127                { annotation }
2128                { 'super(' individualvaluedPropertyID ')' }
2129                [ 'inverseOf(' individualvaluedPropertyID ')' ] [ 'Symmetric' ]
2130                [ 'Functional' | 'InverseFunctional' |
2131                'Functional' 'InverseFunctional' |
2132                'Transitive' ]
2133                { 'domain(' description ')' } { 'range(' description ')' } ')
2134    ```
2135    """
2136
2137    def setupVerbAnnotations(self, verb_annotations):  # noqa: N802
2138        """OWL properties map to ACE transitive verbs (TV)
2139
2140        There are 6 morphological categories that determine the surface form
2141        of an IRI:
2142
2143        - singular form of a transitive verb (e.g. mans)
2144        - plural form of a transitive verb (e.g. man)
2145        - past participle form a transitive verb (e.g. manned)
2146        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
2147        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
2148        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg
2149        """
2150
2151        if isinstance(verb_annotations, tuple):
2152            tv_sgprop, tv_plprop, tv_vbg = verb_annotations
2153        else:
2154            tv_sgprop = verb_annotations
2155            tv_plprop = verb_annotations
2156            tv_vbg = verb_annotations
2157        if tv_sgprop:
2158            self.tv_sgprop.extent = [
2159                (self.identifier, self.handleAnnotation(tv_sgprop))
2160            ]
2161        if tv_plprop:
2162            self.tv_plprop.extent = [
2163                (self.identifier, self.handleAnnotation(tv_plprop))
2164            ]
2165        if tv_vbg:
2166            self.tv_vbgprop.extent = [(self.identifier, self.handleAnnotation(tv_vbg))]
2167
2168    def __init__(
2169        self,
2170        identifier=None,
2171        graph=None,
2172        baseType=OWL.ObjectProperty,  # noqa: N803
2173        subPropertyOf=None,  # noqa: N803
2174        domain=None,
2175        range=None,
2176        inverseOf=None,  # noqa: N803
2177        otherType=None,  # noqa: N803
2178        equivalentProperty=None,  # noqa: N803
2179        comment=None,
2180        verbAnnotations=None,  # noqa: N803
2181        nameAnnotation=None,  # noqa: N803
2182        nameIsLabel=False,  # noqa: N803
2183    ):
2184        super(Property, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)
2185        if verbAnnotations:
2186            self.setupVerbAnnotations(verbAnnotations)
2187
2188        assert not isinstance(self.identifier, BNode)
2189        if baseType is None:
2190            # None give, determine via introspection
2191            self._baseType = first(Individual(self.identifier, graph=self.graph).type)
2192        else:
2193            if (self.identifier, RDF.type, baseType) not in self.graph:
2194                self.graph.add((self.identifier, RDF.type, baseType))
2195            self._baseType = baseType
2196        self.subPropertyOf = subPropertyOf
2197        self.inverseOf = inverseOf
2198        self.domain = domain
2199        self.range = range
2200        self.comment = [] if comment is None else comment
2201
2202    def serialize(self, graph):
2203        for fact in self.graph.triples((self.identifier, None, None)):
2204            graph.add(fact)
2205        for p in itertools.chain(self.subPropertyOf, self.inverseOf):
2206            p.serialize(graph)
2207        for c in itertools.chain(self.domain, self.range):
2208            CastClass(c, self.graph).serialize(graph)
2209
2210    def _get_extent(self, graph=None):
2211        for triple in (graph is None and self.graph or graph).triples(
2212            (None, self.identifier, None)
2213        ):
2214            yield triple
2215
2216    def _set_extent(self, other):
2217        if not other:
2218            return
2219        for subj, obj in other:
2220            self.graph.add((subj, self.identifier, obj))
2221
2222    extent = property(_get_extent, _set_extent)
2223
2224    def __repr__(self):
2225        rt = []
2226        if OWL.ObjectProperty in self.type:
2227            rt.append(
2228                "ObjectProperty( %s annotation(%s)"
2229                % (self.qname, first(self.comment) and first(self.comment) or "")
2230            )
2231            if first(self.inverseOf):
2232                # type error: Item "None" of "Optional[Any]" has no attribute "inverseOf"
2233                two_link_inverse = first(first(self.inverseOf).inverseOf)  # type: ignore[union-attr]
2234                if two_link_inverse and two_link_inverse.identifier == self.identifier:
2235                    # type error: Item "None" of "Optional[Any]" has no attribute "qname"
2236                    inverserepr = first(self.inverseOf).qname  # type: ignore[union-attr]
2237                else:
2238                    inverserepr = repr(first(self.inverseOf))
2239                rt.append(
2240                    "  inverseOf( %s )%s"
2241                    % (
2242                        inverserepr,
2243                        OWL.SymmetricProperty in self.type and " Symmetric" or "",
2244                    )
2245                )
2246            for _s, _p, roletype in self.graph.triples_choices(
2247                # 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]]]"
2248                (  # type: ignore[arg-type]
2249                    self.identifier,
2250                    RDF.type,
2251                    [
2252                        OWL.FunctionalProperty,
2253                        OWL.InverseFunctionalProperty,
2254                        OWL.TransitiveProperty,
2255                    ],
2256                )
2257            ):
2258                # type error: "Node" has no attribute "split"
2259                rt.append(str(roletype.split(str(OWL))[-1]))  # type: ignore[attr-defined]
2260        else:
2261            rt.append(
2262                "DatatypeProperty( %s %s"
2263                % (self.qname, first(self.comment) and first(self.comment) or "")
2264            )
2265            for _s, _p, roletype in self.graph.triples(
2266                (self.identifier, RDF.type, OWL.FunctionalProperty)
2267            ):
2268                rt.append("   Functional")
2269
2270        def canonicalName(term, g):  # noqa: N802
2271            normalized_name = classOrIdentifier(term)
2272            if isinstance(normalized_name, BNode):
2273                return term
2274            elif normalized_name.startswith(XSD):
2275                return str(term)
2276            elif first(
2277                g.triples_choices(
2278                    (normalized_name, [OWL.unionOf, OWL.intersectionOf], None)
2279                )
2280            ):
2281                return repr(term)
2282            else:
2283                return str(term.qname)
2284
2285        rt.append(
2286            " ".join(
2287                [
2288                    "   super( %s )" % canonicalName(super_property, self.graph)
2289                    for super_property in self.subPropertyOf
2290                ]
2291            )
2292        )
2293        rt.append(
2294            " ".join(
2295                [
2296                    "   domain( %s )" % canonicalName(domain, self.graph)
2297                    for domain in self.domain
2298                ]
2299            )
2300        )
2301        rt.append(
2302            " ".join(
2303                [
2304                    "   range( %s )" % canonicalName(range, self.graph)
2305                    for range in self.range
2306                ]
2307            )
2308        )
2309        # type error: Incompatible types in assignment (expression has type "str", variable has type "List[str]")
2310        rt = "\n".join([expr for expr in rt if expr])  # type: ignore[assignment]
2311        rt += "\n)"
2312        return rt
2313
2314    def _get_subpropertyof(self):
2315        for anc in self.graph.objects(
2316            subject=self.identifier, predicate=RDFS.subPropertyOf
2317        ):
2318            yield Property(anc, graph=self.graph, baseType=None)
2319
2320    def _set_subpropertyof(self, other):
2321        if not other:
2322            return
2323        for subproperty in other:
2324            self.graph.add(
2325                (self.identifier, RDFS.subPropertyOf, classOrIdentifier(subproperty))
2326            )
2327
2328    @TermDeletionHelper(RDFS.subPropertyOf)
2329    def _del_subpropertyof(self):
2330        pass  # pragma: no cover
2331
2332    subPropertyOf = property(  # noqa: N815
2333        _get_subpropertyof, _set_subpropertyof, _del_subpropertyof
2334    )
2335
2336    def _get_inverseof(self):
2337        for anc in self.graph.objects(subject=self.identifier, predicate=OWL.inverseOf):
2338            yield Property(anc, graph=self.graph, baseType=None)
2339
2340    def _set_inverseof(self, other):
2341        if not other:
2342            return
2343        self.graph.add((self.identifier, OWL.inverseOf, classOrIdentifier(other)))
2344
2345    @TermDeletionHelper(OWL.inverseOf)
2346    def _del_inverseof(self):
2347        pass  # pragma: no cover
2348
2349    inverseOf = property(_get_inverseof, _set_inverseof, _del_inverseof)  # noqa: N815
2350
2351    def _get_domain(self):
2352        for dom in self.graph.objects(subject=self.identifier, predicate=RDFS.domain):
2353            yield Class(dom, graph=self.graph)
2354
2355    def _set_domain(self, other):
2356        if not other:
2357            return
2358        if isinstance(other, (Individual, Identifier)):
2359            self.graph.add((self.identifier, RDFS.domain, classOrIdentifier(other)))
2360        else:
2361            for dom in other:
2362                self.graph.add((self.identifier, RDFS.domain, classOrIdentifier(dom)))
2363
2364    @TermDeletionHelper(RDFS.domain)
2365    def _del_domain(self):
2366        pass  # pragma: no cover
2367
2368    domain = property(_get_domain, _set_domain, _del_domain)
2369
2370    def _get_range(self):
2371        for ran in self.graph.objects(subject=self.identifier, predicate=RDFS.range):
2372            yield Class(ran, graph=self.graph)
2373
2374    def _set_range(self, ranges):
2375        if not ranges:
2376            return
2377        if isinstance(ranges, (Individual, Identifier)):
2378            self.graph.add((self.identifier, RDFS.range, classOrIdentifier(ranges)))
2379        else:
2380            for range in ranges:
2381                self.graph.add((self.identifier, RDFS.range, classOrIdentifier(range)))
2382
2383    @TermDeletionHelper(RDFS.range)
2384    def _del_range(self):
2385        pass  # pragma: no cover
2386
2387    range = property(_get_range, _set_range, _del_range)
2388
2389    def replace(self, other):
2390        # extension = []
2391        for s, _p, o in self.extent:
2392            self.graph.add((s, propertyOrIdentifier(other), o))
2393        self.graph.remove((None, self.identifier, None))
2394
2395
2396def CommonNSBindings(graph, additionalNS=None):  # noqa: N802, N803
2397    """
2398    Takes a graph and binds the common namespaces (rdf,rdfs, & owl)
2399    """
2400    additional_ns = {} if additionalNS is None else additionalNS
2401    namespace_manager = NamespaceManager(graph)
2402    namespace_manager.bind("rdfs", RDFS)
2403    namespace_manager.bind("rdf", RDF)
2404    namespace_manager.bind("owl", OWL)
2405    for prefix, uri in list(additional_ns.items()):
2406        namespace_manager.bind(prefix, uri, override=False)
2407    graph.namespace_manager = namespace_manager