rdflib.extras package

Submodules

rdflib.extras.cmdlineutils module

rdflib.extras.cmdlineutils.main(target, _help=<function _help>, options='', stdin=True)[source]

A main function for tools that read RDF from files given on commandline or from STDIN (if stdin parameter is true)

rdflib.extras.describer module

A Describer is a stateful utility for creating RDF statements in a semi-declarative manner. It has methods for creating literal values, rel and rev resource relations (somewhat resembling RDFa).

The Describer.rel and Describer.rev methods return a context manager which sets the current about to the referenced resource for the context scope (for use with the with statement).

Full example in the to_rdf method below:

>>> import datetime
>>> from rdflib.graph import Graph
>>> from rdflib.namespace import Namespace, RDFS, FOAF
>>>
>>> ORG_URI = "http://example.org/"
>>>
>>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#")
>>>
>>> class Person:
...     def __init__(self):
...         self.first_name = "Some"
...         self.last_name = "Body"
...         self.username = "some1"
...         self.presentation = "Just a Python & RDF hacker."
...         self.image = "/images/persons/" + self.username + ".jpg"
...         self.site = "http://example.net/"
...         self.start_date = datetime.date(2009, 9, 4)
...     def get_full_name(self):
...         return " ".join([self.first_name, self.last_name])
...     def get_absolute_url(self):
...         return "/persons/" + self.username
...     def get_thumbnail_url(self):
...         return self.image.replace('.jpg', '-thumb.jpg')
...
...     def to_rdf(self):
...         graph = Graph()
...         graph.bind('foaf', FOAF)
...         graph.bind('cv', CV)
...         lang = 'en'
...         d = Describer(graph, base=ORG_URI)
...         d.about(self.get_absolute_url()+'#person')
...         d.rdftype(FOAF.Person)
...         d.value(FOAF.name, self.get_full_name())
...         d.value(FOAF.givenName, self.first_name)
...         d.value(FOAF.familyName, self.last_name)
...         d.rel(FOAF.homepage, self.site)
...         d.value(RDFS.comment, self.presentation, lang=lang)
...         with d.rel(FOAF.depiction, self.image):
...             d.rdftype(FOAF.Image)
...             d.rel(FOAF.thumbnail, self.get_thumbnail_url())
...         with d.rev(CV.aboutPerson):
...             d.rdftype(CV.CV)
...             with d.rel(CV.hasWorkHistory):
...                 d.value(CV.startDate, self.start_date)
...                 d.rel(CV.employedIn, ORG_URI+"#company")
...         return graph
...
>>> person_graph = Person().to_rdf()
>>> expected = Graph().parse(data='''<?xml version="1.0" encoding="utf-8"?>
... <rdf:RDF
...   xmlns:foaf="http://xmlns.com/foaf/0.1/"
...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...   xmlns:cv="http://purl.org/captsolo/resume-rdf/0.2/cv#"
...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
...   <foaf:Person rdf:about="http://example.org/persons/some1#person">
...     <foaf:name>Some Body</foaf:name>
...     <foaf:givenName>Some</foaf:givenName>
...     <foaf:familyName>Body</foaf:familyName>
...     <foaf:depiction>
...       <foaf:Image
...         rdf:about=
...             "http://example.org/images/persons/some1.jpg">
...         <foaf:thumbnail
...         rdf:resource=
...             "http://example.org/images/persons/some1-thumb.jpg"/>
...       </foaf:Image>
...     </foaf:depiction>
...     <rdfs:comment xml:lang="en">
...             Just a Python &amp; RDF hacker.
...     </rdfs:comment>
...     <foaf:homepage rdf:resource="http://example.net/"/>
...   </foaf:Person>
...   <cv:CV>
...     <cv:aboutPerson
...         rdf:resource="http://example.org/persons/some1#person">
...     </cv:aboutPerson>
...     <cv:hasWorkHistory>
...       <rdf:Description>
...         <cv:startDate
...             rdf:datatype="http://www.w3.org/2001/XMLSchema#date"
...             >2009-09-04</cv:startDate>
...         <cv:employedIn rdf:resource="http://example.org/#company"/>
...       </rdf:Description>
...     </cv:hasWorkHistory>
...   </cv:CV>
... </rdf:RDF>
... ''', format="xml")
>>>
>>> from rdflib.compare import isomorphic
>>> isomorphic(person_graph, expected)  
True
class rdflib.extras.describer.Describer(graph=None, about=None, base=None)[source]

