Search code examples
javaowlowl-api

Get equivalent classes in order


I need to get equivalent classes of an OWL Class in the same order as in the .owl file.

I use this code

for(OWLClassExpression cls: clazz.getEquivalentClasses(ontology) ) { 

Set <OWLClass> classes_of_the_Expression =cls.getClassesInSignature();
}

But this code gets them randomly.

Please find below an example of cases I treat. Here, dog_owner class is an equivalent Class and intersection of both person and dog classes. By executing my java code I get first dog class, then person class; and I need to get the inverse which means person class then dog class. Because I need precisely the first class of the equivalent classes.

<owl:Class rdf:about="http://owl.man.ac.uk/2005/07/sssw/peopleeemodifiée#dog_owner">
<owl:equivalentClass>
  <owl:Class>
    <owl:intersectionOf rdf:parseType="Collection">
      <owl:Class rdf:about="http://owl.man.ac.uk/2005/07/sssw/peopleeemodifiée#person"/>
      <owl:Restriction>
        <owl:onProperty>
          <owl:ObjectProperty rdf:about="http://owl.man.ac.uk/2005/07/sssw/peopleeemodifiée#has_pet"/>
        </owl:onProperty>
        <owl:someValuesFrom rdf:resource="http://owl.man.ac.uk/2005/07/sssw/peopleeemodifiée#dog"/>
      </owl:Restriction>
    </owl:intersectionOf>
  </owl:Class>
</owl:equivalentClass>
<rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string"
>dog owner</rdfs:label>
<rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string"
></rdfs:comment>


Solution

  • In order to only take into account the named classes inside an intersection included in an equivalent classes axiom, you can use visitors:

    OWLEquivalentClassesAxiom ax=null;
    ax.accept(new OWLObjectVisitor() {
        @Override
        public void visit(OWLObjectIntersectionOf ce) {
            ce.operands().filter(x->x.isOWLClass()).forEach(x->{
                // this is where x is Person, or any other 
                // named class in the intersection;
                // anonymous classes are skipped
            });
        }
    });
    

    For OWLAPI 3:

    for(OWLClass clazzzz : ontology.getClassesInSignature()) {
        for(OWLEquivalentClassesAxiom ax: ontology.getEquivalentClassesAxioms(clazzzz)) {
            OWLObjectVisitorAdapter visitor = new OWLObjectVisitorAdapter() {
            @Override
            public void visit(OWLObjectIntersectionOf ce) {
                for (OWLClassExpression e : ce.getOperands()) {
                    if (!e.isAnonymous()) {
                        // this is where x is Person, or any other
                        // named class in the intersection;
                        // anonymous classes are skipped
                    }
                }
            }
            };
            ax.accept(visitor);
        }
    }