Example #1
0
 public Set<OWLClass> getClasses() {
   Set<OWLClass> classSet = new HashSet<OWLClass>();
   for (OWLClass clase : _ontology.getClassesInSignature()) {
     classSet.add(clase);
   }
   return classSet;
 }
  private void runWithSeparateFiles() {
    if (owlFile == null) {
      throw new NullPointerException("You have to specify an ontology file!");
    }

    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    OWLOntology ontology = null;
    OBDADataFactory obdaDataFactory = OBDADataFactoryImpl.getInstance();
    try {
      ontology = manager.loadOntologyFromOntologyDocument((new File(owlFile)));

      if (disableReasoning) {
        /*
         * when reasoning is disabled, we extract only the declaration assertions for the vocabulary
         */
        ontology = extractDeclarations(manager, ontology);
      }

      Collection<Predicate> predicates = new ArrayList<>();

      for (OWLClass owlClass : ontology.getClassesInSignature()) {
        Predicate predicate = obdaDataFactory.getClassPredicate(owlClass.getIRI().toString());
        predicates.add(predicate);
      }
      for (OWLDataProperty owlDataProperty : ontology.getDataPropertiesInSignature()) {
        Predicate predicate =
            obdaDataFactory.getDataPropertyPredicate(owlDataProperty.getIRI().toString());
        predicates.add(predicate);
      }
      for (OWLObjectProperty owlObjectProperty : ontology.getObjectPropertiesInSignature()) {
        Predicate predicate =
            obdaDataFactory.getObjectPropertyPredicate(owlObjectProperty.getIRI().toString());
        predicates.add(predicate);
      }

      OBDAModel obdaModel = loadMappingFile(mappingFile);

      Ontology inputOntology = OWLAPI3TranslatorUtility.translate(ontology);

      obdaModel.declareAll(inputOntology.getVocabulary());

      int numPredicates = predicates.size();

      int i = 1;
      for (Predicate predicate : predicates) {
        System.err.println(String.format("Materializing %s (%d/%d)", predicate, i, numPredicates));
        serializePredicate(ontology, inputOntology, obdaModel, predicate, outputFile, format);
        i++;
      }

    } catch (OWLOntologyCreationException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * This method makes sure is used to setup a new/fresh OBDA model. This is done by replacing the
   * instance this.obdacontroller (the OBDA model) with a new object. On creation listeners for the
   * datasources, mappings and queries are setup so that changes in these trigger and ontology
   * change.
   *
   * <p>Additionally, this method configures all available OBDAOWLReasonerFacotry objects to have a
   * reference to the newly created OBDA model and to the global preference object. This is
   * necessary so that the factories are able to pass the OBDA model to the reasoner instances when
   * they are created.
   */
  private void setupNewOBDAModel() {
    OBDAModel activeOBDAModel = getActiveOBDAModel();

    if (activeOBDAModel != null) {
      return;
    }
    activeOBDAModel = dfac.getOBDAModel();

    activeOBDAModel.addSourcesListener(dlistener);
    activeOBDAModel.addMappingsListener(mlistener);
    queryController.addListener(qlistener);

    OWLModelManager mmgr = owlEditorKit.getOWLWorkspace().getOWLModelManager();

    Set<OWLOntology> ontologies = mmgr.getOntologies();
    for (OWLOntology ontology : ontologies) {
      // Setup the entity declarations
      for (OWLClass c : ontology.getClassesInSignature()) {
        OClass pred = ofac.createClass(c.getIRI().toString());
        activeOBDAModel.declareClass(pred);
      }
      for (OWLObjectProperty r : ontology.getObjectPropertiesInSignature()) {
        ObjectPropertyExpression pred = ofac.createObjectProperty(r.getIRI().toString());
        activeOBDAModel.declareObjectProperty(pred);
      }
      for (OWLDataProperty p : ontology.getDataPropertiesInSignature()) {
        DataPropertyExpression pred = ofac.createDataProperty(p.getIRI().toString());
        activeOBDAModel.declareDataProperty(pred);
      }
    }

    // Setup the prefixes
    PrefixOWLOntologyFormat prefixManager =
        PrefixUtilities.getPrefixOWLOntologyFormat(mmgr.getActiveOntology());
    //		addOBDACommonPrefixes(prefixManager);

    PrefixManagerWrapper prefixwrapper = new PrefixManagerWrapper(prefixManager);
    activeOBDAModel.setPrefixManager(prefixwrapper);

    OWLOntology activeOntology = mmgr.getActiveOntology();

    String defaultPrefix = prefixManager.getDefaultPrefix();
    if (defaultPrefix == null) {
      OWLOntologyID ontologyID = activeOntology.getOntologyID();
      defaultPrefix = ontologyID.getOntologyIRI().toURI().toString();
    }
    activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, defaultPrefix);

    // Add the model
    URI modelUri = activeOntology.getOntologyID().getOntologyIRI().toURI();
    obdamodels.put(modelUri, activeOBDAModel);
  }
 private void rebuild() {
   typeNodes.clear();
   if (reasoner != null) {
     Set<OWLOntology> importsClosure = reasoner.getRootOntology().getImportsClosure();
     for (OWLOntology ont : importsClosure) {
       for (OWLClass cls : ont.getClassesInSignature()) {
         final Set<OWLNamedIndividual> inds =
             reasoner.getInstances(cls, showDirect).getFlattened();
         if (!inds.isEmpty()) {
           typeNodes.put(cls, new HashSet<OWLObject>(inds));
         }
       }
     }
   }
   fireHierarchyChanged();
 }
Example #5
0
  /**
   * <b>Motivation</b>: OWL reasoners do not return superclass expressions If we want to find all
   * class expressions that may hold for a class then we must pre-coordinate all possible
   * expressions within the subset of OWL we care about. <br>
   * This class generates all satisfiable class expressions of the form r some c (for the
   * cross-product of R x C), as well as all class expressions that have been used (which may
   * include nested expressions)
   *
   * <p>The results are stored in queryClassMap
   *
   * @param precomputePropertyClassCombinations
   */
  @Deprecated
  private void generateQueryOntology(boolean precomputePropertyClassCombinations) {
    queryClassMap = new HashMap<OWLClass, OWLClassExpression>();

    getReasoner().flush();

    if (precomputePropertyClassCombinations) {
      LOG.debug("Precomputing all OP x Class combos");
      // cross-product of P x C
      // TODO - reflexivity and local reflexivity?
      for (OWLObjectProperty p : tboxOntology.getObjectPropertiesInSignature(true)) {
        LOG.debug(" materializing P some C for P=:" + p);
        for (OWLClass c : tboxOntology.getClassesInSignature(true)) {
          OWLObjectSomeValuesFrom r = getOWLDataFactory().getOWLObjectSomeValuesFrom(p, c);
          // LOG.debug(" QMAP:"+r);
          addClassExpressionToQueryMap(r);
        }
      }
    }

    // all expressions used in ontology
    for (OWLOntology ont : tboxOntology.getImportsClosure()) {
      LOG.debug("Finding all nested anonymous expressions");
      for (OWLAxiom ax : ont.getAxioms()) {
        // TODO - check if this is the nest closure. ie (r some (r2 some (r3 some ...)))
        for (OWLClassExpression x : ax.getNestedClassExpressions()) {
          if (x.isAnonymous()) {
            // LOG.debug(" QMAP+:"+x);
            addClassExpressionToQueryMap(x);
          }
        }
      }
    }
    if (LOG.isDebugEnabled()) {
      for (OWLOntology ont : collectedAxioms.keySet()) {
        LOG.debug("TOTAL axioms in QMAP: " + collectedAxioms.get(ont).size());
      }
    }
    LOG.debug("Adding collected axioms");
    addCollectedAxioms();
    LOG.debug("Flushing reasoner...");
    reasoner.flush();
    LOG.debug("Flushed reasoner");
  }
Example #6
0
 private void compareClassificationResults(
     OWLOntology ontology, OWLReasoner reasoner, Jedis resultStore, Jedis idReader)
     throws Exception {
   Set<OWLClass> classes = ontology.getClassesInSignature();
   Pipeline resultPipeline = resultStore.pipelined();
   double classCount = 0;
   int multiplier = 1;
   double totalCount = 0;
   for (OWLClass cl : classes) {
     classCount++;
     double classProgress = (classCount / classes.size()) * 100;
     Set<OWLClass> reasonerSuperclasses = reasoner.getSuperClasses(cl, false).getFlattened();
     // add cl itself to S(X) computed by reasoner. That is missing
     // in its result.
     reasonerSuperclasses.add(cl);
     // adding equivalent classes -- they are not considered if asked for superclasses
     Iterator<OWLClass> iterator = reasoner.getEquivalentClasses(cl).iterator();
     while (iterator.hasNext()) reasonerSuperclasses.add(iterator.next());
     String classToCheckID = conceptToID(cl.toString(), idReader);
     List<Response<Double>> responseList = new ArrayList<Response<Double>>();
     for (OWLClass scl : reasonerSuperclasses) {
       String key = conceptToID(scl.toString(), idReader);
       responseList.add(resultPipeline.zscore(key, classToCheckID));
     }
     resultPipeline.sync();
     double hitCount = 0;
     for (Response<Double> response : responseList) {
       if (response.get() != null) hitCount++;
     }
     totalCount += (hitCount / reasonerSuperclasses.size());
     if (classProgress >= (5 * multiplier)) {
       System.out.println(
           "% of no. of classes looked at: "
               + classProgress
               + "\tProgress %: "
               + (totalCount / classCount) * 100);
       multiplier++;
     }
   }
   double progress = totalCount / classes.size();
   System.out.println("\nProgress %: " + (progress * 100));
 }
  private void importFile(
      InputStream in, IRI documentIRI, File inDir, Authorizations authorizations) throws Exception {
    byte[] inFileData = IOUtils.toByteArray(in);

    Reader inFileReader = new InputStreamReader(new ByteArrayInputStream(inFileData));

    OWLOntologyLoaderConfiguration config = new OWLOntologyLoaderConfiguration();
    OWLOntologyManager m = createOwlOntologyManager(config, documentIRI);

    OWLOntologyDocumentSource documentSource = new ReaderDocumentSource(inFileReader, documentIRI);
    OWLOntology o = m.loadOntologyFromOntologyDocument(documentSource, config);

    storeOntologyFile(new ByteArrayInputStream(inFileData), documentIRI);

    for (OWLClass ontologyClass : o.getClassesInSignature()) {
      if (!o.isDeclared(ontologyClass, false)) {
        continue;
      }
      importOntologyClass(o, ontologyClass, inDir, authorizations);
    }

    for (OWLDataProperty dataTypeProperty : o.getDataPropertiesInSignature()) {
      if (!o.isDeclared(dataTypeProperty, false)) {
        continue;
      }
      importDataProperty(o, dataTypeProperty);
    }

    for (OWLObjectProperty objectProperty : o.getObjectPropertiesInSignature()) {
      if (!o.isDeclared(objectProperty, false)) {
        continue;
      }
      importObjectProperty(o, objectProperty);
    }

    for (OWLObjectProperty objectProperty : o.getObjectPropertiesInSignature()) {
      if (!o.isDeclared(objectProperty, false)) {
        continue;
      }
      importInverseOf(o, objectProperty);
    }
  }
  public static Map<OWLClass, Set<OWLObjectSomeValuesFrom>> getExpressions(
      OWLOntology ontology, Set<OWLObjectProperty> properties, OWLClassFilter filter) {
    final ExpressionMaterializingReasonerFactory rf =
        new ExpressionMaterializingReasonerFactory(new ElkReasonerFactory());
    final ExpressionMaterializingReasoner reasoner = rf.createReasoner(ontology);
    try {
      reasoner.materializeExpressions(properties);
      final Map<OWLClass, Set<OWLObjectSomeValuesFrom>> newAxioms =
          new HashMap<OWLClass, Set<OWLObjectSomeValuesFrom>>();
      for (OWLClass cls : ontology.getClassesInSignature()) {
        if (filter != null && filter.use(cls) == false) {
          continue;
        }
        // find existing some value froms
        Set<OWLObjectSomeValuesFrom> existingSVFs =
            getSuperSVFs(ontology.getSubClassAxiomsForSubClass(cls));
        // get all direct super classes
        Set<OWLClassExpression> directSuperCE = reasoner.getSuperClassExpressions(cls, true);
        // filter for SVFs
        Set<OWLObjectSomeValuesFrom> directSuperSVFs = getSVFs(directSuperCE);

        // missing direct SVFs, calculate using a set difference
        Set<OWLObjectSomeValuesFrom> missingSVFs = Sets.difference(directSuperSVFs, existingSVFs);

        // add to result set
        if (missingSVFs.isEmpty() == false) {
          missingSVFs = new HashSet<OWLObjectSomeValuesFrom>(missingSVFs);
          if (filter != null) {
            missingSVFs = filterSVFs(filter, missingSVFs);
          }
          if (missingSVFs.isEmpty() == false) {
            newAxioms.put(cls, missingSVFs);
          }
        }
      }
      return newAxioms;
    } finally {
      reasoner.dispose();
    }
  }
  public void writeOntology() throws OWLRendererException {
    if (ontologies.size() != 1) {
      throw new OWLRuntimeException("Can only render one ontology");
    }
    OWLOntology ontology = getOntologies().iterator().next();
    writePrefixMap();
    writeNewLine();
    writeOntologyHeader(ontology);

    for (OWLAnnotationProperty prop : ontology.getAnnotationPropertiesInSignature()) {
      write(prop);
    }
    for (OWLDatatype datatype : ontology.getDatatypesInSignature()) {
      write(datatype);
    }
    for (OWLObjectProperty prop : ontology.getObjectPropertiesInSignature()) {
      write(prop);
      OWLObjectPropertyExpression invProp = prop.getInverseProperty();
      if (!ontology.getAxioms(invProp).isEmpty()) {
        write(invProp);
      }
    }
    for (OWLDataProperty prop : ontology.getDataPropertiesInSignature()) {
      write(prop);
    }
    for (OWLClass cls : ontology.getClassesInSignature()) {
      write(cls);
    }
    for (OWLNamedIndividual ind : ontology.getIndividualsInSignature()) {
      write(ind);
    }
    for (OWLAnonymousIndividual ind : ontology.getReferencedAnonymousIndividuals()) {
      write(ind);
    }
    // Nary disjoint classes axioms
    event = new RendererEvent(this, ontology);
    for (OWLDisjointClassesAxiom ax : ontology.getAxioms(AxiomType.DISJOINT_CLASSES)) {
      if (ax.getClassExpressions().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getClassExpressions(), ax);
        writeSection(DISJOINT_CLASSES, map, ",", false, ontology);
      }
    }
    // Nary equivalent classes axioms
    for (OWLEquivalentClassesAxiom ax : ontology.getAxioms(AxiomType.EQUIVALENT_CLASSES)) {
      if (ax.getClassExpressions().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getClassExpressions(), ax);
        writeSection(EQUIVALENT_CLASSES, map, ",", false, ontology);
      }
    }
    // Nary disjoint properties
    for (OWLDisjointObjectPropertiesAxiom ax :
        ontology.getAxioms(AxiomType.DISJOINT_OBJECT_PROPERTIES)) {
      if (ax.getProperties().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getProperties(), ax);
        writeSection(DISJOINT_PROPERTIES, map, ",", false, ontology);
      }
    }
    // Nary equivlant properties
    for (OWLEquivalentObjectPropertiesAxiom ax :
        ontology.getAxioms(AxiomType.EQUIVALENT_OBJECT_PROPERTIES)) {
      if (ax.getProperties().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getProperties(), ax);
        writeSection(EQUIVALENT_PROPERTIES, map, ",", false, ontology);
      }
    }
    // Nary disjoint properties
    for (OWLDisjointDataPropertiesAxiom ax :
        ontology.getAxioms(AxiomType.DISJOINT_DATA_PROPERTIES)) {
      if (ax.getProperties().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getProperties(), ax);
        writeSection(DISJOINT_PROPERTIES, map, ",", false, ontology);
      }
    }
    // Nary equivalent properties
    for (OWLEquivalentDataPropertiesAxiom ax :
        ontology.getAxioms(AxiomType.EQUIVALENT_DATA_PROPERTIES)) {
      if (ax.getProperties().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getProperties(), ax);
        writeSection(EQUIVALENT_PROPERTIES, map, ",", false, ontology);
      }
    }
    // Nary different individuals
    for (OWLDifferentIndividualsAxiom ax : ontology.getAxioms(AxiomType.DIFFERENT_INDIVIDUALS)) {
      if (ax.getIndividuals().size() > 2) {
        SectionMap map = new SectionMap();
        map.add(ax.getIndividuals(), ax);
        writeSection(DIFFERENT_INDIVIDUALS, map, ",", false, ontology);
      }
    }
    for (SWRLRule rule : ontology.getAxioms(AxiomType.SWRL_RULE)) {
      writeSection(RULE, Collections.singleton(rule), ", ", false);
    }
    flush();
  }