Bases: object

__dict__ = mappingproxy({'__module__': 'rdflib.extras.describer', '__init__': <function Describer.__init__>, 'about': <function Describer.about>, 'value': <function Describer.value>, 'rel': <function Describer.rel>, 'rev': <function Describer.rev>, 'rdftype': <function Describer.rdftype>, '_current': <function Describer._current>, '_subject_stack': <function Describer._subject_stack>, '__dict__': <attribute '__dict__' of 'Describer' objects>, '__weakref__': <attribute '__weakref__' of 'Describer' objects>, '__doc__': None, '__annotations__': {}})
__init__(graph=None, about=None, base=None)[source]
__module__ = 'rdflib.extras.describer'
__weakref__

list of weak references to the object (if defined)

about(subject, **kws)[source]

Sets the current subject. Will convert the given object into an URIRef if it’s not an Identifier.

Usage:

>>> d = Describer()
>>> d._current() 
rdflib.term.BNode(...)
>>> d.about("http://example.org/")
>>> d._current()
rdflib.term.URIRef('http://example.org/')
rdftype(t)[source]

Shorthand for setting rdf:type of the current subject.

Usage:

>>> from rdflib import URIRef
>>> from rdflib.namespace import RDF, RDFS
>>> d = Describer(about="http://example.org/")
>>> d.rdftype(RDFS.Resource)
>>> (URIRef('http://example.org/'),
...     RDF.type, RDFS.Resource) in d.graph
True
rel(p, o=None, **kws)[source]

Set an object for the given property. Will convert the given object into an URIRef if it’s not an Identifier. If none is given, a new BNode is used.

Returns a context manager for use in a with block, within which the given object is used as current subject.

Usage:

>>> from rdflib import URIRef
>>> from rdflib.namespace import RDF, RDFS
>>> d = Describer(about="/", base="http://example.org/")
>>> _ctxt = d.rel(RDFS.seeAlso, "/about")
>>> d.graph.value(URIRef('http://example.org/'), RDFS.seeAlso)
rdflib.term.URIRef('http://example.org/about')

>>> with d.rel(RDFS.seeAlso, "/more"):
...     d.value(RDFS.label, "More")
>>> (URIRef('http://example.org/'), RDFS.seeAlso,
...         URIRef('http://example.org/more')) in d.graph
True
>>> d.graph.value(URIRef('http://example.org/more'), RDFS.label)
rdflib.term.Literal('More')
rev(p, s=None, **kws)[source]

Same as rel, but uses current subject as object of the relation. The given resource is still used as subject in the returned context manager.

Usage:

>>> from rdflib import URIRef
>>> from rdflib.namespace import RDF, RDFS
>>> d = Describer(about="http://example.org/")
>>> with d.rev(RDFS.seeAlso, "http://example.net/"):
...     d.value(RDFS.label, "Net")
>>> (URIRef('http://example.net/'), RDFS.seeAlso,
...         URIRef('http://example.org/')) in d.graph
True
>>> d.graph.value(URIRef('http://example.net/'), RDFS.label)
rdflib.term.Literal('Net')
value(p, v, **kws)[source]

Set a literal value for the given property. Will cast the value to an Literal if a plain literal is given.

Usage:

>>> from rdflib import URIRef
>>> from rdflib.namespace import RDF, RDFS
>>> d = Describer(about="http://example.org/")
>>> d.value(RDFS.label, "Example")
>>> d.graph.value(URIRef('http://example.org/'), RDFS.label)
rdflib.term.Literal('Example')
rdflib.extras.describer.cast_identifier(ref, **kws)[source]
rdflib.extras.describer.cast_value(v, **kws)[source]

