Search code examples
owljena

Is there a way in Jena to see that an OntClass is coming from an imported ontology?


I have an ontology which import bfo. In my test case I have only one Class which is a sub-class of entity:

<rdf:RDF xmlns="http://my.ontology/ontologyTest#"
     xml:base="http://my.ontology/ontologyTest"
     xmlns:da="http://my.ontology/ontologyTest#"
     xmlns:dc="http://purl.org/dc/elements/1.1/"
     xmlns:obo="http://purl.obolibrary.org/obo/"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:foaf="http://xmlns.com/foaf/0.1/"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     xmlns:skos="http://www.w3.org/2004/02/skos/core#"
     xmlns:terms="http://purl.org/dc/terms/">
    <owl:Ontology rdf:about="http://my.ontology/ontologyTest">
        <owl:imports rdf:resource="http://purl.obolibrary.org/obo/bfo/2019-08-26/bfo.owl"/>
    </owl:Ontology>
    
    <owl:Class rdf:about="http://my.ontology/ontologyTest#Event">
        <rdfs:subClassOf rdf:resource="http://purl.obolibrary.org/obo/BFO_0000001"/>
    </owl:Class>
   
</rdf:RDF>

When I open the ontology, I am doing:

OntModel model = createModel("OWL_MEM");
FileManager.get().readModel(model, uri.toString());
Model _model = model.getRawModel();
model = new OntModelImpl(OntModelSpec.OWL_MEM, _model);
ExtendedIterator classes = model.listClasses();
while (classes.hasNext()) {
    OntClass theOwlClass = (OntClass) classes.next();
    if (thisClass.getNameSpace() == null && thisClass.getLocalName() == null) {
        continue;
    }
    ...
}

I am getting all the Classes, both from my Ontology (here it is Event), but also from the imported ontologies. Is there a way in Jena to know that an OntClass is from an imported ontology and is not declared in my current Ontology?


Solution

  • With Apache Jena, you can:

    • List the URIs of all imported ontologies model.listImportedOntologyURIs()
    • List all the classes of an imported ontology model.getImportedModel(uri).listClasses()

    You can then write a method to check if an OntClass comes from an imported OntModel:

    public boolean isFromImportedOntology(OntClass ontClass, OntModel ontModel) {
      for (String uri : ontModel.listImportedOntologyURIs()) {
        Set<OntClass> importedClasses = ontModel.getImportedModel(uri).listClasses().toSet();
        if (importedClasses.contains(ontClass)) {
          return true;
        }
      }
      return false;
    }
    

    Note: Thanks to UninformedUser for base ideas.