示例#1
0
  public void exportInstances() {
    for (Instance instance : this.mobi.getAllInstances().values()) {
      for (Class mobiClass : this.mobi.getInstanceClasses(instance)) {
        OntClass ontClassA = this.createJenaClass(mobiClass);
        Class mobiBaseClass = instance.getBaseClass();

        Individual instanceJena = this.jena.getIndividual(this.ontologyPrefix + instance.getUri());

        if (mobiBaseClass != null) {
          OntClass ontBaseClass = this.createJenaClass(mobiBaseClass);

          if (!mobiBaseClass.getUri().equals(mobiClass.getUri()))
            ontBaseClass.addSubClass(ontClassA);

          if (instanceJena == null) {
            instanceJena =
                this.jena.createIndividual(this.ontologyPrefix + instance.getUri(), ontBaseClass);
            instanceJena.addOntClass(ontClassA);
          } else {
            instanceJena.addOntClass(ontBaseClass);
            instanceJena.addOntClass(ontClassA);
          }
        } else {
          if (instanceJena == null)
            instanceJena =
                this.jena.createIndividual(this.ontologyPrefix + instance.getUri(), ontClassA);
          else instanceJena.addOntClass(ontClassA);
        }
      }
    }
  }
  /**
   * Method that s if two elements of an ontology are siblings.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isSiblingMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {

    boolean gotSuperClass = false;
    OntClass ontClass = null;
    Iterator iter = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    ontClass = model.getOntClass(serviceParameter.toString());
    iter = ontClass.listSuperClasses(true);
    if (iter.hasNext()) {
      ontClass = (OntClass) iter.next();
      gotSuperClass = true;
    }
    if (gotSuperClass) {
      iter = ontClass.listSubClasses(true);
    }
    while (iter.hasNext()) {
      String next = iter.next().toString();
      if (requestParameter.toString().equals(next)) {
        return true;
      }
    }
    return false;
  }
 @Override
 public boolean accept(OntClass cls) {
   if (!cls.isAnon()) {
     return cls.getURI().startsWith(RDF.getURI());
   }
   return false;
 }
示例#4
0
 private OntClass createJenaClass(Class mobiClass) {
   OntClass jenaClasse = this.jena.createClass(this.ontologyPrefix + mobiClass.getUri());
   if (mobiClass.getComment() != null) {
     jenaClasse.setComment(mobiClass.getComment(), null);
   }
   return jenaClasse;
 }
示例#5
0
  private void addSubtypes(Frame frame) {

    Iterator<OntClass> sequence = frame.asOntClass().listSubClasses(true);
    while (sequence.hasNext()) {
      OntClass type = sequence.next();
      String subURI = type.getURI();
      if (subURI == null) continue;
      Frame subFrame = manager.getFrameByUri(subURI);
      if (subFrame == null) {
        subFrame = manager.getListTypeByListUri(subURI);
      }
      if (subFrame != null) {
        frame.getSubtypeList().add(subFrame);
      } else {

        Datatype datatype = manager.getDatatypeByUri(subURI);
        if (datatype != null) {
          frame.addSubdatatype(datatype);
          continue;
        }

        if (isStandard(subURI)) continue;
        logger.warn(
            "Ignoring supertype of " + type.getLocalName() + " because frame not found: " + subURI);
      }
    }
  }
  /**
   * Method that s if two elements of an ontology are subsumes.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isSubsumesMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {
    Iterator iter = null;
    OntClass ontClass = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    if (typeOfParameter == FunctionalMatcher.INPUT) {
      ontClass = model.getOntClass(serviceParameter.toString());
      iter = ontClass.listSubClasses();
      while (iter.hasNext()) {
        if (requestParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }
    } else if (typeOfParameter == FunctionalMatcher.OUTPUT) {
      ontClass = model.getOntClass(requestParameter.toString());
      iter = ontClass.listSubClasses();
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }
    }

    return false;
  }
示例#7
0
  public void exportInheritanceRelations() {

    for (InheritanceRelation ir : this.mobi.getAllInheritanceRelations().values()) {
      OntClass classeA = this.createJenaClass(ir.getClassA());
      OntClass classeB = this.createJenaClass(ir.getClassB());
      classeA.addSubClass(classeB);
    }
  }
示例#8
0
  public void exportEquivalenceRelations() {

    for (EquivalenceRelation ir : this.mobi.getAllEquivalenceRelations().values()) {
      OntClass classeA = this.createJenaClass(ir.getClassA());
      OntClass classeB = this.createJenaClass(ir.getClassB());
      classeA.addEquivalentClass(classeB);
      classeB.addEquivalentClass(classeA);
    }
  }
示例#9
0
 public static void addVocab(OntModel model) {
   OntClass ontCurrency = model.createClass(URI);
   DatatypeProperty AMNT = model.createDatatypeProperty(AMNT_URI);
   DatatypeProperty CURRENCY = model.createDatatypeProperty(CURRENCY_URI);
   AMNT.addDomain(ontCurrency);
   AMNT.addRange(XSD.xfloat);
   CURRENCY.addDomain(ontCurrency);
   CURRENCY.addRange(XSD.xstring);
   ontCurrency.addLabel(label, null);
 }
示例#10
0
 private List<OntClass> listRestrictions(OntClass type) {
   List<OntClass> list = new ArrayList<OntClass>();
   Iterator<OntClass> sequence = type.listSuperClasses(true);
   while (sequence.hasNext()) {
     OntClass supertype = sequence.next();
     if (supertype.hasRDFType(OWL.Restriction, false)) {
       list.add(supertype);
     }
   }
   return list;
 }
  public Iterator getInstancesOfClass(String className) {
    // get the instances of a class
    OntClass onto = model.getOntClass(className);

    if (onto == null) {
      System.out.println("ONT CLASS IS NULL");
      return (new ArrayList()).iterator();
    }

    Iterator instances = onto.listInstances();
    return instances;
  }
  public OntClass asOntClass(OntModel owlModel, Model pmlModel) {
    // int col = cmpOpCol(testNumber);

    Individual elem =
        owlModel.createIndividual(Ontology.EPA.NS + elementName, Ontology.Element(owlModel));
    OntClass elemRestrict =
        owlModel.createHasValueRestriction(null, Ontology.hasElement(owlModel), elem);
    // OntClass testRestrict =
    // owlModel.createClass(Ontology.EPA.NS+"EPA-"+elementName+"-test-"+testNumber);
    Literal test = owlModel.createTypedLiteral(testNumber);
    OntClass testRestrict =
        owlModel.createHasValueRestriction(null, Ontology.hasTestNumber(owlModel), test);
    Resource x =
        owlModel.createResource(
            Ontology.EPA.NS + "EPA-" + elementName + "-Threshold-" + testNumber);
    String op = null;
    switch (cmpType) {
      case 0:
        op = "minInclusive";
        break;
      case 1:
        op = "minExclusive";
        break;
      case 3:
        op = "maxExclusive";
        break;
      case 4:
        op = "maxInclusive";
        break;
      default:
        System.err.println("unknown cmp type");
    }
    x.addLiteral(owlModel.createProperty(XSD.getURI() + op), Double.parseDouble(cmpValue));
    RDFList withRestrict = owlModel.createList(new RDFNode[] {x});
    Resource y = owlModel.createResource(RDFS.Datatype);
    y.addProperty(OWL2.withRestrictions, withRestrict);
    y.addProperty(OWL2.onDatatype, XSD.xdouble);
    OntClass valueRestrict =
        owlModel.createSomeValuesFromRestriction(null, Ontology.hasValue(owlModel), y);
    RDFNode[] components = new RDFNode[4];
    components[0] = Ontology.FacilityMeasurement(owlModel);
    components[2] = valueRestrict;
    components[3] = elemRestrict;
    components[1] = testRestrict;
    RDFList intersect = owlModel.createList(components);
    OntClass self =
        owlModel.createIntersectionClass(
            Ontology.EPA.NS + "EPA-Excessive-" + elementName + "-Measurement-" + testNumber,
            intersect);
    self.addProperty(RDFS.subClassOf, Ontology.Violation(owlModel));

    return self;
  }
示例#13
0
 public static synchronized boolean isSingleValued(
     OntClass cls, OntProperty prop, String rngString) {
   if (prop.isFunctionalProperty()) {
     return true;
   }
   if (cls != null) {
     ExtendedIterator<OntClass> eitr = cls.listSuperClasses(false);
     while (eitr.hasNext()) {
       OntClass supercls = eitr.next();
       if (supercls.isRestriction()) {
         Restriction rstrct = supercls.asRestriction();
         if (rstrct.isMaxCardinalityRestriction()) {
           MaxCardinalityRestriction mxcr = rstrct.asMaxCardinalityRestriction();
           if (mxcr.getOnProperty().equals(prop) && mxcr.getMaxCardinality() == 1) {
             return true;
           }
         } else if (rstrct.isCardinalityRestriction()) {
           if (rstrct.isCardinalityRestriction()) {
             CardinalityRestriction cr = rstrct.asCardinalityRestriction();
             if (cr.getOnProperty().equals(prop) && cr.getCardinality() == 1) {
               return true;
             }
           }
         } else {
           if (rstrct.hasProperty(OWL2.maxQualifiedCardinality)) {
             if (rstrct.getOnProperty().equals(prop)
                 && rstrct.getProperty(OWL2.maxQualifiedCardinality).getInt() == 1) {
               // check class
               if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) {
                 return true;
               }
             }
           } else if (rstrct.hasProperty(OWL2.qualifiedCardinality)) {
             if (rstrct.getOnProperty().equals(prop)
                 && rstrct.getProperty(OWL2.qualifiedCardinality).getInt() == 1) {
               // check class
               if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) {
                 return true;
               }
             }
           }
           //						StmtIterator siter = rstrct.listProperties();
           //						while (siter.hasNext()) {
           //							System.out.println(siter.nextStatement().toString());
           //						}
         }
       }
     }
   }
   return false;
 }
示例#14
0
  private Model createModelFromDatabase() throws DataBaseNotAccessibleException {
    HashMap<String, Vector<String>> res = this.getMetaInfoFromDataBase();
    OntModel m = ModelFactory.createOntologyModel();

    String ns = "http://www.lirmm.fr/metaInfo#";
    m.setNsPrefix("metaInfos", ns);

    OntClass maDataBase = m.createClass(ns + "DATABASE");
    OntClass nameDataBase = m.createClass(ns + database.getDatabaseName());
    nameDataBase.addSuperClass(maDataBase);

    OntClass maSuperClasse = m.createClass(ns + "TABLE");

    for (String cle : res.keySet()) {
      OntClass c = m.createClass(ns + cle);
      c.addSuperClass(maSuperClasse);
      for (int i = 0; i < res.get(cle).size(); i++) {
        OntClass c2 = m.createClass(ns + res.get(cle).get(i));
        OntProperty prop =
            m.createOntProperty(ns + "COLONNE_" + c.getLocalName() + "_" + c2.getLocalName());
        prop.setRange(c2);
        prop.setDomain(c);
        c2.addSuperClass(maSuperClasse);
      }
    }
    return m;
  }
示例#15
0
 private void setRestCategory(Frame frame) {
   OntClass type = frame.asOntClass();
   Iterator<Resource> sequence = type.listRDFTypes(false);
   while (sequence.hasNext()) {
     Resource resource = sequence.next();
     if (BindVocabulary.Addressable.equals(resource)) {
       frame.setCategory(RestCategory.ADDRESSABLE);
     } else if (BindVocabulary.Enum.equals(resource)) {
       frame.setCategory(RestCategory.ENUMERABLE);
     } else if (BindVocabulary.EmbeddableClass.equals(resource)) {
       frame.setCategory(RestCategory.EMBEDDABLE);
     }
   }
 }
示例#16
0
  /** Prints out the inferred classes of the aligned ontology */
  public void printInfClasses(Model model) {
    ExtendedIterator<OntClass> classes = ((OntModel) model).listClasses();
    while (classes.hasNext()) {
      OntClass thisClass = (OntClass) classes.next();
      if (thisClass.getLocalName() != null) {
        System.out.println("Found class: " + thisClass.getLocalName());

        ExtendedIterator inst = thisClass.listInstances();
        while (inst.hasNext()) {
          Individual thisInstance = (Individual) inst.next();
          System.out.println("\tFound instance: " + thisInstance.getLocalName());
        }
      }
    }
  } // printInfClasses
  // replaces the label of the class
  public void replaceClassLabel(
      String uri,
      String newLabel,
      boolean activeRandomString,
      boolean activeTranslateString,
      boolean activeSynonym,
      int activeStringOperation) {
    OntClass c = modifiedModel.getOntClass(uri);

    if (c.getLabel("en") != null) {
      if (activeTranslateString) {
        c.setLabel(newLabel, "fr");
      } else c.setLabel(newLabel, "en");
    }
  }
  /**
   * Method that calculates if two elements of an ontology are exact.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isExactMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {
    Iterator iterClass = null;
    NodeIterator iter = null;
    OntClass ontClass = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    if (typeOfParameter == FunctionalMatcher.INPUT) {
      resource = model.getResource(ontology + requestParameter.getFragment());
      iter = model.listObjectsOfProperty(resource, OWL.equivalentClass);
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }

      ontClass = model.getOntClass(requestParameter.toString());
      iterClass = ontClass.listSubClasses(true);
      while (iterClass.hasNext()) {
        if (serviceParameter.toString().equals(iterClass.next().toString())) {
          return true;
        }
      }
    } else if (typeOfParameter == FunctionalMatcher.OUTPUT) {
      resource = model.getResource(ontology + requestParameter.getFragment());
      iter = model.listObjectsOfProperty(resource, OWL.equivalentClass);
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }

      ontClass = model.getOntClass(serviceParameter.toString());
      iterClass = ontClass.listSubClasses(true);
      while (iterClass.hasNext()) {
        if (requestParameter.toString().equals(iterClass.next().toString())) {
          return true;
        }
      }
    }
    if (requestParameter.toString().equals(serviceParameter.toString())) {
      return true;
    }
    return false;
  }
 /* (non-Javadoc)
  * @see org.sadiframework.client.Registry#findServicesByConnectedClass(com.hp.hpl.jena.rdf.model.Resource)
  */
 @Override
 public Collection<? extends Service> findServicesByConnectedClass(Resource clazz)
     throws SADIException {
   Set<String> classURIs = new HashSet<String>();
   if (clazz.isURIResource()) classURIs.add(clazz.getURI());
   if (clazz.canAs(OntClass.class)) {
     for (Iterator<? extends OntClass> i = clazz.as(OntClass.class).listSubClasses();
         i.hasNext(); ) {
       OntClass c = i.next();
       if (c.isURIResource()) classURIs.add(c.getURI());
     }
   }
   return findServicesByConnectedClass(classURIs);
   // TODO
   //		return findServices(RegistrySearchCriteria.findService().addConnectedClass(clazz));
 }