rdflib.extras.external_graph_libs module

Convert (to and) from rdflib graphs to other well known graph libraries.

Currently the following libraries are supported: - networkx: MultiDiGraph, DiGraph, Graph - graph_tool: Graph

Doctests in this file are all skipped, as we can’t run them conditionally if networkx or graph_tool are available and they would err otherwise. see ../../test/test_extras_external_graph_libs.py for conditional tests

rdflib.extras.external_graph_libs.rdflib_to_graphtool(graph, v_prop_names=['term'], e_prop_names=['term'], transform_s=<function <lambda>>, transform_p=<function <lambda>>, transform_o=<function <lambda>>)[source]

Converts the given graph into a graph_tool.Graph().

The subjects and objects are the later vertices of the Graph. The predicates become edges.

Parameters:
  • graph: a rdflib.Graph.

  • v_prop_names: a list of names for the vertex properties. The default is set to [‘term’] (see transform_s, transform_o below).

  • e_prop_names: a list of names for the edge properties.

  • transform_s: callable with s, p, o input. Should return a dictionary containing a value for each name in v_prop_names. By default is set to {‘term’: s} which in combination with v_prop_names = [‘term’] adds s as ‘term’ property to the generated vertex for s.

  • transform_p: similar to transform_s, but wrt. e_prop_names. By default returns {‘term’: p} which adds p as a property to the generated edge between the vertex for s and the vertex for o.

  • transform_o: similar to transform_s.

Returns: graph_tool.Graph()

>>> from rdflib import Graph, URIRef, Literal
>>> g = Graph()
>>> a, b, l = URIRef('a'), URIRef('b'), Literal('l')
>>> p, q = URIRef('p'), URIRef('q')
>>> edges = [(a, p, b), (a, q, b), (b, p, a), (b, p, l)]
>>> for t in edges:
...     g.add(t)
...
>>> mdg = rdflib_to_graphtool(g)
>>> len(list(mdg.edges()))
4
>>> from graph_tool import util as gt_util
>>> vpterm = mdg.vertex_properties['term']
>>> va = gt_util.find_vertex(mdg, vpterm, a)[0]
>>> vb = gt_util.find_vertex(mdg, vpterm, b)[0]
>>> vl = gt_util.find_vertex(mdg, vpterm, l)[0]
>>> (va, vb) in [(e.source(), e.target()) for e in list(mdg.edges())]
True
>>> epterm = mdg.edge_properties['term']
>>> len(list(gt_util.find_edge(mdg, epterm, p))) == 3
True
>>> len(list(gt_util.find_edge(mdg, epterm, q))) == 1
True
>>> mdg = rdflib_to_graphtool(
...     g,
...     e_prop_names=[str('name')],
...     transform_p=lambda s, p, o: {str('name'): unicode(p)})
>>> epterm = mdg.edge_properties['name']
>>> len(list(gt_util.find_edge(mdg, epterm, unicode(p)))) == 3
True
>>> len(list(gt_util.find_edge(mdg, epterm, unicode(q)))) == 1
True
Parameters:
rdflib.extras.external_graph_libs.rdflib_to_networkx_digraph(graph, calc_weights=True, edge_attrs=<function <lambda>>, **kwds)[source]

Converts the given graph into a networkx.DiGraph.

As an rdflib.Graph() can contain multiple edges between nodes, by default adds the a ‘triples’ attribute to the single DiGraph edge with a list of all triples between s and o. Also by default calculates the edge weight as the length of triples.

Parameters:
  • graph: a rdflib.Graph.

  • calc_weights: If true calculate multi-graph edge-count as edge ‘weight’

  • edge_attrs: Callable to construct later edge_attributes. It receives

    3 variables (s, p, o) and should construct a dictionary that is passed to networkx’s add_edge(s, o, **attrs) function.

    By default this will include setting the ‘triples’ attribute here, which is treated specially by us to be merged. Other attributes of multi-edges will only contain the attributes of the first edge. If you don’t want the ‘triples’ attribute for tracking, set this to lambda s, p, o: {}.