Example #10
0
  private OWLOntology parseWithReasoner(OWLOntologyManager manager, OWLOntology ontology) {
    try {
      PelletOptions.load(new URL("http://" + cssLocation + "pellet.properties"));
      PelletReasoner reasoner = PelletReasonerFactory.getInstance().createReasoner(ontology);
      reasoner.getKB().prepare();
      List<InferredAxiomGenerator<? extends OWLAxiom>> generators =
          new ArrayList<InferredAxiomGenerator<? extends OWLAxiom>>();
      generators.add(new InferredSubClassAxiomGenerator());
      generators.add(new InferredClassAssertionAxiomGenerator());
      generators.add(new InferredDisjointClassesAxiomGenerator());
      generators.add(new InferredEquivalentClassAxiomGenerator());
      generators.add(new InferredEquivalentDataPropertiesAxiomGenerator());
      generators.add(new InferredEquivalentObjectPropertyAxiomGenerator());
      generators.add(new InferredInverseObjectPropertiesAxiomGenerator());
      generators.add(new InferredPropertyAssertionGenerator());
      generators.add(new InferredSubDataPropertyAxiomGenerator());
      generators.add(new InferredSubObjectPropertyAxiomGenerator());

      InferredOntologyGenerator iog = new InferredOntologyGenerator(reasoner, generators);

      OWLOntologyID id = ontology.getOntologyID();
      Set<OWLImportsDeclaration> declarations = ontology.getImportsDeclarations();
      Set<OWLAnnotation> annotations = ontology.getAnnotations();

      Map<OWLEntity, Set<OWLAnnotationAssertionAxiom>> entityAnnotations =
          new HashMap<OWLEntity, Set<OWLAnnotationAssertionAxiom>>();
      for (OWLClass aEntity : ontology.getClassesInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }
      for (OWLObjectProperty aEntity : ontology.getObjectPropertiesInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }
      for (OWLDataProperty aEntity : ontology.getDataPropertiesInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }
      for (OWLNamedIndividual aEntity : ontology.getIndividualsInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }
      for (OWLAnnotationProperty aEntity : ontology.getAnnotationPropertiesInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }
      for (OWLDatatype aEntity : ontology.getDatatypesInSignature()) {
        entityAnnotations.put(aEntity, aEntity.getAnnotationAssertionAxioms(ontology));
      }

      manager.removeOntology(ontology);
      OWLOntology inferred = manager.createOntology(id);
      iog.fillOntology(manager, inferred);

      for (OWLImportsDeclaration decl : declarations) {
        manager.applyChange(new AddImport(inferred, decl));
      }
      for (OWLAnnotation ann : annotations) {
        manager.applyChange(new AddOntologyAnnotation(inferred, ann));
      }
      for (OWLClass aEntity : inferred.getClassesInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }
      for (OWLObjectProperty aEntity : inferred.getObjectPropertiesInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }
      for (OWLDataProperty aEntity : inferred.getDataPropertiesInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }
      for (OWLNamedIndividual aEntity : inferred.getIndividualsInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }
      for (OWLAnnotationProperty aEntity : inferred.getAnnotationPropertiesInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }
      for (OWLDatatype aEntity : inferred.getDatatypesInSignature()) {
        applyAnnotations(aEntity, entityAnnotations, manager, inferred);
      }

      return inferred;
    } catch (FileNotFoundException e1) {
      return ontology;
    } catch (MalformedURLException e1) {
      return ontology;
    } catch (IOException e1) {
      return ontology;
    } catch (OWLOntologyCreationException e) {
      return ontology;
    }
  }
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      //			args = new String[] { "/home/yzhou/backup/20141212/univ-bench-dl-queries.owl"};
      args = new String[] {PagodaTester.onto_dir + "fly/fly-all-in-one_rolledUp.owl"};
      //			args = new String[] { PagodaTester.onto_dir +
      // "dbpedia/integratedOntology-all-in-one-minus-datatype.owl" };
      //			args = new String[] { PagodaTester.onto_dir + "npd/npd-all-minus-datatype.owl" };
      //			args = new String[] { PagodaTester.onto_dir + "bio2rdf/chembl/cco-noDPR.ttl" };
      //			args = new String[] { PagodaTester.onto_dir +
      // "bio2rdf/reactome/biopax-level3-processed.owl" };
      //			args = new String[] { PagodaTester.onto_dir + "bio2rdf/uniprot/core-processed-noDis.owl"
      // };
    }

    //		OWLOntology ontology = OWLHelper.getMergedOntology(args[0], null);
    //		OWLHelper.correctDataTypeRangeAxioms(ontology);
    OWLOntology ontology = OWLHelper.loadOntology(args[0]);

    OWLOntologyManager manager = ontology.getOWLOntologyManager();
    OWLDataFactory factory = manager.getOWLDataFactory();
    //		manager.saveOntology(ontology, new FileOutputStream(args[0].replace(".owl",
    // "_owlapi.owl")));

    if (outputFile != null) Utility.redirectCurrentOut(outputFile);

    int queryID = 0;
    for (OWLClass cls : ontology.getClassesInSignature(true)) {
      if (cls.equals(factory.getOWLThing()) || cls.equals(factory.getOWLNothing())) continue;
      if (!cls.toStringID().contains("Query")) continue;
      System.out.println("^[Query" + ++queryID + "]");
      System.out.println(template.replace("@CLASS", cls.toStringID()));
      System.out.println();
    }

    for (OWLOntology onto : ontology.getImportsClosure())
      for (OWLObjectProperty prop : onto.getObjectPropertiesInSignature()) {
        //				if (!prop.toStringID().contains("Query")) continue;
        System.out.println("^[Query" + ++queryID + "]");
        System.out.println("SELECT ?X ?Y");
        System.out.println("WHERE {");
        System.out.println("?X <" + prop.toStringID() + "> ?Y .");
        System.out.println("}");
        System.out.println();
      }

    String[] answerVars = new String[] {"?X", "?Y"};

    for (OWLOntology onto : ontology.getImportsClosure())
      for (OWLObjectProperty prop : onto.getObjectPropertiesInSignature()) {
        //				if (!prop.toStringID().contains("Query")) continue;
        for (int i = 0; i < answerVars.length; ++i) {
          System.out.println("^[Query" + ++queryID + "]");
          System.out.println("SELECT " + answerVars[i]);
          System.out.println("WHERE {");
          System.out.println("?X <" + prop.toStringID() + "> ?Y .");
          System.out.println("}");
          System.out.println();
        }
      }

    if (outputFile != null) Utility.closeCurrentOut();
  }