示例#20
0
  private List<OntClass> OntClassInheritanceChain(List<OntClass> _subClasses) {

    List<OntClass> removeSubClasses = new ArrayList<OntClass>();

    for (OntClass jenaClass : _subClasses) {
      List<OntClass> subClassCopy = jenaClass.listSubClasses().toList();
      for (OntClass subClass : subClassCopy) {
        if (_subClasses.contains(subClass)) {
          if (!removeSubClasses.contains(subClass)) removeSubClasses.add(subClass);
        }
      }
    }

    for (OntClass subClass : removeSubClasses)
      _subClasses.remove(_subClasses.lastIndexOf(subClass));

    return _subClasses;
  }
示例#21
0
  public Search(
      final java.awt.Frame parent,
      boolean modal,
      final OntClass ontClass,
      final OntProperty ontTarget,
      final JTextField txtField) {
    super(parent, modal);
    initComponents();
    this.parent = (SaveImage) parent;
    this.ontClass = ontClass;
    individuals = new ArrayList<>();
    all_individuals = new ArrayList<>();
    for (NodeIterator i =
            ontClass.listPropertyValues(
                Ontology.getOntModel().getProperty(Ontology.getNameSpace() + "lbl_netbeans"));
        i.hasNext(); ) {
      title_class.setText(i.next().toString());
    }
    this.txtField = txtField;
    model = new InstancesTable();
    tbl_individuals.setModel(model);
    for (ExtendedIterator<? extends OntResource> i = ontClass.listInstances(); i.hasNext(); ) {
      Individual inst = (Individual) i.next();
      if (inst.getNameSpace() != null) {
        individuals.add(inst);
        all_individuals.add(inst);
      }
    }

    tbl_individuals.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              JTable target = (JTable) e.getSource();
              int row = target.getSelectedRow();
              temp = ((SaveImage) parent).getContentFields().get(ontTarget.toString());
              temp.setIndividual(individuals.get(row));
              temp.getField().setText(individuals.get(row).getLocalName());
            }
          }
        });
  }
 protected Set<OWLClass> getAllClasses() {
   if (ks.isRemote()) {
     return new SPARQLTasks(((SparqlEndpointKS) ks).getEndpoint()).getAllClasses();
   } else {
     Set<OWLClass> classes = new TreeSet<OWLClass>();
     for (OntClass cls :
         ((LocalModelBasedSparqlEndpointKS) ks)
             .getModel()
             .listClasses()
             .filterDrop(new OWLFilter())
             .filterDrop(new RDFSFilter())
             .filterDrop(new RDFFilter())
             .toList()) {
       if (!cls.isAnon()) {
         classes.add(df.getOWLClass(IRI.create(cls.getURI())));
       }
     }
     return classes;
   }
 }