Returns: networkx.DiGraph

>>> from rdflib import Graph, URIRef, Literal
>>> g = Graph()
>>> a, b, l = URIRef('a'), URIRef('b'), Literal('l')
>>> p, q = URIRef('p'), URIRef('q')
>>> edges = [(a, p, b), (a, q, b), (b, p, a), (b, p, l)]
>>> for t in edges:
...     g.add(t)
...
>>> dg = rdflib_to_networkx_digraph(g)
>>> dg[a][b]['weight']
2
>>> sorted(dg[a][b]['triples']) == [(a, p, b), (a, q, b)]
True
>>> len(dg.edges())
3
>>> dg.size()
3
>>> dg.size(weight='weight')
4.0
>>> dg = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s,p,o:{})
>>> 'weight' in dg[a][b]
False
>>> 'triples' in dg[a][b]
False
Parameters:
rdflib.extras.external_graph_libs.rdflib_to_networkx_graph(graph, calc_weights=True, edge_attrs=<function <lambda>>, **kwds)[source]

Converts the given graph into a networkx.Graph.

As an rdflib.Graph() can contain multiple directed edges between nodes, by default adds the a ‘triples’ attribute to the single DiGraph edge with a list of triples between s and o in graph. Also by default calculates the edge weight as the len(triples).

Parameters:
  • graph: a rdflib.Graph.

  • calc_weights: If true calculate multi-graph edge-count as edge ‘weight’

  • edge_attrs: Callable to construct later edge_attributes. It receives

    3 variables (s, p, o) and should construct a dictionary that is passed to networkx’s add_edge(s, o, **attrs) function.

    By default this will include setting the ‘triples’ attribute here, which is treated specially by us to be merged. Other attributes of multi-edges will only contain the attributes of the first edge. If you don’t want the ‘triples’ attribute for tracking, set this to lambda s, p, o: {}.

Returns:

networkx.Graph

>>> from rdflib import Graph, URIRef, Literal
>>> g = Graph()
>>> a, b, l = URIRef('a'), URIRef('b'), Literal('l')
>>> p, q = URIRef('p'), URIRef('q')
>>> edges = [(a, p, b), (a, q, b), (b, p, a), (b, p, l)]
>>> for t in edges:
...     g.add(t)
...
>>> ug = rdflib_to_networkx_graph(g)
>>> ug[a][b]['weight']
3
>>> sorted(ug[a][b]['triples']) == [(a, p, b), (a, q, b), (b, p, a)]
True
>>> len(ug.edges())
2
>>> ug.size()
2
>>> ug.size(weight='weight')
4.0
>>> ug = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s,p,o:{})
>>> 'weight' in ug[a][b]
False
>>> 'triples' in ug[a][b]
False
Parameters:
rdflib.extras.external_graph_libs.rdflib_to_networkx_multidigraph(graph, edge_attrs=<function <lambda>>, **kwds)[source]

Converts the given graph into a networkx.MultiDiGraph.

The subjects and objects are the later nodes of the MultiDiGraph. The predicates are used as edge keys (to identify multi-edges).

Parameters:
  • graph: a rdflib.Graph.

  • edge_attrs: Callable to construct later edge_attributes. It receives

    3 variables (s, p, o) and should construct a dictionary that is passed to networkx’s add_edge(s, o, **attrs) function.

    By default this will include setting the MultiDiGraph key=p here. If you don’t want to be able to re-identify the edge later on, you can set this to lambda s, p, o: {}. In this case MultiDiGraph’s default (increasing ints) will be used.

Returns:

networkx.MultiDiGraph