Example #12
0
  private void rearrangeAndCompareResults(
      OWLOntology ontology,
      OWLReasoner reasoner,
      Jedis resultStore,
      Jedis resultStore2,
      Jedis idReader)
      throws Exception {
    new ResultRearranger().initializeAndRearrange();
    Set<OWLClass> classes = ontology.getClassesInSignature();
    // rearranged results are in DB-1
    resultStore.select(1);
    double classCount = 0;
    int multiplier = 1;
    int missCount = 0;
    String bottomID = Util.getPackedID(Constants.BOTTOM_ID, EntityType.CLASS);
    System.out.println("Comparing Classes... " + classes.size());
    OWLClass owlThing = ontology.getOWLOntologyManager().getOWLDataFactory().getOWLThing();
    for (OWLClass cl : classes) {
      String classID = conceptToID(cl.toString(), idReader);
      // REL/Pellet doesn't consider individuals i.e. {a} \sqsubseteq \bottom
      // so skipping checking bottom
      if (classID.equals(bottomID)) continue;

      classCount++;
      Set<OWLClass> reasonerSuperClasses = reasoner.getSuperClasses(cl, false).getFlattened();
      // add cl itself to S(X) computed by reasoner. That is missing
      // in its result.
      reasonerSuperClasses.add(cl);
      reasonerSuperClasses.add(owlThing);
      // adding equivalent classes -- they are not considered if asked for superclasses
      Iterator<OWLClass> iterator = reasoner.getEquivalentClasses(cl).iterator();
      while (iterator.hasNext()) reasonerSuperClasses.add(iterator.next());
      Set<String> superClasses = resultStore.smembers(classID);
      if (superClasses.size() == reasonerSuperClasses.size()) {
        compareAndPrintEqualSizedClasses(cl, reasonerSuperClasses, superClasses, idReader);
      } else {
        System.out.println(
            "\n"
                + cl.toString()
                + " -- "
                + superClasses.size()
                + ", "
                + reasonerSuperClasses.size());
        for (OWLClass scl : reasonerSuperClasses) {
          String sclID = conceptToID(scl.toString(), idReader);
          if (!superClasses.contains(sclID)) {
            System.out.print(cl.toString() + " -ne- " + scl.toString());
            System.out.print("  ,  ");
          }
          superClasses.remove(sclID);
        }
        for (String s : superClasses)
          System.out.println("\t -- " + Util.idToConcept(s, idReader) + "(" + s + ")");
        System.out.println();
        missCount++;
      }
    }
    System.out.println("No of classes not equal: " + missCount);

    Set<OWLNamedIndividual> individuals = ontology.getIndividualsInSignature();
    System.out.println("Rearranging individuals...");
    System.out.println("Individuals: " + individuals.size());
    System.out.println("Not checking for individuals...");
    /*
    		rearrangeIndividuals(individuals, resultStore, resultStore2, idReader);
    		int cnt = 0;
    		for(OWLClass cl : classes) {
    			Set<OWLNamedIndividual> instances =
    				reasoner.getInstances(cl, false).getFlattened();
    			Set<String> computedInstances = resultStore2.smembers(
    					conceptToID(cl.toString(), idReader));
    			if(computedInstances.size() == instances.size()) {
    				compareAndPrintEqualSizedIndividuals(cl, instances, computedInstances, idReader);
    			}
    			else {
    				System.out.println(cl.toString() + " -- " +
    						computedInstances.size() + " , " + instances.size());
    				compareAndPrintUnEqualSizedIndividuals(cl, instances, computedInstances, idReader);
    				cnt++;
    			}
    		}
    		System.out.println("No of classes for which individuals didn't match: " + cnt);
    */
    resultStore.select(0);
  }
