Beispiel #1
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#getDomain(java.net.URI)
   */
  public URI getDomain(URI relationshipOrProperty) throws TreatyException {

    OntModel model;
    model = getOntology();

    ObjectProperty property;
    property = model.getObjectProperty(relationshipOrProperty.toString());

    if (property != null) {

      try {
        return new URI(property.getDomain().getURI());
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // and catch.
    }
    // no else.

    DatatypeProperty dataProperty = model.getDatatypeProperty(relationshipOrProperty.toString());

    if (dataProperty != null) {

      try {
        return new URI(dataProperty.getDomain().getURI());
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // end catch.
    }
    // no else.

    return null;
  }
Beispiel #2
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#checkRange(java.net.URI,
   * java.net.URI)
   */
  public boolean checkRange(URI relationshipOrProperty, URI range) throws TreatyException {

    boolean result;

    OntModel model;
    model = getOntology();

    ObjectProperty property;
    property = model.getObjectProperty(relationshipOrProperty.toString());

    if (property == null) {
      result = false;
    } else {
      result = range.toString().equals(property.getRange().getURI());
    }

    return result;
  }
Beispiel #3
0
 @Test
 public void universalTest() throws FileNotFoundException {
   model.read(
       this.getClass()
           .getClassLoader()
           .getResourceAsStream("test/data/misc/universal-property.owl"),
       null);
   final ObjectProperty universal =
       model.getObjectProperty(
           "http://www.inmindcomputing.com/example/universal.owl#universalProperty");
   final ObjectProperty abstracT =
       model.getObjectProperty(
           "http://www.inmindcomputing.com/example/universal.owl#abstractProperty");
   final ObjectProperty concrete =
       model.getObjectProperty(
           "http://www.inmindcomputing.com/example/universal.owl#concreteProperty");
   Assert.assertTrue(universal.getEquivalentProperty().equals(OWL2.topObjectProperty));
   Assert.assertTrue(universal.listSubProperties().toSet().contains(abstracT));
   Assert.assertTrue(universal.listSubProperties().toSet().contains(concrete));
 }
Beispiel #4
0
  private void convertToFunctionalOrInverseFunctionalProperty(
      HashMap<String, HashMap<String, HashMap<String, Integer>>> objectProperts,
      boolean isCompositionRelations) {
    Set<String> keysPropertys = objectProperts.keySet();
    for (String keyProperty : keysPropertys) {
      ObjectProperty objectProperty =
          this.jena.createObjectProperty(this.ontologyPrefix + keyProperty, false);

      boolean sideAFunctional = this.convertObjectPropertyToFunctional(keyProperty, objectProperts);

      if (sideAFunctional) objectProperty.convertToFunctionalProperty();

      if (isCompositionRelations) {
        String nameInverseProperty = this.mobi.getInversePropertyName(keyProperty);

        if (nameInverseProperty != null
            && this.convertObjectPropertyToFunctional(nameInverseProperty, objectProperts))
          objectProperty.convertToInverseFunctionalProperty();
      } else {
        if (sideAFunctional) objectProperty.convertToInverseFunctionalProperty();
      }
    }
  }
  @Override
  protected OntModel createOntology() {

    OntModel extendedTAGSchema = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);

    // initialize super schema
    setCreatedSchema(extendedTAGSchema);

    new AltEntryManager(getCreatedSchema())
        .importWithAltEntry(
            CommonOntologyVocabulary.TAG_EXTENDING_ONTOLOGY_URI,
            CommonOntologyVocabulary.TAG_BASE_URI,
            AltEntryManager.getCvOntURI());

    OntClass tagCls = extendedTAGSchema.createClass(CommonOntologyVocabulary.TAG_RSC_URI);

    ObjectProperty hasTagPrp =
        extendedTAGSchema.createObjectProperty(CommonOntologyVocabulary.HAS_TAG_PRP_URI);
    hasTagPrp.addRange(tagCls);

    extendedTAGSchema.createOntology(CommonOntologyVocabulary.TAG_EXTENDING_ONTOLOGY_URI);

    return extendedTAGSchema;
  }
  /**
   * Parse a dependency tree from generated objects TODO: There are NIF properties missing to
   * describe dependency relations from phrases to other phrases TODO: What exactly is the "root"
   * node? I will make this the sentence resource but that seems to be wrong. should there be an
   * artificial "root" phrase? what does it contain? what offsets does it have?
   *
   * @param sentenceObjects
   */
  private void parseDependencyTree(
      List<ConLLWord> sentenceObjects,
      OntModel inputModel,
      Individual sentence,
      Individual context) {
    // create the tree
    // TODO: defining new property here, should be changed to work ootb
    ObjectProperty phraseHead =
        inputModel.createObjectProperty(
            "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#phraseHead");
    phraseHead.addProperty(RDFS.comment, "The head of a Phrase.");
    phraseHead.addProperty(RDFS.domain, NIFOntClasses.Phrase.getUri());
    phraseHead.addProperty(RDFS.range, NIFOntClasses.Phrase.getUri());

    ObjectProperty depRelType =
        inputModel.createObjectProperty(
            "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#dependencyRelationType");
    depRelType.addProperty(
        RDFS.comment,
        "Dependency relation to the HEAD. The set of dependency relations depends on the particular language. Note that depending on the original treebank annotation, the dependency relation may be meaningful or simply 'ROOT'. ");
    depRelType.addProperty(RDFS.domain, NIFOntClasses.Phrase.getUri());

    ObjectProperty govTODep = NIFObjectProperties.dependency.getObjectProperty(inputModel);

    for (ConLLWord word : sentenceObjects) {
      int phraseHeadId = word.getPhraseHeadId();
      Individual wordResource = word.getResource();
      // every word is a phrase
      wordResource.addOntClass(NIFOntClasses.Phrase.getOntClass(inputModel));

      if (phraseHeadId == 0) {
        // root node, making the sentence the head
        wordResource.addProperty(depRelType, word.getPhraseType());

      } else {
        // ids start with 1, List<> indexes starts with 0
        ConLLWord phraseHeadObject = sentenceObjects.get(phraseHeadId - 1);
        phraseHeadObject.getResource().addProperty(govTODep, wordResource);

        wordResource.addProperty(phraseHead, phraseHeadObject.getResource());
        wordResource.addProperty(
            NIFDatatypeProperties.head.getDatatypeProperty(inputModel),
            String.valueOf(phraseHeadId));
        wordResource.addProperty(depRelType, word.getPhraseType());
      }
    }
  }
    public void run() {
      while (pelletListener.isDirty()) {
        // pipeOpen = false;
        try {
          pelletListener.setDirty(false);
          inferenceRounds++;
          log.info("Getting new inferences");
          long startTime = System.currentTimeMillis();
          LinkedList<ObjectPropertyStatementPattern> irpl =
              new LinkedList<ObjectPropertyStatementPattern>();

          if (inferenceReceivingPatternAllowSet != null) {
            irpl.addAll(inferenceReceivingPatternAllowSet);
          } else {
            irpl.add(ObjectPropertyStatementPatternFactory.getPattern(null, null, null));
          }

          if (reasonerConfiguration.getQueryForAllObjectProperties()) {
            pelletModel.enterCriticalSection(Lock.READ);
            try {
              ClosableIterator closeIt = pelletModel.listObjectProperties();
              try {
                for (Iterator objPropIt = closeIt; objPropIt.hasNext(); ) {
                  ObjectProperty objProp = (ObjectProperty) objPropIt.next();
                  if (!("http://www.w3.org/2002/07/owl#".equals(objProp.getNameSpace()))) {
                    irpl.add(ObjectPropertyStatementPatternFactory.getPattern(null, objProp, null));
                  }
                }
              } finally {
                closeIt.close();
              }
            } finally {
              pelletModel.leaveCriticalSection();
            }
            deletedObjectProperties.enterCriticalSection(Lock.WRITE);
            try {
              ClosableIterator sit = deletedObjectProperties.listSubjects();
              try {
                while (sit.hasNext()) {
                  Resource subj = (Resource) sit.next();
                  irpl.add(
                      ObjectPropertyStatementPatternFactory.getPattern(
                          null, ResourceFactory.createProperty(subj.getURI()), null));
                }
              } finally {
                sit.close();
              }
              deletedObjectProperties.removeAll();
            } finally {
              deletedObjectProperties.leaveCriticalSection();
            }
          }

          if (reasonerConfiguration.getQueryForAllDatatypeProperties()) {
            pelletModel.enterCriticalSection(Lock.READ);
            try {
              ClosableIterator closeIt = pelletModel.listDatatypeProperties();
              try {
                for (Iterator dataPropIt = closeIt; dataPropIt.hasNext(); ) {
                  DatatypeProperty dataProp = (DatatypeProperty) dataPropIt.next();
                  if (!("http://www.w3.org/2002/07/owl#".equals(dataProp.getNameSpace()))) {
                    // TODO: THIS WILL WORK, BUT NEED TO GENERALIZE THE PATTERN CLASSES
                    irpl.add(
                        ObjectPropertyStatementPatternFactory.getPattern(null, dataProp, null));
                  }
                }
              } finally {
                closeIt.close();
              }
            } finally {
              pelletModel.leaveCriticalSection();
            }
            deletedDataProperties.enterCriticalSection(Lock.WRITE);
            try {
              ClosableIterator sit = deletedDataProperties.listSubjects();
              try {
                while (sit.hasNext()) {
                  Resource subj = (Resource) sit.next();
                  irpl.add(
                      ObjectPropertyStatementPatternFactory.getPattern(
                          null, ResourceFactory.createProperty(subj.getURI()), null));
                }
              } finally {
                sit.close();
              }
              deletedDataProperties.removeAll();
            } finally {
              deletedDataProperties.leaveCriticalSection();
            }
          }

          int addCount = 0;
          int retractCount = 0;

          // force new reasoner (disabled)
          if (false && !reasonerConfiguration.isIncrementalReasoningEnabled()) {
            Model baseModel = pelletModel.getBaseModel();
            pelletModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);
            pelletModel.getDocumentManager().setProcessImports(false);
            pelletModel.add(baseModel);
          }

          pelletModel.enterCriticalSection(Lock.WRITE);
          try {
            pelletModel.rebind();
            pelletModel.prepare();
          } finally {
            pelletModel.leaveCriticalSection();
          }

          for (Iterator<ObjectPropertyStatementPattern> patIt = irpl.iterator();
              patIt.hasNext(); ) {
            ObjectPropertyStatementPattern pat = patIt.next();

            if (log.isDebugEnabled()) {
              String subjStr = (pat.getSubject() != null) ? pat.getSubject().getURI() : "*";
              String predStr = (pat.getPredicate() != null) ? pat.getPredicate().getURI() : "*";
              String objStr = (pat.getObject() != null) ? pat.getObject().getURI() : "*";
              log.debug("Querying for " + subjStr + " : " + predStr + " : " + objStr);
            }

            Model tempModel = ModelFactory.createDefaultModel();

            pelletModel.enterCriticalSection(Lock.READ);
            try {

              ClosableIterator ci =
                  pelletModel.listStatements(pat.getSubject(), pat.getPredicate(), pat.getObject());
              try {
                for (ClosableIterator i = ci; i.hasNext(); ) {
                  Statement stmt = (Statement) i.next();

                  boolean reject = false;

                  // this next part is only needed if we're using Jena's OWL reasoner instead of
                  // actually using Pellet
                  try {
                    if ((((Resource) stmt.getObject()).equals(RDFS.Resource))) {
                      reject = true;
                    } else if ((((Resource) stmt.getSubject()).equals(OWL.Nothing))) {
                      reject = true;
                    } else if ((((Resource) stmt.getObject()).equals(OWL.Nothing))) {
                      reject = true;
                    }
                  } catch (Exception e) {
                  }

                  if (!reject) {
                    tempModel.add(stmt);

                    boolean fullModelContainsStatement = false;
                    fullModel.enterCriticalSection(Lock.READ);
                    try {
                      fullModelContainsStatement = fullModel.contains(stmt);
                    } finally {
                      fullModel.leaveCriticalSection();
                    }

                    if (!fullModelContainsStatement) {
                      // in theory we should be able to lock only the inference model, but I'm not
                      // sure yet if Jena propagates the locking upward
                      fullModel.enterCriticalSection(Lock.WRITE);
                      closePipe();
                      try {
                        inferenceModel.add(stmt);
                        addCount++;
                      } finally {
                        openPipe();
                        fullModel.leaveCriticalSection();
                      }
                    }
                  }
                }
              } finally {
                ci.close();
              }
            } finally {
              pelletModel.leaveCriticalSection();
            }

            // now we see what's in the inference model that isn't in the temp model and remove it

            try {
              Queue<Statement> localRemovalQueue = new LinkedList<Statement>();
              inferenceModel.enterCriticalSection(Lock.READ);
              try {
                ClosableIterator ci =
                    inferenceModel.listStatements(
                        pat.getSubject(), pat.getPredicate(), pat.getObject());
                try {
                  for (ClosableIterator i = ci; i.hasNext(); ) {
                    Statement stmt = (Statement) i.next();
                    if (!tempModel.contains(stmt)) {
                      localRemovalQueue.add(stmt);
                    }
                  }
                } finally {
                  ci.close();
                }
              } finally {
                inferenceModel.leaveCriticalSection();
              }
              for (Iterator<Statement> i = localRemovalQueue.iterator(); i.hasNext(); ) {
                fullModel.enterCriticalSection(Lock.WRITE);
                closePipe();
                try {
                  retractCount++;
                  inferenceModel.remove(i.next());
                } finally {
                  openPipe();
                  fullModel.leaveCriticalSection();
                }
              }

              localRemovalQueue.clear();
            } catch (Exception e) {
              log.error("Error getting inferences", e);
            }
            tempModel = null;
          }
          this.pelletListener.isConsistent = true;
          this.pelletListener.inErrorState = false;
          this.pelletListener.explanation = "";
          if (log.isDebugEnabled()) {
            log.info("Added " + addCount + " statements entailed by assertions");
            log.info("Retracted " + retractCount + " statements no longer entailed by assertions");
            log.info(
                "Done getting new inferences: "
                    + (System.currentTimeMillis() - startTime) / 1000
                    + " seconds");
          }
        } catch (InconsistentOntologyException ioe) {
          this.pelletListener.isConsistent = false;
          String explanation = ((PelletInfGraph) pelletModel.getGraph()).getKB().getExplanation();
          this.pelletListener.explanation = explanation;
          log.error(ioe);
          log.error(explanation);
        } catch (Exception e) {
          this.pelletListener.inErrorState = true;
          log.error("Exception during inference", e);
        } finally {
          pelletListener.endReasoning();
        }
      }
    }
  public Collection<PropertyInstance> getAllPropInstByVClasses(List<VClass> vclasses) {

    List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>();

    if (vclasses == null || vclasses.isEmpty()) {
      return propInsts;
    }

    Collections.sort(
        vclasses, new VClassHierarchyRanker(this.getWebappDaoFactory().getVClassDao()));

    OntModel ontModel = getOntModelSelector().getTBoxModel();

    try {

      ontModel.enterCriticalSection(Lock.READ);

      // map object property URI to an array of two resources:
      // the first is the "allValuesFrom" resource and the second is
      // "someValuesFrom"
      Map<String, Resource[]> applicableProperties = new HashMap<String, Resource[]>();

      try {
        for (VClass vclass : vclasses) {
          if (vclass.isAnonymous()) {
            continue;
          }
          String VClassURI = vclass.getURI();

          OntClass ontClass = getOntClass(ontModel, VClassURI);
          if (ontClass != null) {
            List<OntClass> relatedClasses = new ArrayList<OntClass>();
            relatedClasses.addAll(ontClass.listEquivalentClasses().toList());
            relatedClasses.addAll(ontClass.listSuperClasses().toList());
            for (OntClass relatedClass : relatedClasses) {
              // find properties in restrictions
              if (relatedClass.isRestriction()) {
                // TODO: check if restriction is something like
                // maxCardinality 0 or allValuesFrom owl:Nothing,
                // in which case the property is NOT applicable!
                Restriction rest = (Restriction) relatedClass.as(Restriction.class);
                OntProperty onProperty = rest.getOnProperty();
                if (onProperty != null && onProperty.canAs(ObjectProperty.class)) {
                  Resource[] ranges = new Resource[2];
                  if (rest.isAllValuesFromRestriction()) {
                    ranges[0] = (rest.asAllValuesFromRestriction()).getAllValuesFrom();
                  } else if (rest.isSomeValuesFromRestriction()) {
                    ranges[1] = (rest.asSomeValuesFromRestriction()).getSomeValuesFrom();
                  }
                  updatePropertyRangeMap(applicableProperties, onProperty.getURI(), ranges);
                }
              }
            }

            // find properties with class in domain
            ResIterator pit = ontModel.listSubjectsWithProperty(RDFS.domain, ontClass);
            while (pit.hasNext()) {
              Resource prop = pit.nextResource();
              if (prop.getNameSpace() != null
                  && !NONUSER_NAMESPACES.contains(prop.getNameSpace())) {
                StmtIterator rangeSit = prop.listProperties(RDFS.range);
                Resource rangeRes = null;
                while (rangeSit.hasNext()) {
                  Statement s = rangeSit.nextStatement();
                  if (s.getObject().isURIResource()) {
                    rangeRes = (Resource) s.getObject();
                  }
                }
                Resource[] ranges = new Resource[2];
                ranges[0] = rangeRes;
                updatePropertyRangeMap(applicableProperties, prop.getURI(), ranges);
              }
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Unable to get applicable properties "
                + "by examining property restrictions and domains",
            e);
      }

      // make the PropertyInstance objects
      for (String propertyURI : applicableProperties.keySet()) {
        ObjectProperty op = ontModel.getObjectProperty(propertyURI);
        if (op == null) {
          continue;
        }
        String domainURIStr = getURIStr(op.getDomain());
        Resource[] foundRanges = applicableProperties.get(propertyURI);
        Resource rangeRes =
            (foundRanges[0] != null)
                ? foundRanges[0]
                : (op.getRange() == null && foundRanges[1] != null)
                    ? foundRanges[1]
                    : op.getRange();
        PropertyInstance pi = new PropertyInstance();
        if (rangeRes != null) {
          String rangeClassURI;
          if (rangeRes.isAnon()) {
            rangeClassURI = PSEUDO_BNODE_NS + rangeRes.getId().toString();
          } else {
            rangeClassURI = (String) rangeRes.getURI();
          }
          pi.setRangeClassURI(rangeClassURI);
          try {
            pi.setRangeClassName(
                getWebappDaoFactory().getVClassDao().getVClassByURI(rangeClassURI).getName());
            // pi.setRangeClassName(getLabel(getOntModel().getOntResource(rangeClassURI)));
          } catch (NullPointerException e) {
            /* probably a union or intersection - need to handle this somehow */
          }
        } else {
          pi.setRangeClassURI(OWL.Thing.getURI()); // TODO see above
        }
        pi.setDomainClassURI(domainURIStr);
        try {
          pi.setDomainClassName(
              getWebappDaoFactory().getVClassDao().getVClassByURI(domainURIStr).getName());
          // pi.setDomainClassName(getLabel(getOntModel().getOntResource(op.getDomain().getURI())));
        } catch (NullPointerException e) {
          /* probably a union or intersection - need to handle this somehow */
        }
        pi.setSubjectSide(true);
        pi.setPropertyURI(op.getURI());
        pi.setPropertyName(getLabelOrId(op)); // TODO
        pi.setRangePublic(getLabelOrId(op));
        pi.setDomainPublic(getLabelOrId(op));
        propInsts.add(pi);
      }
    } finally {
      ontModel.leaveCriticalSection();
    }

    Collections.sort(propInsts, new PropInstSorter());
    return propInsts;
  }
Beispiel #9
0
  private void ImportRelationsComposition() throws Exception {
    List<ObjectProperty> properties = this.jena.listObjectProperties().toList();

    for (ObjectProperty property : properties) {

      OntClass domain = property.listDomain().next().asClass();
      if (domain.isUnionClass()) domain = domain.asUnionClass().listOperands().toList().get(0);

      OntClass range = property.listRange().next().asClass();
      if (range.isUnionClass()) range = range.asUnionClass().listOperands().toList().get(0);

      Relation r = null;

      if (property.isSymmetricProperty())
        r =
            this.mobi.createSymmetricRelation(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()));
      else if (property.getInverse() == null)
        r =
            this.mobi.createUnidirecionalCompositionRelationship(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()));
      else if (property.getInverse() != null)
        r =
            this.mobi.createBidirecionalCompositionRelationship(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()),
                this.getNameObjectProperty(
                    property.getInverse().getLocalName(),
                    range.getLocalName().length(),
                    domain.getLocalName().length()));

      Class mobiDomain = new Class(domain.getLocalName());
      // this.mobi.getClass(domain.getLocalName());
      Class mobiRange = new Class(range.getLocalName());
      // this.mobi.getClass(range.getLocalName());

      if (mobiDomain != null && mobiRange != null) {
        r.setClassA(mobiDomain);
        r.setClassB(mobiRange);

        List<? extends OntResource> individuals = domain.listInstances().toList();

        for (OntResource resourceIndividual : individuals) {
          Individual individualDomain = resourceIndividual.asIndividual();

          NodeIterator propertyValues =
              this.jena.getIndividual(individualDomain.getURI()).listPropertyValues(property);

          while (propertyValues.hasNext()) {
            RDFNode node = propertyValues.next();
            Individual individualValue = node.as(Individual.class);

            this.mobi.addConcept(mobiDomain);
            this.mobi.addConcept(mobiRange);

            Instance instanceDomain = new Instance(individualDomain.getLocalName());
            Instance instanceRange = new Instance(individualValue.getLocalName());

            try {
              this.mobi.isOneOf(instanceDomain, mobiDomain);
              this.mobi.isOneOf(instanceRange, mobiRange);
            } catch (ExceptionURI e) {
            }

            r.addInstanceRelation(instanceDomain, instanceRange);
          }
        }

        r.processCardinality();

        if (r.getInstanceRelationMapA().size() > 0) this.mobi.addConcept(r);
      }
    }
  }