>>> from rdflib import Graph, URIRef, Literal
>>> g = Graph()
>>> a, b, l = URIRef('a'), URIRef('b'), Literal('l')
>>> p, q = URIRef('p'), URIRef('q')
>>> edges = [(a, p, b), (a, q, b), (b, p, a), (b, p, l)]
>>> for t in edges:
...     g.add(t)
...
>>> mdg = rdflib_to_networkx_multidigraph(g)
>>> len(mdg.edges())
4
>>> mdg.has_edge(a, b)
True
>>> mdg.has_edge(a, b, key=p)
True
>>> mdg.has_edge(a, b, key=q)
True
>>> mdg = rdflib_to_networkx_multidigraph(g, edge_attrs=lambda s,p,o: {})
>>> mdg.has_edge(a, b, key=0)
True
>>> mdg.has_edge(a, b, key=1)
True
Parameters:

graph (Graph) –

rdflib.extras.infixowl module

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'))  
rdflib.extras.infixowl.AllClasses(graph)[source]
rdflib.extras.infixowl.AllDifferent(members)[source]

TODO: implement this function

DisjointClasses(’ description description { description } ‘)’

rdflib.extras.infixowl.AllProperties(graph)[source]
class rdflib.extras.infixowl.AnnotatableTerms(identifier, graph=None, nameAnnotation=None, nameIsLabel=False)[source]

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>
__init__(identifier, graph=None, nameAnnotation=None, nameIsLabel=False)[source]
__module__ = 'rdflib.extras.infixowl'
property comment
handleAnnotation(val)[source]
property label
property seeAlso
setupACEAnnotations()[source]
class rdflib.extras.infixowl.BooleanClass(identifier=None, operator=rdflib.term.URIRef('http://www.w3.org/2002/07/owl#intersectionOf'), members=None, graph=None)[source]

Bases: OWLRDFListProxy, Class

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

owl:complementOf is an attribute of Class, however

__init__(identifier=None, operator=rdflib.term.URIRef('http://www.w3.org/2002/07/owl#intersectionOf'), members=None, graph=None)[source]
__module__ = 'rdflib.extras.infixowl'
__or__(other)[source]

Adds other to the list and returns self

__repr__()[source]

Returns the Manchester Syntax equivalent for this class

changeOperator(newOperator)[source]

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)  
The new operator is already being used!
copy()[source]

Create a copy of this class

getIntersections = <rdflib.extras.infixowl.Callable object>[source]
getUnions = <rdflib.extras.infixowl.Callable object>[source]
isPrimitive()[source]
serialize(graph)[source]
class rdflib.extras.infixowl.Callable(anycallable)[source]

Bases: object

__call__(*args, **kwargs)[source]

Call self as a function.

__dict__ = mappingproxy({'__module__': 'rdflib.extras.infixowl', '__init__': <function Callable.__init__>, '__call__': <function Callable.__call__>, '__dict__': <attribute '__dict__' of 'Callable' objects>, '__weakref__': <attribute '__weakref__' of 'Callable' objects>, '__doc__': None, '__annotations__': {}})
__init__(anycallable)[source]
__module__ = 'rdflib.extras.infixowl'
__weakref__

list of weak references to the object (if defined)

rdflib.extras.infixowl.CastClass(c, graph=None)[source]
class rdflib.extras.infixowl.Class(identifier=None, subClassOf=None, equivalentClass=None, disjointWith=None, complementOf=None, graph=None, skipOWLClassMembership=False, comment=None, nounAnnotations=None, nameAnnotation=None, nameIsLabel=False)[source]

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.”

__and__(other)[source]

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  
ex:YoungPerson THAT ( ex:Female AND ex:Human )
>>> isinstance(youngWoman, BooleanClass)
True
>>> isinstance(youngWoman.identifier, BNode)
True
__eq__(other)[source]

Return self==value.

__hash__()[source]
>>> b = Class(OWL.Restriction)
>>> c = Class(OWL.Restriction)
>>> len(set([b,c]))
1
__iadd__(other)[source]
__init__(identifier=None, subClassOf=None, equivalentClass=None, disjointWith=None, complementOf=None, graph=None, skipOWLClassMembership=False, comment=None, nounAnnotations=None, nameAnnotation=None, nameIsLabel=False)[source]
__invert__()[source]

