msc87
msc87

Reputation: 1029

How to instantiate an ontology using rdflib?

I have an ontology where I have defined series of classes, subclasses and properties. Now I want to automatically instantiate the ontology with Python code and save it in RDF/XML again and load it in Protege. I have written the following code:

def instantiating_ontology(rdf_address):
from rdflib import *
g = Graph()
input_RDF = g.parse(rdf_address)
#input_RDF = g.open(rdf_address, create=False)
myNamespace="http://www.semanticweb.org/.../ontologies/2015/3/RNO_V5042_RDF"
rno = Namespace(myNamespace+"#")
nodeClass = URIRef(rno+"Node")
arcClass = URIRef(rno+"Arc")
#owlNamespace = 'http://www.w3.org/2002/07/owl#NamedIndividual'
namedIndividual = URIRef('http://www.w3.org/2002/07/owl#NamedIndividual')
rdftype = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
for i in range(0,100):
    individualName = rno + "arc_"+str(arcID)
    #arc_individual= BNode(individualName)
    arc_individual = BNode()
    #g.add()
    #g.add((arc_individual,rdftype, namedIndividual))
    g.add((arc_individual,rdftype, arcClass))
    g.add((arc_individual,rdftype, arcClass))
    #g.commit()
output_address ="RNO_V5042_RDF.owl"
g.serialize(destination = output_address)

The file contains the added triples to the rdf/xml:

  <rdf:Description rdf:nodeID="N0009844208f0490887a02160fbbf8b98">
<rdf:type rdf:resource="http://www.semanticweb.org/ehsan.abdolmajidi/ontologies/2015/3/RNO_V5042#Arc"/>

but when I open the file in Protege there are no instances for the classes.

Can someone tell me if the way I defined instances is wrong or I should use different tags?

Upvotes: 3

Views: 1751

Answers (1)

msc87
msc87

Reputation: 1029

After playing around with the code and the results, I realized that the notion rdf:nodeID should be replaced with rdf:about. to do so I only needed to change

for i in range(0,100):
individualName = rno + "arc_"+str(arcID)
#arc_individual= BNode(individualName)
arc_individual = BNode()        #---> remove this one 
arc_individual = URIRef(individualName)    #----> add this one 
g.add((arc_individual,rdftype, arcClass))
g.add((arc_individual,rdftype, arcClass))
arc_individual = URIRef(individualName)

that might seem easy but took me sometime to understand. I hope this can help others. :D

Upvotes: 3

Related Questions