示例#23
0
  private Field createListField(Frame frame, OntProperty p, OntResource range) {

    Resource intersection = range.getPropertyResourceValue(OWL.intersectionOf);
    if (intersection == null) return null;

    if (intersection.canAs(RDFList.class)) {
      List<RDFNode> intersectionList = intersection.as(RDFList.class).asJavaList();
      for (RDFNode node : intersectionList) {
        if (node.canAs(OntClass.class)) {
          OntClass intersectionMember = node.as(OntClass.class);

          if (RDF.first.equals(intersectionMember.getPropertyResourceValue(OWL.onProperty))) {
            // The intersectionMember has an owl:onProperty property whose value is rdf:first

            Resource elementRdfType =
                intersectionMember.getPropertyResourceValue(OWL.allValuesFrom);

            if (elementRdfType != null) {

              String elementTypeURI = elementRdfType.getURI();
              if (elementTypeURI != null) {
                RdfType elementType = manager.getTypeByURI(elementTypeURI);
                if (elementType != null) {

                  ListType listType = manager.getListTypeByElementUri(elementTypeURI);
                  if (listType == null) {
                    listType = new ListType(manager, intersectionMember, elementType);
                    manager.add(listType);
                  }

                  return new Field(frame, p, listType);
                }
              }
            }
          }
        }
      }
    }

    return null;
  }