Beispiel #10
0
  public void exportSymmetricRelations() throws ExceptionSymmetricRelation {

    HashMap<String, HashMap<String, HashMap<String, Integer>>> relationsPropertys =
        new HashMap<String, HashMap<String, HashMap<String, Integer>>>();
    HashMap<String, HashMap<String, HashMap<String, Class>>> listRestrictions =
        new HashMap<String, HashMap<String, HashMap<String, Class>>>();

    for (SymmetricRelation symmetricRelation : this.mobi.getAllSymmetricRelations().values()) {

      String nameJenaObjectProperty =
          this.mobi.getPropertyName(
              symmetricRelation.getName(),
              symmetricRelation.getClassA(),
              symmetricRelation.getClassB());

      for (CompositionRelation cr : this.mobi.getAllCompositionRelations().values()) {
        if ((this.mobi
                .getPropertyName(cr.getNameA(), cr.getClassA(), cr.getClassB())
                .equals(nameJenaObjectProperty))
            || (cr.getNameB() != null
                && this.mobi
                    .getPropertyName(cr.getNameB(), cr.getClassB(), cr.getClassA())
                    .equals(nameJenaObjectProperty)))
          throw new ExceptionSymmetricRelation(
              "Could not create OWL file. There is another composition relation with the name: "
                  + nameJenaObjectProperty
                  + " for this symmetric relation.");
      }

      OntClass classeA = this.createJenaClass(symmetricRelation.getClassA());
      OntClass classeB = this.createJenaClass(symmetricRelation.getClassB());

      if (!relationsPropertys.containsKey(nameJenaObjectProperty))
        relationsPropertys.put(
            nameJenaObjectProperty, new HashMap<String, HashMap<String, Integer>>());

      if (!((HashMap<String, HashMap<String, Integer>>)
              relationsPropertys.get(nameJenaObjectProperty))
          .containsKey(symmetricRelation.getClassA().getUri()))
        ((HashMap<String, HashMap<String, Integer>>) relationsPropertys.get(nameJenaObjectProperty))
            .put(symmetricRelation.getClassA().getUri(), new HashMap<String, Integer>());

      if (!((HashMap<String, HashMap<String, Integer>>)
              relationsPropertys.get(nameJenaObjectProperty))
          .containsKey(symmetricRelation.getClassB().getUri()))
        ((HashMap<String, HashMap<String, Integer>>) relationsPropertys.get(nameJenaObjectProperty))
            .put(symmetricRelation.getClassB().getUri(), new HashMap<String, Integer>());

      if (!listRestrictions.containsKey(nameJenaObjectProperty))
        listRestrictions.put(nameJenaObjectProperty, new HashMap<String, HashMap<String, Class>>());

      if (!listRestrictions
          .get(nameJenaObjectProperty)
          .containsKey(symmetricRelation.getClassA().getUri()))
        listRestrictions
            .get(nameJenaObjectProperty)
            .put(symmetricRelation.getClassA().getUri(), new HashMap<String, Class>());

      if (!listRestrictions
          .get(nameJenaObjectProperty)
          .get(symmetricRelation.getClassA().getUri())
          .containsKey(symmetricRelation.getClassB().getUri()))
        listRestrictions
            .get(nameJenaObjectProperty)
            .get(symmetricRelation.getClassA().getUri())
            .put(symmetricRelation.getClassB().getUri(), symmetricRelation.getClassB());

      if (!listRestrictions
          .get(nameJenaObjectProperty)
          .containsKey(symmetricRelation.getClassB().getUri()))
        listRestrictions
            .get(nameJenaObjectProperty)
            .put(symmetricRelation.getClassB().getUri(), new HashMap<String, Class>());

      if (!listRestrictions
          .get(nameJenaObjectProperty)
          .get(symmetricRelation.getClassB().getUri())
          .containsKey(symmetricRelation.getClassA().getUri()))
        listRestrictions
            .get(nameJenaObjectProperty)
            .get(symmetricRelation.getClassB().getUri())
            .put(symmetricRelation.getClassA().getUri(), symmetricRelation.getClassA());

      ObjectProperty objectProperty =
          this.jena.createObjectProperty(this.ontologyPrefix + nameJenaObjectProperty);
      SymmetricProperty p = objectProperty.convertToSymmetricProperty();

      p.setInverseOf(p);
      p.setDomain(this.getJenaDomainsObjectProperty(nameJenaObjectProperty, false));
      p.setRange(this.getJenaRangesObjectProperty(nameJenaObjectProperty, false));

      for (InstanceRelation instanceRelation :
          symmetricRelation.getInstanceRelationMapA().values()) {

        Individual individual =
            this.jena.createIndividual(
                this.ontologyPrefix + instanceRelation.getInstance().getUri(), classeA);

        for (Instance instance : instanceRelation.getAllInstances().values()) {
          Individual individualv1 =
              this.jena.createIndividual(this.ontologyPrefix + instance.getUri(), classeB);
          individualv1.addProperty(objectProperty, individual);

          individual.addProperty(objectProperty, individualv1);

          if (!((HashMap<String, HashMap<String, Integer>>)
                  relationsPropertys.get(nameJenaObjectProperty))
              .get(symmetricRelation.getClassA().getUri())
              .containsKey(instanceRelation.getInstance().getUri()))
            ((HashMap<String, HashMap<String, Integer>>)
                    relationsPropertys.get(nameJenaObjectProperty))
                .get(symmetricRelation.getClassA().getUri())
                .put(instanceRelation.getInstance().getUri(), 1);
          else {
            Integer count =
                ((HashMap<String, HashMap<String, Integer>>)
                        relationsPropertys.get(nameJenaObjectProperty))
                    .get(symmetricRelation.getClassA().getUri())
                    .get(instanceRelation.getInstance().getUri());
            ((HashMap<String, HashMap<String, Integer>>)
                    relationsPropertys.get(nameJenaObjectProperty))
                .get(symmetricRelation.getClassA().getUri())
                .put(instanceRelation.getInstance().getUri(), count + 1);
          }
        }
      }

      for (InstanceRelation instanceRelation :
          symmetricRelation.getInstanceRelationMapB().values()) {

        Individual individual =
            this.jena.createIndividual(
                this.ontologyPrefix + instanceRelation.getInstance().getUri(), classeB);

        for (Instance instance : instanceRelation.getAllInstances().values()) {
          Individual individualv1 =
              this.jena.createIndividual(this.ontologyPrefix + instance.getUri(), classeA);
          individual.addProperty(objectProperty, individualv1);

          individualv1.addProperty(objectProperty, individual);
        }
      }
    }

    Set<String> keysRestrictions = listRestrictions.keySet();

    for (String keyRestriction : keysRestrictions) {
      HashMap<String, HashMap<String, Class>> listRestrictions2 =
          listRestrictions.get(keyRestriction);
      Set<String> keysRestrictions2 = listRestrictions2.keySet();
      for (String keyRestriction2 : keysRestrictions2) {
        this.createJenaRestriction(
            this.jena.createObjectProperty(this.ontologyPrefix + keyRestriction),
            this.jena.createClass(this.ontologyPrefix + keyRestriction2),
            this.createUnionJenaClassFromMobiClass(listRestrictions2.get(keyRestriction2)),
            Mobi2OWL.RESTRICTION_ALLVALUES);
      }
    }

    this.convertToFunctionalOrInverseFunctionalProperty(relationsPropertys, false);
  }