Shorthand for Manchester syntax’s not operator

__isub__(other)[source]
__module__ = 'rdflib.extras.infixowl'
__or__(other)[source]

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

__repr__(full=False, normalization=True)[source]

Returns the Manchester Syntax equivalent for this class

property annotation
property complementOf
property disjointWith
property equivalentClass
property extent
property extentQuery
isPrimitive()[source]
property parents

computed attributes that returns a generator over taxonomic ‘parents’ by disjunction, conjunction, and subsumption

>>> from rdflib.util import first
>>> exNs = Namespace('http://example.com/')
>>> g = Graph()
>>> g.bind("ex", exNs, override=False)
>>> Individual.factoryGraph = g
>>> brother = Class(exNs.Brother)
>>> sister = Class(exNs.Sister)
>>> sibling = brother | sister
>>> sibling.identifier = exNs.Sibling
>>> sibling
( ex:Brother OR ex:Sister )
>>> first(brother.parents)
Class: ex:Sibling EquivalentTo: ( ex:Brother OR ex:Sister )
>>> parent = Class(exNs.Parent)
>>> male = Class(exNs.Male)
>>> father = parent & male
>>> father.identifier = exNs.Father
>>> list(father.parents)
[Class: ex:Parent , Class: ex:Male ]
serialize(graph)[source]
setupNounAnnotations(noun_annotations)[source]
property subClassOf
subSumpteeIds()[source]
class rdflib.extras.infixowl.ClassNamespaceFactory(value: str | bytes)[source]

Bases: Namespace

__getattr__(name)[source]
__getitem__(key, default=None)[source]

Return self[key].

__module__ = 'rdflib.extras.infixowl'
term(name)[source]
rdflib.extras.infixowl.CommonNSBindings(graph, additionalNS=None)[source]

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

rdflib.extras.infixowl.ComponentTerms(cls)[source]

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