示例#24
0
  public static void main(String args[]) {
    String filename = "example6.rdf";

    // Create an empty model
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);

    // Use the FileManager to find the input file
    InputStream in = FileManager.get().open(filename);

    if (in == null) throw new IllegalArgumentException("File: " + filename + " not found");

    // Read the RDF/XML file
    model.read(in, null);
    // model.write(System.out,"Turtle");

    ExtendedIterator<? extends OntResource> iterator;
    // ** TASK 7.1: List all individuals of "Person" **
    OntClass person = model.getOntClass(ns + "Person");

    iterator = person.listInstances();
    System.out.println("Individuals");
    System.out.println("------------------------------------");
    while (iterator.hasNext()) {
      OntResource r = iterator.next();
      System.out.println(r.getURI());
    }
    System.out.println("------------------------------------");
    // ** TASK 7.2: List all subclasses of "Person" **
    iterator = person.listSubClasses();
    System.out.println("Sublcasses");
    System.out.println("------------------------------------");
    while (iterator.hasNext()) {
      OntResource r = iterator.next();
      System.out.println(r.getURI());
    }
    System.out.println("------------------------------------");
    // ** TASK 7.3: Make the necessary changes to get as well indirect instances and subclasses.
    // TIP: you need some inference... **

  }
示例#25
0
  public static void showShows() {
    OntModel model = PersistentOntology.getOntModel();
    model.write(System.out, "N-TRIPLES");
    OntClass show = model.getOntClass(PersistentOntology.NS + "TVShow");

    ExtendedIterator it = show.listInstances();

    while (it.hasNext()) {
      System.out.println("TVSHOW:");
      Individual ind = (Individual) it.next();
      Statement p = ind.getProperty(PersistentOntology.name);
      if (p != null)
        System.out.println(" - name: " + ind.getProperty(PersistentOntology.name).getString());

      p = ind.getProperty(PersistentOntology.status);
      if (p != null)
        System.out.println(" - status: " + ind.getProperty(PersistentOntology.status).getString());

      p = ind.getProperty(PersistentOntology.airDay);
      if (p != null) System.out.println(" - dates: " + p.getString());
      System.out.println();
    }
  }