Beispiel #11
0
  public void exportCompositionRelations()
      throws ExceptionInverseRelation, ExceptionSymmetricRelation {

    HashMap<String, HashMap<String, HashMap<String, Integer>>> relationsPropertys =
        new HashMap<String, HashMap<String, HashMap<String, Integer>>>();
    HashMap<String, HashMap<String, HashMap<String, Class>>> listRestrictions =
        new HashMap<String, HashMap<String, HashMap<String, Class>>>();

    for (CompositionRelation cr : this.mobi.getAllCompositionRelations().values()) {

      for (SymmetricRelation sr : this.mobi.getAllSymmetricRelations().values()) {
        if (this.mobi
            .getPropertyName(sr.getName(), sr.getClassA(), sr.getClassB())
            .equals(this.mobi.getPropertyName(cr.getNameA(), cr.getClassA(), cr.getClassB())))
          throw new ExceptionSymmetricRelation(
              "Unable to generate the OWL file, as it has a symmetrical relationship with the name: "
                  + this.mobi.getPropertyName(cr.getNameA(), cr.getClassA(), cr.getClassB())
                  + " for this relationship composition.");

        if (cr.getNameB() != null
            && this.mobi
                .getPropertyName(cr.getNameB(), cr.getClassB(), cr.getClassA())
                .equals(this.mobi.getPropertyName(sr.getName(), sr.getClassA(), sr.getClassB())))
          throw new ExceptionSymmetricRelation(
              "Unable to generate the OWL file, as it has a symmetrical relationship with the name:"
                  + this.mobi.getPropertyName(cr.getNameB(), cr.getClassB(), cr.getClassA())
                  + " for this relationship composition.");
      }

      OntClass classA = this.createJenaClass(cr.getClassA());
      OntClass classB = this.createJenaClass(cr.getClassB());

      ObjectProperty objectPropertyA = null, objectPropertyB = null;
      String nameJenaObjectPropertyA = null, nameJenaObjectPropertyB = null;

      if (cr.getNameA() != null) {
        nameJenaObjectPropertyA =
            this.mobi.getPropertyName(cr.getNameA(), cr.getClassA(), cr.getClassB());

        objectPropertyA =
            this.jena.createObjectProperty(this.ontologyPrefix + nameJenaObjectPropertyA, false);

        objectPropertyA.setDomain(this.getJenaDomainsObjectProperty(nameJenaObjectPropertyA, true));
        objectPropertyA.setRange(this.getJenaRangesObjectProperty(nameJenaObjectPropertyA, true));

        if (!relationsPropertys.containsKey(nameJenaObjectPropertyA))
          relationsPropertys.put(
              nameJenaObjectPropertyA, new HashMap<String, HashMap<String, Integer>>());

        if (!((HashMap<String, HashMap<String, Integer>>)
                relationsPropertys.get(nameJenaObjectPropertyA))
            .containsKey(cr.getClassA().getUri()))
          ((HashMap<String, HashMap<String, Integer>>)
                  relationsPropertys.get(nameJenaObjectPropertyA))
              .put(cr.getClassA().getUri(), new HashMap<String, Integer>());

        if (this.getMobiDomainsObjectProperty(nameJenaObjectPropertyA, true).size() > 1) {
          if (!listRestrictions.containsKey(nameJenaObjectPropertyA))
            listRestrictions.put(
                nameJenaObjectPropertyA, new HashMap<String, HashMap<String, Class>>());

          if (!listRestrictions.get(nameJenaObjectPropertyA).containsKey(cr.getClassA().getUri()))
            listRestrictions
                .get(nameJenaObjectPropertyA)
                .put(cr.getClassA().getUri(), new HashMap<String, Class>());

          if (!listRestrictions
              .get(nameJenaObjectPropertyA)
              .get(cr.getClassA().getUri())
              .containsKey(cr.getClassB().getUri()))
            listRestrictions
                .get(nameJenaObjectPropertyA)
                .get(cr.getClassA().getUri())
                .put(cr.getClassB().getUri(), cr.getClassB());
        }
      }

      if (cr.getNameB() != null) {
        nameJenaObjectPropertyB =
            this.mobi.getPropertyName(cr.getNameB(), cr.getClassB(), cr.getClassA());

        String nameInversePropertyA = this.mobi.getInversePropertyName(nameJenaObjectPropertyB);
        String nameInversePropertyB = this.mobi.getInversePropertyName(nameJenaObjectPropertyA);

        if (!nameInversePropertyA.equals(nameJenaObjectPropertyA))
          throw new ExceptionInverseRelation(
              "Unable to generate the OWL file, as the inverse of the"
                  + nameJenaObjectPropertyB
                  + " is the property"
                  + nameInversePropertyA
                  + ". Thus, the property"
                  + nameJenaObjectPropertyA
                  + " can not be attributed to the reverse of the latter.");

        if (!nameInversePropertyB.equals(nameJenaObjectPropertyB))
          throw new ExceptionInverseRelation(
              "Unable to generate the OWL file, as the inverse of the"
                  + nameJenaObjectPropertyA
                  + " is the property "
                  + nameInversePropertyB
                  + ". Thus, the property"
                  + nameJenaObjectPropertyB
                  + " can not be attributed to the reverse of the latter.");

        if (nameInversePropertyA.equals(nameInversePropertyB))
          throw new ExceptionInverseRelation(
              "Unable to generate the OWL file as a composition of two-way relationship with the names of the inverse and direct the same to be characterized as a symmetrical relationship.");

        objectPropertyB =
            this.jena.createObjectProperty(this.ontologyPrefix + nameJenaObjectPropertyB, false);

        objectPropertyB.setDomain(this.getJenaDomainsObjectProperty(nameJenaObjectPropertyB, true));
        objectPropertyB.setRange(this.getJenaRangesObjectProperty(nameJenaObjectPropertyB, true));

        if (!relationsPropertys.containsKey(nameJenaObjectPropertyB))
          relationsPropertys.put(
              nameJenaObjectPropertyB, new HashMap<String, HashMap<String, Integer>>());

        if (!((HashMap<String, HashMap<String, Integer>>)
                relationsPropertys.get(nameJenaObjectPropertyB))
            .containsKey(cr.getClassB().getUri()))
          ((HashMap<String, HashMap<String, Integer>>)
                  relationsPropertys.get(nameJenaObjectPropertyB))
              .put(cr.getClassB().getUri(), new HashMap<String, Integer>());

        if (this.getMobiDomainsObjectProperty(nameJenaObjectPropertyB, true).size() > 1) {
          if (!listRestrictions.containsKey(nameJenaObjectPropertyB))
            listRestrictions.put(
                nameJenaObjectPropertyB, new HashMap<String, HashMap<String, Class>>());

          if (!listRestrictions.get(nameJenaObjectPropertyB).containsKey(cr.getClassB().getUri()))
            listRestrictions
                .get(nameJenaObjectPropertyB)
                .put(cr.getClassB().getUri(), new HashMap<String, Class>());

          if (!listRestrictions
              .get(nameJenaObjectPropertyB)
              .get(cr.getClassB().getUri())
              .containsKey(cr.getClassA().getUri()))
            listRestrictions
                .get(nameJenaObjectPropertyB)
                .get(cr.getClassB().getUri())
                .put(cr.getClassA().getUri(), cr.getClassA());
        }
      }

      if ((cr.getNameA() != null) && (cr.getNameB() != null)) {
        objectPropertyA.setInverseOf(objectPropertyB);
        objectPropertyB.setInverseOf(objectPropertyA);
      }

      for (InstanceRelation instanceRelation : cr.getInstanceRelationMapA().values()) {

        Individual individualA =
            this.jena.createIndividual(
                this.ontologyPrefix + instanceRelation.getInstance().getUri(), classA);

        for (Instance instance : instanceRelation.getAllInstances().values()) {
          Individual individualB =
              jena.createIndividual(this.ontologyPrefix + instance.getUri(), classB);

          if (cr.getNameA() != null) {
            individualA.addProperty(objectPropertyA, individualB);

            if (!((HashMap<String, HashMap<String, Integer>>)
                    relationsPropertys.get(nameJenaObjectPropertyA))
                .get(cr.getClassA().getUri())
                .containsKey(instanceRelation.getInstance().getUri()))
              ((HashMap<String, HashMap<String, Integer>>)
                      relationsPropertys.get(nameJenaObjectPropertyA))
                  .get(cr.getClassA().getUri())
                  .put(instanceRelation.getInstance().getUri(), 1);
            else {
              Integer count =
                  ((HashMap<String, HashMap<String, Integer>>)
                          relationsPropertys.get(nameJenaObjectPropertyA))
                      .get(cr.getClassA().getUri())
                      .get(instanceRelation.getInstance().getUri());
              ((HashMap<String, HashMap<String, Integer>>)
                      relationsPropertys.get(nameJenaObjectPropertyA))
                  .get(cr.getClassA().getUri())
                  .put(instanceRelation.getInstance().getUri(), count + 1);
            }
          }
          if (cr.getNameB() != null) {
            individualB.addProperty(objectPropertyB, individualA);

            if (!((HashMap<String, HashMap<String, Integer>>)
                    relationsPropertys.get(nameJenaObjectPropertyB))
                .get(cr.getClassB().getUri())
                .containsKey(instance.getUri()))
              ((HashMap<String, HashMap<String, Integer>>)
                      relationsPropertys.get(nameJenaObjectPropertyB))
                  .get(cr.getClassB().getUri())
                  .put(instance.getUri(), 1);
            else {
              Integer count =
                  ((HashMap<String, HashMap<String, Integer>>)
                          relationsPropertys.get(nameJenaObjectPropertyB))
                      .get(cr.getClassB().getUri())
                      .get(instance.getUri());
              ((HashMap<String, HashMap<String, Integer>>)
                      relationsPropertys.get(nameJenaObjectPropertyB))
                  .get(cr.getClassB().getUri())
                  .put(instance.getUri(), count + 1);
            }
          }
        }
      }
    }

    Set<String> keysRestrictions1 = listRestrictions.keySet();

    for (String keyRestriction1 : keysRestrictions1) {
      HashMap<String, HashMap<String, Class>> listRestrictions2 =
          listRestrictions.get(keyRestriction1);
      Set<String> keysRestrictions2 = listRestrictions2.keySet();
      for (String keyRestriction2 : keysRestrictions2) {
        this.createJenaRestriction(
            this.jena.createObjectProperty(this.ontologyPrefix + keyRestriction1),
            this.jena.createClass(this.ontologyPrefix + keyRestriction2),
            this.createUnionJenaClassFromMobiClass(listRestrictions2.get(keyRestriction2)),
            RESTRICTION_ALLVALUES);
      }
    }

    this.convertToFunctionalOrInverseFunctionalProperty(relationsPropertys, true);
  }