rdflib.extras.infixowl.DeepClassClear(class_to_prune)[source]

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)))
[]
class rdflib.extras.infixowl.EnumeratedClass(identifier=None, members=None, graph=None)[source]

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  
{ 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'))  
@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#> .

ex:ogbujicBros a owl:Class;
    owl:oneOf ( ex:chime ex:uche ex:ejike ) .

__init__(identifier=None, members=None, graph=None)[source]
__module__ = 'rdflib.extras.infixowl'
__repr__()[source]

Returns the Manchester Syntax equivalent for this class

isPrimitive()[source]
serialize(graph)[source]
rdflib.extras.infixowl.GetIdentifiedClasses(graph)[source]
class rdflib.extras.infixowl.Individual(identifier=None, graph=None)[source]

Bases: object

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

__dict__ = mappingproxy({'__module__': 'rdflib.extras.infixowl', '__doc__': '\n    A typed individual, the base class of the InfixOWL classes.\n\n    ', 'factoryGraph': <Graph identifier=Na46377468c3f4198b531c199eb26f0ec (<class 'rdflib.graph.Graph'>)>, 'serialize': <function Individual.serialize>, '__init__': <function Individual.__init__>, 'clearInDegree': <function Individual.clearInDegree>, 'clearOutDegree': <function Individual.clearOutDegree>, 'delete': <function Individual.delete>, 'replace': <function Individual.replace>, '_get_type': <function Individual._get_type>, '_set_type': <function Individual._set_type>, '_delete_type': <function TermDeletionHelper.__call__.<locals>._remover>, 'type': <property object>, '_get_identifier': <function Individual._get_identifier>, '_set_identifier': <function Individual._set_identifier>, 'identifier': <property object>, '_get_sameAs': <function Individual._get_sameAs>, '_set_sameAs': <function Individual._set_sameAs>, '_delete_sameAs': <function TermDeletionHelper.__call__.<locals>._remover>, 'sameAs': <property object>, '__dict__': <attribute '__dict__' of 'Individual' objects>, '__weakref__': <attribute '__weakref__' of 'Individual' objects>, '__annotations__': {}})
__init__(identifier=None, graph=None)[source]
__module__ = 'rdflib.extras.infixowl'
__weakref__

list of weak references to the object (if defined)

clearInDegree()[source]

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

clearOutDegree()[source]

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.

delete()[source]

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

factoryGraph = <Graph identifier=Na46377468c3f4198b531c199eb26f0ec (<class 'rdflib.graph.Graph'>)>
property identifier: Identifier
replace(other)[source]

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
property sameAs: Iterable[Node]
serialize(graph)[source]
property type: Iterable[Node]
class rdflib.extras.infixowl.Infix(function)[source]

Bases: object

__call__(value1, value2)[source]

Call self as a function.

__dict__ = mappingproxy({'__module__': 'rdflib.extras.infixowl', '__init__': <function Infix.__init__>, '__rlshift__': <function Infix.__rlshift__>, '__rshift__': <function Infix.__rshift__>, '__rmatmul__': <function Infix.__rmatmul__>, '__matmul__': <function Infix.__matmul__>, '__call__': <function Infix.__call__>, '__dict__': <attribute '__dict__' of 'Infix' objects>, '__weakref__': <attribute '__weakref__' of 'Infix' objects>, '__doc__': None, '__annotations__': {}})
__init__(function)[source]
__matmul__(other)[source]
__module__ = 'rdflib.extras.infixowl'
__rlshift__(other)[source]
__rmatmul__(other)[source]
__rshift__(other)[source]
__weakref__

list of weak references to the object (if defined)

exception rdflib.extras.infixowl.MalformedClass[source]

Bases: ValueError

Deprecated since version TODO-NEXT-VERSION: This class will be removed in version 7.0.0.

__module__ = 'rdflib.extras.infixowl'
__weakref__

list of weak references to the object (if defined)

exception rdflib.extras.infixowl.MalformedClassError(msg)[source]

Bases: MalformedClass

__init__(msg)[source]
__module__ = 'rdflib.extras.infixowl'
__repr__()[source]

Return repr(self).

class rdflib.extras.infixowl.OWLRDFListProxy(rdf_list, members=None, graph=None)[source]

Bases: object

__contains__(item)[source]
__delitem__(key)[source]
__dict__ = mappingproxy({'__module__': 'rdflib.extras.infixowl', '__init__': <function OWLRDFListProxy.__init__>, '__eq__': <function OWLRDFListProxy.__eq__>, '__len__': <function OWLRDFListProxy.__len__>, 'index': <function OWLRDFListProxy.index>, '__getitem__': <function OWLRDFListProxy.__getitem__>, '__setitem__': <function OWLRDFListProxy.__setitem__>, '__delitem__': <function OWLRDFListProxy.__delitem__>, 'clear': <function OWLRDFListProxy.clear>, '__iter__': <function OWLRDFListProxy.__iter__>, '__contains__': <function OWLRDFListProxy.__contains__>, 'append': <function OWLRDFListProxy.append>, '__iadd__': <function OWLRDFListProxy.__iadd__>, '__dict__': <attribute '__dict__' of 'OWLRDFListProxy' objects>, '__weakref__': <attribute '__weakref__' of 'OWLRDFListProxy' objects>, '__doc__': None, '__hash__': None, '__annotations__': {}})
__eq__(other)[source]

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

__getitem__(key)[source]
__hash__ = None
__iadd__(other)[source]
__init__(rdf_list, members=None, graph=None)[source]
__iter__()[source]
__len__()[source]
__module__ = 'rdflib.extras.infixowl'
__setitem__(key, value)[source]
__weakref__

list of weak references to the object (if defined)

append(item)[source]
clear()[source]
index(item)[source]
class rdflib.extras.infixowl.Ontology(identifier=None, imports=None, comment=None, graph=None)[source]

Bases: AnnotatableTerms

The owl ontology metadata

__init__(identifier=None, imports=None, comment=None, graph=None)[source]
__module__ = 'rdflib.extras.infixowl'
property imports
setVersion(version)[source]
class rdflib.extras.infixowl.Property(identifier=None, graph=None, baseType=rdflib.term.URIRef('http://www.w3.org/2002/07/owl#ObjectProperty'), subPropertyOf=None, domain=None, range=None, inverseOf=None, otherType=None, equivalentProperty=None, comment=None, verbAnnotations=None, nameAnnotation=None, nameIsLabel=False)[source]

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 ‘)’ } ‘)