示例#26
0
  /*
   * (non-Javadoc)
   * @see net.java.treaty.ContractVocabulary#getSupertypes(java.net.URI)
   */
  public Set<URI> getSuperTypes(URI type) throws TreatyException {

    Set<URI> result;
    result = new HashSet<URI>();

    OntModel model;
    model = getOntology();

    OntClass clazz;
    clazz = model.getOntClass(type.toString());

    for (Iterator<OntClass> iterator = clazz.listSuperClasses(false); iterator.hasNext(); ) {

      try {
        result.add(new URI(iterator.next().getURI()));
      } catch (URISyntaxException e) {
        throw new TreatyException(e);
      }
      // end catch.
    }
    // end for.

    return result;
  }
示例#27
0
  /**
   * Initialises the anchor, finding the node's compulsory and optional properties and their NL
   * representations and ordering it all in lists and maps, using the submenus.
   *
   * @param c OntClass corresponding to this anchor
   * @param query true if this is an anchor for a node in the QueryGraph
   * @throws BadAnchorException if the given SGNode does not need an anchor
   */
  public void init(OntClass c, boolean query) throws BadAnchorException {
    Map<String, Integer[]> map = reader.getCardinalities(c.getLocalName());
    List<OntProperty> list = reader.getDomainProperties(c.getLocalName());
    for (int i = 0; i < list.size(); i++) {
      OntProperty p = list.get(i);
      String name = p.getLocalName();
      int nr =
          node.getOutgoingEdges(name).size(); // number of times the node already has this property
      String inverse = reader.getInverse(name); // , n.getLabel(), null);
      if (inverse != null)
        nr +=
            node.getIncomingEdges(inverse)
                .size(); // plus the number of times the inverse has this node as range

      if (map.containsKey(name)) {
        int min =
            map.get(name)[0]; // if the minimum cardinality is not satisfied, add to 'compulsory'
        int max = map.get(name)[1];
        if (query) optional.add(p); // for the query, cardinality constraints do not matter
        else if ((min != 0)
            && (min > nr)) // if the minimum cardinality > 0, add the property to compulsory
        compulsory.add(p);
        else if ((max == 0)
            || (max > nr)) // if the maximum cardinality will not be violated, add to optional
        optional.add(p);
      } else optional.add(p); // no cardinality constraints, so add to optional
    }

    if (!compulsory.isEmpty()) // if there are compulsory properties, this is a red anchor
    redAnchor = true;
    else if (optional.isEmpty()) // compulsory and optional both empty - means this is not an anchor
    throw new BadAnchorException(
          "Node " + node.getLabel() + " is not an anchor anymore; all its relations are specified");

    sort(query);
  }