Example #13
0
  public Set<NamingIssue> detectNonMatchingChildIssues(OWLOntology ontology, boolean directChild) {
    long start = System.currentTimeMillis();

    // get SubClass - SuperClass pairs
    Set<NamingIssue> nonMatchingChildren = new HashSet<NamingIssue>();
    if (directChild) {
      Set<OWLSubClassOfAxiom> axioms = ontology.getAxioms(AxiomType.SUBCLASS_OF);
      for (OWLSubClassOfAxiom ax : axioms) {

        OWLClassExpression subClass = ax.getSubClass();
        OWLClassExpression superClass = ax.getSuperClass();

        if (!subClass.isAnonymous() && !superClass.isAnonymous()) {
          String subClassURI = subClass.asOWLClass().toStringID();
          String superClassURI = superClass.asOWLClass().toStringID();

          if (ignoreSingleTokenSubClasses && !singleToken(subClassURI)) {
            String subClassHead = getHeadNoun(subClassURI);
            String superClassHead = getHeadNoun(superClassURI);

            boolean matching =
                subClassHead.equals(superClassHead) || isHypernymOf(superClassHead, subClassHead);

            if (!matching) {
              String newClassURI = buildNewURI(subClassURI, superClassHead);
              nonMatchingChildren.add(
                  new NamingIssue(
                      subClassURI,
                      superClassURI,
                      new RenamingInstruction(subClassURI, newClassURI)));
            }
          }
        }
      }
    } else {
      OWLReasonerFactory reasonerFactory = PelletReasonerFactory.getInstance();
      OWLReasoner reasoner = reasonerFactory.createNonBufferingReasoner(ontology);

      Set<OWLClass> classes = ontology.getClassesInSignature();

      for (OWLClass cls : classes) {
        Set<OWLClass> superClasses = reasoner.getSuperClasses(cls, false).getFlattened();
        superClasses.remove(OWL_THING);
        for (OWLClass superClass : superClasses) {
          String subClassURI = cls.asOWLClass().toStringID();
          String superClassURI = superClass.asOWLClass().toStringID();

          if (ignoreSingleTokenSubClasses && !singleToken(subClassURI)) {
            String subClassHead = getHeadNoun(subClassURI);
            String superClassHead = getHeadNoun(superClassURI);

            boolean matching =
                subClassHead.equals(superClassHead) || isHypernymOf(superClassHead, subClassHead);

            if (!matching) {
              String newClassURI = buildNewURI(subClassURI, superClassHead);
              nonMatchingChildren.add(
                  new NamingIssue(
                      subClassURI,
                      superClassURI,
                      new RenamingInstruction(subClassURI, newClassURI)));
            }
          }
        }
      }
    }

    long end = System.currentTimeMillis();
    logger.info("Operation took " + (end - start) + "ms");

    return nonMatchingChildren;
  }