__init__(identifier=None, graph=None, baseType=rdflib.term.URIRef('http://www.w3.org/2002/07/owl#ObjectProperty'), subPropertyOf=None, domain=None, range=None, inverseOf=None, otherType=None, equivalentProperty=None, comment=None, verbAnnotations=None, nameAnnotation=None, nameIsLabel=False)[source]
__module__ = 'rdflib.extras.infixowl'
__repr__()[source]

Return repr(self).

property domain
property extent
property inverseOf
property range
replace(other)[source]

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
serialize(graph)[source]
setupVerbAnnotations(verb_annotations)[source]

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

property subPropertyOf
class rdflib.extras.infixowl.Restriction(onProperty, graph=None, allValuesFrom=None, someValuesFrom=None, value=None, cardinality=None, maxCardinality=None, minCardinality=None, identifier=None)[source]

Bases: Class

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

__eq__(other)[source]

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

__hash__()[source]
>>> b = Class(OWL.Restriction)
>>> c = Class(OWL.Restriction)
>>> len(set([b,c]))
1
__init__(onProperty, graph=None, allValuesFrom=None, someValuesFrom=None, value=None, cardinality=None, maxCardinality=None, minCardinality=None, identifier=None)[source]
__module__ = 'rdflib.extras.infixowl'
__repr__()[source]

Returns the Manchester Syntax equivalent for this restriction

property allValuesFrom
property cardinality
property hasValue
isPrimitive()[source]
property maxCardinality
property minCardinality
property onProperty
restrictionKind()[source]
restrictionKinds = [rdflib.term.URIRef('http://www.w3.org/2002/07/owl#allValuesFrom'), rdflib.term.URIRef('http://www.w3.org/2002/07/owl#someValuesFrom'), rdflib.term.URIRef('http://www.w3.org/2002/07/owl#hasValue'), rdflib.term.URIRef('http://www.w3.org/2002/07/owl#cardinality'), rdflib.term.URIRef('http://www.w3.org/2002/07/owl#maxCardinality'), rdflib.term.URIRef('http://www.w3.org/2002/07/owl#minCardinality')]
serialize(graph)[source]
>>> 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  
( ex:someProp SOME ex:Foo )
>>> restr1.serialize(g2)
>>> Individual.factoryGraph = g2
>>> list(Property(
...     EX.someProp,baseType=None).type
... ) 
[rdflib.term.URIRef(
    'http://www.w3.org/2002/07/owl#DatatypeProperty')]
property someValuesFrom
rdflib.extras.infixowl.classOrIdentifier(thing)[source]
rdflib.extras.infixowl.classOrTerm(thing)[source]
rdflib.extras.infixowl.generateQName(graph, uri)[source]
rdflib.extras.infixowl.manchesterSyntax(thing, store, boolean=None, transientList=False)[source]

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

rdflib.extras.infixowl.propertyOrIdentifier(thing)[source]

rdflib.extras.shacl module

Utilities for interacting with SHACL Shapes Graphs more easily.

exception rdflib.extras.shacl.SHACLPathError[source]

Bases: Exception

__module__ = 'rdflib.extras.shacl'
__weakref__

list of weak references to the object (if defined)

rdflib.extras.shacl.parse_shacl_path(shapes_graph, path_identifier)[source]

Parse a valid SHACL path (e.g. the object of a triple with predicate sh:path) from a Graph as a URIRef if the path is simply a predicate or a Path otherwise.

Parameters:
  • shapes_graph (Graph) – A Graph containing the path to be parsed

  • path_identifier (Node) – A Node of the path

Return type:

Union[URIRef, Path]

Returns:

A URIRef or a Path

Module contents