示例#28
0
  private List<OntResource> getEnumeratedIndividuals(OntClass type) {
    Resource equivalentClass = type.getPropertyResourceValue(OWL.equivalentClass);
    if (equivalentClass == null) {
      return null;
    }
    Resource oneOf = equivalentClass.getPropertyResourceValue(OWL.oneOf);
    if (oneOf == null) return null;

    List<RDFNode> nodeList = oneOf.as(RDFList.class).asJavaList();

    List<OntResource> result = new ArrayList<OntResource>();

    for (RDFNode node : nodeList) {
      result.add(node.as(OntResource.class));
    }

    return result;
  }
示例#29
0
  private Frame createFrame(OntClass type) {
    if (manager.isStandardDatatype(type.getNameSpace())) {
      manager.getDatatypeByUri(type.getURI());
      return null;
    }
    if (manager.isStandard(type.getNameSpace())) {
      return null;
    }
    String uri = type.getURI();
    if (uri == null) {
      throw new RuntimeException("URI of type is not defined");
    }
    Frame frame = manager.getFrameByUri(uri);
    if (frame != null) {
      return frame;
    }

    OntClass elemType = manager.getElementType(type);
    if (elemType != null) {
      String elemURI = elemType.getURI();
      ListType listType = manager.getListTypeByElementUri(elemURI);
      if (listType == null) {
        RdfType elemRdfType = manager.getTypeByURI(elemURI);
        if (elemRdfType == null) {
          elemRdfType = createFrame(elemType);
        }
        listType = new ListType(manager, type, elemRdfType);
        manager.add(listType);
      }
      return null;
    }

    List<OntResource> individuals = getEnumeratedIndividuals(type);

    if (individuals == null) {
      frame = new Frame(manager, type);
    } else {

      Enumeration enumFrame = new Enumeration(manager, type);
      frame = enumFrame;
      for (OntResource item : individuals) {
        NamedIndividual value = new NamedIndividual(item);
        enumFrame.add(value);
      }
    }

    manager.add(frame);
    return frame;
  }
  @Override
  public void runMetric() {

    // class annotation cover
    // List<Property> classAnnotationList = new ArrayList<Property>();
    classMetricMap = new HashMap<Property, CoverageTriple>();

    totalClassCount = ontology.getClassesList().size();

    for (Node classNode : ontology.getClassesList()) {
      OntClass currentClass = (OntClass) classNode.getResource().as(OntClass.class);
      StmtIterator i = currentClass.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class) && countedMap.get(p) == null) {
          // this is an annotation property
          if (classMetricMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
            classMetricMap.put(p, t);
          } else {
            CoverageTriple count = classMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    totalPropertyCount = ontology.getPropertiesList().size();
    // property annotation cover
    propertyMetricMap = new HashMap<Property, CoverageTriple>();

    for (Node propertyNode : ontology.getPropertiesList()) {
      OntProperty currentProperty = (OntProperty) propertyNode.getResource().as(OntProperty.class);
      StmtIterator i = currentProperty.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class)) {
          // this is an annotation property
          if (propertyMetricMap.get(p) == null && countedMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            propertyMetricMap.put(p, t);
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          } else {
            CoverageTriple count = propertyMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    // compute the percent coverage
    for (Entry<Property, CoverageTriple> entry : classMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalClassCount;
      if (entry.getValue().count > totalClassCount) {
        // test?
        System.out.println("--");
      }
    }

    for (Entry<Property, CoverageTriple> entry : propertyMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalPropertyCount;
      if (entry.getValue().count > totalPropertyCount) {
        // test?
        System.out.println("--");
      }
    }
  }