Java Examples for org.semanticweb.owlapi.model.OWLOntologyCreationException
The following java examples will help you to understand the usage of org.semanticweb.owlapi.model.OWLOntologyCreationException. These source code samples are taken from different open source projects.
Example 1
Project: Owl-master File: Examples.java View source code |
/**
* The following example uses entities and axioms that are used in the OWL Primer. The purpose
* of this example is to illustrate some of the methods of creating class expressions and
* various types of axioms. Typically, an ontology wouldn't be constructed programmatically in a
* long drawn out fashion like this, it would be constructe in an ontology editor such as
* Protege 4, or Swoop. The OWL API would then be used to examine the asserted structure of the
* ontology, and in conjunction with an OWL reasoner such as FaCT++ or Pellet used to query the
* inferred ontology.
*
* @throws Exception exception
*/
@Test
public void owlPrimer() throws Exception {
// The OWLOntologyManager is at the heart of the OWL API, we can create
// an instance of this using the OWLManager class, which will set up
// commonly used options (such as which parsers are registered etc.
// etc.)
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// We want to create an ontology that corresponds to the ontology used
// in the OWL Primer. Every ontology has a IRI that uniquely identifies
// the ontology. The IRI is essentially a name for the ontology. Note
// that the IRI doesn't necessarily point to a location on the web - in
// this example, we won't publish the ontology at the URL corresponding
// to the ontology IRI below.
IRI ontologyIRI = IRI.create("http://example.com/owlapi/", "families");
// Now that we have a IRI for out ontology, we can create the actual
// ontology. Note that the create ontology method throws an
// OWLOntologyCreationException if there was a problem creating the
// ontology.
OWLOntology ont = manager.createOntology(ontologyIRI);
// We can use the manager to get a reference to an OWLDataFactory. The
// data factory provides a point for creating OWL API objects such as
// classes, properties and individuals.
OWLDataFactory factory = manager.getOWLDataFactory();
// We first need to create some references to individuals. All of our
// individual must have IRIs. A common convention is to take the IRI of
// an ontology, append a # and then a local name. For example we can
// create the individual 'John', using the ontology IRI and appending
// #John. Note however, that there is no reuqirement that a IRI of a
// class, property or individual that is used in an ontology have a
// correspondance with the IRI of the ontology.
OWLIndividual john = factory.getOWLNamedIndividual(ontologyIRI + "#", "John");
OWLIndividual mary = factory.getOWLNamedIndividual(ontologyIRI + "#", "Mary");
OWLIndividual susan = factory.getOWLNamedIndividual(ontologyIRI + "#", "Susan");
OWLIndividual bill = factory.getOWLNamedIndividual(ontologyIRI + "#", "Bill");
// The ontologies that we created aren't contained in any ontology at
// the moment. Individuals (or classes or properties) can't directly be
// added to an ontology, they have to be used in axioms, and then the
// axioms are added to an ontology. We now want to add some facts to the
// ontology. These facts are otherwise known as property assertions. In
// our case, we want to say that John has a wife Mary. To do this we
// need to have a reference to the hasWife object property (object
// properties link an individual to an individual, and data properties
// link and individual to a constant - here, we need an object property
// because John and Mary are individuals).
OWLObjectProperty hasWife = factory.getOWLObjectProperty(ontologyIRI + "#", "hasWife");
// Now we need to create the assertion that John hasWife Mary. To do
// this we need an axiom, in this case an object property assertion
// axiom. This can be thought of as a "triple" that has a subject, john,
// a predicate, hasWife and an object Mary
OWLObjectPropertyAssertionAxiom axiom1 = factory.getOWLObjectPropertyAssertionAxiom(hasWife, john, mary);
// We now need to add this assertion to our ontology. To do this, we
// apply an ontology change to the ontology via the OWLOntologyManager.
// First we create the change object that will tell the manager that we
// want to add the axiom to the ontology
AddAxiom addAxiom1 = new AddAxiom(ont, axiom1);
// Now we apply the change using the manager.
manager.applyChange(addAxiom1);
// Now we want to add the other facts/assertions to the ontology John
// hasSon Bill Get a refernece to the hasSon property
OWLObjectProperty hasSon = factory.getOWLObjectProperty(ontologyIRI + "#", "hasSon");
// Create the assertion, John hasSon Bill
OWLAxiom axiom2 = factory.getOWLObjectPropertyAssertionAxiom(hasSon, john, bill);
// Apply the change
manager.applyChange(new AddAxiom(ont, axiom2));
// John hasDaughter Susan
OWLObjectProperty hasDaughter = factory.getOWLObjectProperty(ontologyIRI + "#", "hasDaughter");
OWLAxiom axiom3 = factory.getOWLObjectPropertyAssertionAxiom(hasDaughter, john, susan);
manager.applyChange(new AddAxiom(ont, axiom3));
// John hasAge 33 In this case, hasAge is a data property, which we need
// a reference to
OWLDataProperty hasAge = factory.getOWLDataProperty(ontologyIRI + "#", "hasAge");
// We create a data property assertion instead of an object property
// assertion
OWLAxiom axiom4 = factory.getOWLDataPropertyAssertionAxiom(hasAge, john, 33);
manager.applyChange(new AddAxiom(ont, axiom4));
// In the above code, 33 is an integer, so we can just pass 33 into the
// data factory method. Behind the scenes the OWL API will create a
// typed constant that it will use as the value of the data property
// assertion. We could have manually created the constant as follows:
OWLDatatype intDatatype = factory.getIntegerOWLDatatype();
OWLLiteral thirtyThree = factory.getOWLLiteral("33", intDatatype);
// We would then create the axiom as follows:
factory.getOWLDataPropertyAssertionAxiom(hasAge, john, thirtyThree);
// However, the convenice method is much shorter! We can now create the
// other facts/assertion for Mary. The OWL API uses a change object
// model, which means we can stack up changes (or sets of axioms) and
// apply the changes (or add the axioms) in one go. We will do this for
// Mary
Set<OWLAxiom> axioms = new HashSet<OWLAxiom>();
axioms.add(factory.getOWLObjectPropertyAssertionAxiom(hasSon, mary, bill));
axioms.add(factory.getOWLObjectPropertyAssertionAxiom(hasDaughter, mary, susan));
axioms.add(factory.getOWLDataPropertyAssertionAxiom(hasAge, mary, 31));
// Add facts/assertions for Bill and Susan
axioms.add(factory.getOWLDataPropertyAssertionAxiom(hasAge, bill, 13));
axioms.add(factory.getOWLDataPropertyAssertionAxiom(hasAge, mary, 8));
// Now add all the axioms in one go - there is a convenience method on
// OWLOntologyManager that will automatically generate the AddAxiom
// change objects for us. We need to specify the ontology that the
// axioms should be added to and the axioms to add.
ont.add(axioms);
// Now specify the genders of John, Mary, Bill and Susan. To do this we
// need the male and female individuals and the hasGender object
// property.
OWLIndividual male = factory.getOWLNamedIndividual(ontologyIRI + "#", "male");
OWLIndividual female = factory.getOWLNamedIndividual(ontologyIRI + "#", "female");
OWLObjectProperty hasGender = factory.getOWLObjectProperty(ontologyIRI + "#", "hasGender");
Set<OWLAxiom> genders = new HashSet<OWLAxiom>();
genders.add(factory.getOWLObjectPropertyAssertionAxiom(hasGender, john, male));
genders.add(factory.getOWLObjectPropertyAssertionAxiom(hasGender, mary, female));
genders.add(factory.getOWLObjectPropertyAssertionAxiom(hasGender, bill, male));
genders.add(factory.getOWLObjectPropertyAssertionAxiom(hasGender, susan, female));
// Add the facts about the genders
ont.add(genders);
// Domain and Range Axioms //At this point, we have an ontology
// containing facts about several individuals. We now want to specify
// more information about the various properties that we have used. We
// want to say that the domains and ranges of hasWife, hasSon and
// hasDaughter are the class Person. To do this we need various domain
// and range axioms, and we need a reference to the class Person First
// get a reference to the person class
OWLClass person = factory.getOWLClass(ontologyIRI + "#", "Person");
// Now we add the domain and range axioms that specify the domains and
// ranges of the various properties that we are interested in.
Set<OWLAxiom> domainsAndRanges = new HashSet<OWLAxiom>();
// Domain and then range of hasWife
domainsAndRanges.add(factory.getOWLObjectPropertyDomainAxiom(hasWife, person));
domainsAndRanges.add(factory.getOWLObjectPropertyRangeAxiom(hasWife, person));
// Domain and range of hasSon and also hasDaugher
domainsAndRanges.add(factory.getOWLObjectPropertyDomainAxiom(hasSon, person));
domainsAndRanges.add(factory.getOWLObjectPropertyRangeAxiom(hasSon, person));
domainsAndRanges.add(factory.getOWLObjectPropertyDomainAxiom(hasDaughter, person));
domainsAndRanges.add(factory.getOWLObjectPropertyRangeAxiom(hasDaughter, person));
// We also have the domain of the data property hasAge as Person, and
// the range as integer. We need the integer datatype. The XML Schema
// Datatype IRIs are used for data types. The OWL API provide a built in
// set via the XSDVocabulary enum.
domainsAndRanges.add(factory.getOWLDataPropertyDomainAxiom(hasAge, person));
OWLDatatype integerDatatype = factory.getIntegerOWLDatatype();
domainsAndRanges.add(factory.getOWLDataPropertyRangeAxiom(hasAge, integerDatatype));
// Now add all of our domain and range axioms
ont.add(domainsAndRanges);
// Class assertion axioms //We can also explicitly say than an
// individual is an instance of a given class. To do this we use a Class
// assertion axiom.
OWLClassAssertionAxiom classAssertionAx = factory.getOWLClassAssertionAxiom(person, john);
// Add the axiom directly using the addAxiom convenience method on
// OWLOntologyManager
manager.addAxiom(ont, classAssertionAx);
// Inverse property axioms //We can specify the inverse property of
// hasWife as hasHusband We first need a reference to the hasHusband
// property.
OWLObjectProperty hasHusband = factory.getOWLObjectProperty(ont.getOntologyID().getOntologyIRI().get() + "#", "hasHusband");
// The full IRI of the hasHusband property will be
// http://example.com/owlapi/families#hasHusband since the IRI of our
// ontology is http://example.com/owlapi/families Create the inverse
// object properties axiom and add it
manager.addAxiom(ont, factory.getOWLInverseObjectPropertiesAxiom(hasWife, hasHusband));
// Sub property axioms //OWL allows a property hierarchy to be
// specified. Here, hasSon and hasDaughter will be specified as
// hasChild.
OWLObjectProperty hasChild = factory.getOWLObjectProperty(ont.getOntologyID().getOntologyIRI().get() + "#", "hasChild");
OWLSubObjectPropertyOfAxiom hasSonSubHasChildAx = factory.getOWLSubObjectPropertyOfAxiom(hasSon, hasChild);
// Add the axiom
manager.addAxiom(ont, hasSonSubHasChildAx);
// And hasDaughter, which is also a sub property of hasChild
manager.addAxiom(ont, factory.getOWLSubObjectPropertyOfAxiom(hasDaughter, hasChild));
// Property characteristics //Next, we want to say that the hasAge
// property is Functional. This means that something can have at most
// one hasAge property. We can do this with a functional data property
// axiom First create the axiom
OWLFunctionalDataPropertyAxiom hasAgeFuncAx = factory.getOWLFunctionalDataPropertyAxiom(hasAge);
// Now add it to the ontology
manager.addAxiom(ont, hasAgeFuncAx);
// The hasWife property should be Functional, InverseFunctional,
// Irreflexive and Asymmetric. Note that the asymmetric property axiom
// used to be called antisymmetric - older versions of the OWL API may
// refer to antisymmetric property axioms
Set<OWLAxiom> hasWifeAxioms = new HashSet<OWLAxiom>();
hasWifeAxioms.add(factory.getOWLFunctionalObjectPropertyAxiom(hasWife));
hasWifeAxioms.add(factory.getOWLInverseFunctionalObjectPropertyAxiom(hasWife));
hasWifeAxioms.add(factory.getOWLIrreflexiveObjectPropertyAxiom(hasWife));
hasWifeAxioms.add(factory.getOWLAsymmetricObjectPropertyAxiom(hasWife));
// Add all of the axioms that specify the characteristics of hasWife
ont.add(hasWifeAxioms);
// SubClass axioms //Now we want to start specifying something about
// classes in our ontology. To begin with we will simply say something
// about the relationship between named classes Besides the Person class
// that we already have, we want to say something about the classes Man,
// Woman and Parent. To say something about these classes, as usual, we
// need references to them:
OWLClass man = factory.getOWLClass(ontologyIRI + "#", "Man");
OWLClass woman = factory.getOWLClass(ontologyIRI + "#", "Woman");
OWLClass parent = factory.getOWLClass(ontologyIRI + "#", "Parent");
// It is important to realise that simply getting references to a class
// via the data factory does not add them to an ontology - only axioms
// can be added to an ontology. Now say that Man, Woman and Parent are
// subclasses of Person
manager.addAxiom(ont, factory.getOWLSubClassOfAxiom(man, person));
manager.addAxiom(ont, factory.getOWLSubClassOfAxiom(woman, person));
manager.addAxiom(ont, factory.getOWLSubClassOfAxiom(parent, person));
// Restrictions //Now we want to say that Person has exactly 1 Age,
// exactly 1 Gender and, only has gender that is male or female. We will
// deal with these restrictions one by one and then combine them as a
// superclass (Necessary conditions) of Person. All anonymous class
// expressions extend OWLClassExpression. First, hasAge exactly 1
OWLDataExactCardinality hasAgeRestriction = factory.getOWLDataExactCardinality(1, hasAge);
// Now the hasGender exactly 1
OWLObjectExactCardinality hasGenderRestriction = factory.getOWLObjectExactCardinality(1, hasGender);
// And finally, the hasGender only {male female} To create this
// restriction, we need an OWLObjectOneOf class expression since male
// and female are individuals We can just list as many individuals as we
// need as the argument of the method.
OWLObjectOneOf maleOrFemale = factory.getOWLObjectOneOf(male, female);
// Now create the actual restriction
OWLObjectAllValuesFrom hasGenderOnlyMaleFemale = factory.getOWLObjectAllValuesFrom(hasGender, maleOrFemale);
// Finally, we bundle these restrictions up into an intersection, since
// we want person to be a subclass of the intersection of them
OWLObjectIntersectionOf intersection = factory.getOWLObjectIntersectionOf(hasAgeRestriction, hasGenderRestriction, hasGenderOnlyMaleFemale);
// And now we set this anonymous intersection class to be a superclass
// of Person using a subclass axiom
manager.addAxiom(ont, factory.getOWLSubClassOfAxiom(person, intersection));
// Restrictions and other anonymous classes can also be used anywhere a
// named class can be used. Let's set the range of hasSon to be Person
// and hasGender value male. This requires an anonymous class that is
// the intersection of Person, and also, hasGender value male. We need
// to create the hasGender value male restriction - this describes the
// class of things that have a hasGender relationship to the individual
// male.
OWLObjectHasValue hasGenderValueMaleRestriction = factory.getOWLObjectHasValue(hasGender, male);
// Now combine this with Person in an intersection
OWLClassExpression personAndHasGenderValueMale = factory.getOWLObjectIntersectionOf(person, hasGenderValueMaleRestriction);
// Now specify this anonymous class as the range of hasSon using an
// object property range axioms
manager.addAxiom(ont, factory.getOWLObjectPropertyRangeAxiom(hasSon, personAndHasGenderValueMale));
// We can do a similar thing for hasDaughter, by specifying that
// hasDaughter has a range of Person and hasGender value female. This
// time, we will make things a little more compact by not using so many
// variables
OWLClassExpression rangeOfHasDaughter = factory.getOWLObjectIntersectionOf(person, factory.getOWLObjectHasValue(hasGender, female));
manager.addAxiom(ont, factory.getOWLObjectPropertyRangeAxiom(hasDaughter, rangeOfHasDaughter));
// Data Ranges and Equivalent Classes axioms //In OWL 2, we can specify
// expressive data ranges. Here, we will specify the classes Teenage,
// Adult and Child by saying something about individuals ages. First we
// take the class Teenager, all of whose instance have an age greater or
// equal to 13 and less than 20. In Manchester Syntax this is written as
// Person and hasAge some int[>=13, <20] We create a data range by
// taking the integer datatype and applying facet restrictions to it.
// Note that we have statically imported the data range facet vocabulary
// OWLFacet
OWLFacetRestriction geq13 = factory.getOWLFacetRestriction(MIN_INCLUSIVE, factory.getOWLLiteral(13));
// We don't have to explicitly create the typed constant, there are
// convenience methods to do this
OWLFacetRestriction lt20 = factory.getOWLFacetRestriction(MAX_EXCLUSIVE, 20);
// Restrict the base type, integer (which is just an XML Schema
// Datatype) with the facet restrictions.
OWLDataRange dataRng = factory.getOWLDatatypeRestriction(integerDatatype, geq13, lt20);
// Now we have the data range of greater than equal to 13 and less than
// 20 we can use this in a restriction.
OWLDataSomeValuesFrom teenagerAgeRestriction = factory.getOWLDataSomeValuesFrom(hasAge, dataRng);
// Now make Teenager equivalent to Person and hasAge some int[>=13, <20]
// First create the class Person and hasAge some int[>=13, <20]
OWLClassExpression teenagePerson = factory.getOWLObjectIntersectionOf(person, teenagerAgeRestriction);
OWLClass teenager = factory.getOWLClass(ontologyIRI + "#", "Teenager");
OWLEquivalentClassesAxiom teenagerDefinition = factory.getOWLEquivalentClassesAxiom(teenager, teenagePerson);
manager.addAxiom(ont, teenagerDefinition);
// Do the same for Adult that has an age greater than 21
OWLDataRange geq21 = factory.getOWLDatatypeRestriction(integerDatatype, factory.getOWLFacetRestriction(MIN_INCLUSIVE, 21));
OWLClass adult = factory.getOWLClass(ontologyIRI + "#", "Adult");
OWLClassExpression adultAgeRestriction = factory.getOWLDataSomeValuesFrom(hasAge, geq21);
OWLClassExpression adultPerson = factory.getOWLObjectIntersectionOf(person, adultAgeRestriction);
OWLAxiom adultDefinition = factory.getOWLEquivalentClassesAxiom(adult, adultPerson);
manager.addAxiom(ont, adultDefinition);
// And finally Child
OWLDataRange notGeq21 = factory.getOWLDataComplementOf(geq21);
OWLClass child = factory.getOWLClass(ontologyIRI + "#", "Child");
OWLClassExpression childAgeRestriction = factory.getOWLDataSomeValuesFrom(hasAge, notGeq21);
OWLClassExpression childPerson = factory.getOWLObjectIntersectionOf(person, childAgeRestriction);
OWLAxiom childDefinition = factory.getOWLEquivalentClassesAxiom(child, childPerson);
manager.addAxiom(ont, childDefinition);
// Different individuals //In OWL, we can say that individuals are
// different from each other. To do this we use a different individuals
// axiom. Since John, Mary, Bill and Susan are all different
// individuals, we can express this using a different individuals axiom.
OWLDifferentIndividualsAxiom diffInds = factory.getOWLDifferentIndividualsAxiom(john, mary, bill, susan);
manager.addAxiom(ont, diffInds);
// Male and Female are also different
manager.addAxiom(ont, factory.getOWLDifferentIndividualsAxiom(male, female));
// Disjoint classes //Two say that two classes do not have any instances
// in common we use a disjoint classes axiom:
OWLDisjointClassesAxiom disjointClassesAxiom = factory.getOWLDisjointClassesAxiom(man, woman);
manager.addAxiom(ont, disjointClassesAxiom);
// Ontology Management //Having added axioms to out ontology we can now
// save it (in a variety of formats). RDF/XML is the default format
// System.out.println("RDF/XML: ");
manager.saveOntology(ont, new StringDocumentTarget());
// OWL/XML
// System.out.println("OWL/XML: ");
manager.saveOntology(ont, new OWLXMLDocumentFormat(), new StringDocumentTarget());
// Manchester Syntax
// System.out.println("Manchester syntax: ");
manager.saveOntology(ont, new ManchesterSyntaxDocumentFormat(), new StringDocumentTarget());
// Turtle
// System.out.println("Turtle: ");
manager.saveOntology(ont, new TurtleDocumentFormat(), new StringDocumentTarget());
}
Example 2
Project: DistributedRepresentations-master File: OpenCycOwl.java View source code |
/** * * @param conceptGUID * @return Set of types for a concept * @throws OWLOntologyCreationException */ public Set<String> getTypesForConceptFromOWL(String conceptGUID) throws OWLOntologyCreationException { Set<String> types = new HashSet<>(); OWLClass concept = dataFactory.getOWLClass(guidToIRI(conceptGUID)); NodeSet<OWLClass> subClasses = getReasoner().getSuperClasses(concept, true); subClasses.forEach( node -> { Set<OWLClass> ents = node.getEntities(); ents.forEach( ent -> { types.add(ent.getIRI().getShortForm()); }); }); return types; }
Example 3
Project: jfact-master File: WebOnt.java View source code |
@Test
@Changed(reason = "test doesn't make sense; This code does the test in a meaningful way")
public void testWebOnt_I5_26_009() throws OWLOntologyCreationException {
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
OWLOntology o = m.createOntology();
OWLDataFactory f = m.getOWLDataFactory();
OWLObjectProperty p = f.getOWLObjectProperty(IRI.create("urn:test:test#p"));
m.addAxiom(o, f.getOWLDeclarationAxiom(p));
OWLReasoner r = factory().createReasoner(o);
assertTrue(r.isConsistent());
OWLObjectMinCardinality c = f.getOWLObjectMinCardinality(1, p);
assertTrue(r.isEntailed(f.getOWLSubClassOfAxiom(c, c)));
}
Example 4
Project: drools-chance-master File: Xsd2OwlImpl.java View source code |
public OWLOntology transform(Schema schema, URL schemaURL, boolean verbose, boolean checkConsistency) {
System.out.println("Transforming....");
StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
OWLOntology ontology = null;
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLDataFactory factory = manager.getOWLDataFactory();
ontology = manager.createOntology(new OWLOntologyID(IRI.create(schema.getTargetNamespace()), IRI.create(schema.getTargetNamespace() + "/" + (schema.getVersion() != null ? schema.getVersion() : "1.0"))));
kSession.setGlobal("ontology", ontology);
kSession.setGlobal("manager", manager);
kSession.setGlobal("factory", factory);
kSession.setGlobal("validating", new Boolean(checkConsistency));
visit(schema, schemaURL, kSession, manager);
if (verbose) {
try {
manager.saveOntology(ontology, new ManchesterOWLSyntaxOntologyFormat(), System.out);
} catch (OWLOntologyStorageException e) {
e.printStackTrace();
}
}
if (checkConsistency) {
launchReasoner(ontology, fullAxiomGenerators);
}
} catch (Exception e) {
e.printStackTrace();
try {
return OWLManager.createOWLOntologyManager().createOntology();
} catch (OWLOntologyCreationException e1) {
e1.printStackTrace();
return null;
}
} finally {
kSession.dispose();
}
System.out.println("DONE!");
return ontology;
}
Example 5
Project: magetabcheck-master File: EfoLoader.java View source code |
public EfoDag load(final URL url) throws IOException, OWLOntologyCreationException {
if (url == null) {
log.error("Given EFO url is null; please use the config file to specify the proper one");
return null;
}
File cacheFile = getCacheFile(url);
if (!cacheFile.exists()) {
log.debug("The cache file doesn't exist; creating one [file={}]", cacheFile);
if (!cacheDir.exists() && !cacheDir.mkdirs()) {
throw new IOException("Can't create EFO cache directory: " + cacheDir.getAbsolutePath());
}
log.debug("Downloading EFO file [url={}]", url);
Resources.asByteSource(url).copyTo(Files.asByteSink(cacheFile));
log.debug("EFO file download successfully completed.");
} else {
log.debug("Loading EFO graph from cache [file={}]", cacheFile);
}
return load(cacheFile);
}
Example 6
Project: molgenis_apps-legacy-master File: OntologyBuilder.java View source code |
/*
* This method is used to load reference ontology and our own ontology.
*
* @param referenceOntology
*
* @param buildingOntology
*/
public void setOntology(String referenceOntology, String buildingOntology) throws OWLOntologyCreationException {
File file = new File(referenceOntology);
File saveFile = new File(buildingOntology);
// IRI efoIRI = IRI.create(referenceOntology);
// ontology = manager.loadOntology(efoIRI);
ontology = manager.loadOntologyFromOntologyDocument(file);
saveOntology = manager.loadOntologyFromOntologyDocument(saveFile);
// referenceOntologyURIConvert = labelMapURI(ontology);
// chaoClassURIConvert = labelMapURI(saveOntology);
reasonerFactory = new Reasoner.ReasonerFactory();
reasoner = reasonerFactory.createReasoner(saveOntology);
// DiseaseOntologyURIConvert = labelMapURI(ontology);
}
Example 7
Project: snorocket-master File: SnorocketOWLReasoner.java View source code |
// //////////////////////////////////////////////////////////////////////////
// Main method to use stand alone
// //////////////////////////////////////////////////////////////////////////
/**
* @param args
*/
public static void main(String[] args) {
String filename = args[0];
File f = new File(filename);
IRI iri = IRI.create(f.getAbsoluteFile());
try {
long start = System.currentTimeMillis();
System.out.println("Loading OWL ontology");
OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
OWLOntology ont = mgr.loadOntologyFromOntologyDocument(iri);
SnorocketOWLReasoner c = new SnorocketOWLReasoner(ont, null, false);
System.out.println("Took " + (System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
System.out.println("Classifying");
c.precomputeInferences(InferenceType.CLASS_HIERARCHY);
System.out.println("Took " + (System.currentTimeMillis() - start) + "ms");
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
}
Example 8
Project: Glimmer-master File: RDFIndexStatisticsBuilder.java View source code |
public RDFIndexStatisticsBuilder setOwlOntologyInputStream(InputStream owlOntologgyInputStream) throws IOException {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
try {
ontology = manager.loadOntologyFromOntologyDocument(owlOntologgyInputStream);
} catch (OWLOntologyCreationException e) {
throw new IllegalArgumentException("Ontology failed to load:" + e.getMessage());
}
owlOntologgyInputStream.close();
return this;
}
Example 9
Project: ontology-master File: OwlOWLCreator.java View source code |
// public static void main(String[] args) {
public static boolean doit(Ontology ontology) {
if (contentSerializer == null) {
contentSerializer = (MessageContentSerializer) Activator.mc.getContainer().fetchSharedObject(Activator.mc, new Object[] { MessageContentSerializer.class.getName() });
if (contentSerializer == null) {
System.out.println("ERROR: no serializer found for serializing the ontology");
return false;
}
}
String name = ontology.getInfo().getFilename();
if (// remove ".owl" at the end
name.endsWith(".owl"))
name = name.substring(0, name.length() - 4);
if (name == null)
name = Integer.toHexString(new Random(System.currentTimeMillis()).nextInt());
String strDir = "target" + File.separator + "ontologies";
File dir = new File(strDir);
if (!dir.exists())
dir.mkdirs();
name = strDir + File.separator + name;
String nameTtl = name + ".ttl";
String nameOwl = name + ".owl";
String serializedOntology = contentSerializer.serialize(ontology);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(nameTtl, false));
out.write(serializedOntology);
out.close();
} catch (IOException e) {
System.out.println("Exception " + e);
return false;
}
File outFile = new File(nameOwl);
File file = new File(nameTtl);
// try {
// System.out.println(" File OWL: " + outFile.getCanonicalPath());
// System.out.println(" File TTL: " + file.getCanonicalPath());
// } catch (IOException e2) {
// e2.printStackTrace();
// }
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
IRI documentIRI = IRI.create(file);
OWLOntology owlOntology;
try {
owlOntology = manager.loadOntologyFromOntologyDocument(documentIRI);
System.out.println(" Loaded ontology: " + owlOntology);
OWLOntologyFormat format = manager.getOntologyFormat(owlOntology);
RDFXMLOntologyFormat rdfxmlFormat = new RDFXMLOntologyFormat();
if (format.isPrefixOWLOntologyFormat()) {
rdfxmlFormat.copyPrefixesFrom(format.asPrefixOWLOntologyFormat());
}
manager.saveOntology(owlOntology, rdfxmlFormat, IRI.create(outFile));
System.out.println(" Saved ontology " + owlOntology + " in file " + nameOwl);
} catch (OWLOntologyCreationException e1) {
e1.printStackTrace();
return false;
} catch (OWLOntologyStorageException e) {
e.printStackTrace();
return false;
}
return true;
}
Example 10
Project: phenoscape-nlp-master File: EQPerformanceEvaluation.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
//String database = "biocreative2012";
//String candidate = "the cat sat on the mat";
// String reference = "the cat was sat on the mat";
//LOGGER.debug(meteor(candidate,reference,1,1));
//String resulttable = ApplicationUtilities.getProperty("table.output");
//long startTime = System.currentTimeMillis();
//String resulttable = "test_equivalent";
//String goldstandard = "goldstandard";
//EQPerformanceEvaluation pe = new EQPerformanceEvaluation(database, resulttable, goldstandard,"evaluationrecords", "test_is_equivalent");
//pe.evaluate();
//intercurator comparison
/*String database = "charaparsereval2013";
String[] resulttable = new String[]{"naive_38484", "naive_38484", "naive_40674",
"knowledge_40716", "knowledge_40716","knowledge_40717", "naive_38484", "naive_40674", "naive_40676"};
String[] goldstandard = new String[]{"naive_40674","naive_40676", "naive_40676",
"knowledge_40717", "knowledge_40718","knowledge_40718", "knowledge_40716", "knowledge_40717", "knowledge_40718"};
String[] setting = new String[]{"c38484_c40674", "c38484_c40676","c40674_c40676",
"c40716_c40717","c40716_c40718","c40717_c40718", "c38484_c40716", "c40674_c40717", "c40676_c40718" };*/
String database = ApplicationUtilities.getProperty("database.name");
String[] ids = new String[] { "naive_38484", "naive_40674", "naive_40676", "knowledge_40717", "knowledge_40718", "knowledge_40716" };
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.println("Evaluation with " + database + "," + ids[i] + "," + ids[j] + "," + "evaluationrecords" + "," + ids[i] + "_" + ids[j]);
EQPerformanceEvaluation pe = new EQPerformanceEvaluation(database, ids[i], ids[j], "evaluationrecords", ids[i] + "_" + ids[j] + "_sym");
pe.evaluate();
}
}
//EQPerformanceEvaluation pe = new EQPerformanceEvaluation("charaparsereval2013", "naive_38484", "knowledge_40717","evaluationrecords", "debug");
//pe.evaluate();
//long stopTime = System.currentTimeMillis();
//System.out.println("Elapsed time was " + (stopTime - startTime)/60000f + " minutes.");
//maxChunks("28135","13528635",0,3);
// String candidate ="UBERON:0002743 and (OBO_REL_part_of some (UBERON:0004741 and (OBO_REL_part_of some UBERON:0011683)))";
// String reference = "UBERON:0007831 and (OBO_REL_part_of some (UBERON:0011648 and (OBO_REL_part_of some UBERON:0002743)))";
// LinkedHashMap<String,Float> temp = new LinkedHashMap<String,Float>();
// Hashtable<String,String> equivalence = new Hashtable<String,String>();
//
// ELKReasoner elk = null;
// try {
//// elk = new ELKReasoner(new File(ApplicationUtilities.getProperty("ontology.dir")+System.getProperty("file.separator")+"ext.owl"));
// } catch (OWLOntologyCreationException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//start should be zero and end should be length of candidate string -1
//getMatchingSubstrings("2 8 1 3 5 2 8 7","1 3 5 1 3 8 5 6 3 5 2",0,7,temp,"exact",elk);
// candidate = format(candidate);
// reference = format(reference);
// getMatchingSubstrings(candidate,reference,0,candidate.split(" ").length-1,temp,"entity",elk,equivalence);
// LOGGER.debug("final score====="+replaceSubString(candidate,reference,temp,equivalence));
// candidate= candidate.replace(" ", "");
// reference = reference.replace(" ", "");
}
Example 11
Project: KBTaxonomy-master File: OpenCycConcept.java View source code |
/** * Factory method for creating a new OpenCycConcept * * @param kbTaxonomyCycConceptTerm * @param nlLabels * @param conceptUri * @return * @throws OWLOntologyCreationException */ public static OpenCycConcept create(String kbTaxonomyCycConceptTerm, Set<String> nlLabels, String conceptUri) throws OWLOntologyCreationException { if (haveConcept(kbTaxonomyCycConceptTerm)) { return (OpenCycConcept) getConcept(kbTaxonomyCycConceptTerm); } assert (!kbTaxonomyCycConceptTerm.startsWith("NonCycConcept")) : "Attempt to create OpenCyc Concept for NonCyc term " + kbTaxonomyCycConceptTerm; OpenCycConcept created = new OpenCycConcept(kbTaxonomyCycConceptTerm, nlLabels, conceptUri); addToLists(created); return created; }
Example 12
Project: opencirm-master File: LegacyEmulator.java View source code |
/**
* Augment a business object ontology with metadata axioms.
*
*/
public BOntology addMetaDataAxioms(BOntology bo) throws OWLOntologyCreationException {
OWLOntology ontology = bo.getOntology();
IRI verboseiri = IRI.create(ontology.getOntologyID().getOntologyIRI().toString() + "/verbose");
OWLOntologyManager manager = Refs.tempOntoManager.resolve();
OWLOntology result = manager.getOntology(verboseiri);
if (result != null)
manager.removeOntology(result);
result = manager.createOntology(IRI.create(ontology.getOntologyID().getOntologyIRI().toString() + "/verbose"), Collections.singleton(ontology));
OWLDataFactory factory = manager.getOWLDataFactory();
Set<OWLNamedIndividual> individuals = result.getIndividualsInSignature();
List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>();
for (OWLNamedIndividual ind : individuals) {
// If the individual lives in the CiRM namespace, we add all information about it.
if (OWL.ontology().containsEntityInSignature(ind, true)) {
ind = OWL.individual(ind.getIRI());
for (OWLOntology O : OWL.ontologies()) {
for (OWLIndividualAxiom axiom : O.getDataPropertyAssertionAxioms(ind)) changes.add(new AddAxiom(result, axiom));
for (OWLObjectPropertyAssertionAxiom axiom : O.getObjectPropertyAssertionAxioms(ind)) // but are they harmful? That logic takes away the generality of the method.
if (!axiom.getProperty().equals(objectProperty("legacy:hasLegacyInterface")) && !axiom.getProperty().equals(objectProperty("legacy:hasAllowableEvent")))
changes.add(new AddAxiom(result, axiom));
}
} else {
// add boid to businessObject in the BOntology
OWLDataProperty boid = factory.getOWLDataProperty(Model.legacy("boid"));
if (ind.getDataPropertyValues(boid, result).isEmpty()) {
// identifiers.get(ind);
Long id = Long.valueOf(bo.getObjectId());
// from the onto.
if (id != null)
changes.add(new AddAxiom(result, factory.getOWLDataPropertyAssertionAxiom(boid, ind, factory.getOWLLiteral(id.toString(), factory.getOWLDatatype(OWL2Datatype.XSD_INT.getIRI())))));
}
}
}
if (changes.size() > 0)
manager.applyChanges(changes);
BOntology newBO = new BOntology(result);
return newBO;
}
Example 13
Project: SnomedCTParser-master File: TestSNOMEDCTOWLParser.java View source code |
/** * Test method for * {@link se.liu.imt.mi.snomedct.parser.SNOMEDCTOWLParser#parse(org.semanticweb.owlapi.io.OWLOntologyDocumentSource, org.semanticweb.owlapi.model.OWLOntology)} * . Actually, this is not as much a test method as a method for generating * output * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException */ @Test public void testParseAndSaveOWLOntology() throws OWLOntologyCreationException, OWLOntologyStorageException { URL expressionsURL = getClass().getResource("/example_expression.sct"); ontology = manager.loadOntologyFromOntologyDocument(new File(expressionsURL.getFile())); // create a file for the new format File output = new File("output_as_Turtle.owl"); // save the ontology in Turtle format OWLDocumentFormat format = manager.getOntologyFormat(ontology); TurtleDocumentFormat turtleFormat = new TurtleDocumentFormat(); if (format.isPrefixOWLOntologyFormat()) { turtleFormat.copyPrefixesFrom(format.asPrefixOWLOntologyFormat()); } manager.saveOntology(ontology, turtleFormat, IRI.create(output.toURI())); // create another file for SNOMED CT Compositional Grammar format File output2 = new File("output_as_SNOMED_CT_CG.owl"); // save the ontology in SNOMED CT Compositional Grammar format SNOMEDCTDocumentFormat snomedCTFormat = new SNOMEDCTDocumentFormat(); manager.saveOntology(ontology, snomedCTFormat, IRI.create(output2.toURI())); }
Example 14
Project: software-master File: LexoCLI.java View source code |
public static void main(String[] args) throws IOException {
OptionParser parser = ParameterParser.getParser(args, "http://cli.nlp2rdf.org/lexo#");
try {
Monitor total = MonitorFactory.getTimeMonitor("total").start();
NIFParameters nifParameters = ParameterParser.CLIbefore(args, parser, "");
//customize
OntModel outputModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
OntModel inputModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RDFS_INF, ModelFactory.createDefaultModel());
inputModel.add(nifParameters.getInputModel());
inputModel.createOntology(nifParameters.getPrefix());
nifParameters.setInputModel(inputModel);
Monitor mon = MonitorFactory.getTimeMonitor(LexoCLI.class.getCanonicalName());
LExO lexo = new LExO();
int x = 0;
for (Individual context : inputModel.listIndividuals(NIFOntClasses.Context.getOntClass(inputModel)).toList()) {
lexo.processText(context, inputModel, outputModel, nifParameters);
x++;
}
String finalMessage = "Annotated " + x + " nif:Context(s) in " + mon.stop().getTotal() + " ms. (avg.:" + (mon.getAvg()) + ") producing " + outputModel.size() + " triples";
outputModel.add(RLOGSLF4JBinding.log(nifParameters.getLogPrefix(), finalMessage, RLOGIndividuals.DEBUG, lexo.getClass().getCanonicalName(), null, null));
if (nifParameters.getOutputFormat().equalsIgnoreCase("owldl")) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
outputModel.write(out);
try {
System.out.println(Render.render(new ByteArrayInputStream(out.toByteArray())));
} catch (OWLOntologyCreationException oce) {
oce.printStackTrace();
}
System.exit(0);
}
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(2);
System.err.println("needed total: " + nf.format(total.getLastValue()));
} catch (Exception e) {
ParameterParser.die(parser, e.getMessage());
}
}
Example 15
Project: stanbol-master File: ClerezzaOntologyProvider.java View source code |
/**
* In this implementation the identifier is the ImmutableGraph Name (e.g. ontonet::blabla)
*/
@SuppressWarnings("unchecked")
@Override
@Deprecated
public <O> O getStoredOntology(String identifier, Class<O> returnType, boolean forceMerge) {
if (identifier == null || identifier.isEmpty())
throw new IllegalArgumentException("Identifier cannot be null or empty.");
if (returnType == null) {
// Defaults to OWLOntology
returnType = (Class<O>) OWLOntology.class;
log.warn("No return type given for the ontology. Will return a {}", returnType.getCanonicalName());
}
boolean canDo = false;
for (Class<?> clazz : getSupportedReturnTypes()) if (clazz.isAssignableFrom(returnType)) {
canDo = true;
break;
}
if (!canDo)
throw new UnsupportedOperationException("Return type " + returnType.getCanonicalName() + " is not allowed in this implementation. Only allowed return types are " + supported);
Graph tc = store.getGraph(new IRI(identifier));
if (tc == null)
return null;
if (Graph.class.equals(returnType) || Graph.class.isAssignableFrom(returnType)) {
return returnType.cast(tc);
} else if (OWLOntology.class.isAssignableFrom(returnType)) {
try {
return (O) toOWLOntology(new IRI(identifier), forceMerge);
} catch (OWLOntologyCreationException e) {
log.error("Failed to return stored ontology " + identifier + " as type " + returnType.getCanonicalName(), e);
}
}
return null;
}
Example 16
Project: SVoNt-master File: PartitionEL.java View source code |
/** * Splits the given ontology into two partitions: The set of OWL EL * compliant axioms and the set of axioms which are not compliant with the * OWL EL profile. The EL compliant partition is stored in the left part of * resulting pair, and the EL non-compliant partition is stored in the right * part. * * @param sourceOnto * The source ontology to be partitioned. * @param compatibilityMode * Specifies the reasoner with which the resulting partition * should be compatible (e.g. Pellet has a different notion of EL * than other reasoners). * @return A pair containing two ontologies. The left part is the partition * of the source ontology with all EL-compliant axioms. The right * part is the partition of the source ontology with all * non-EL-compliant axioms. If the source ontology already conforms * to the OWL-EL profile, then the left part of the result contains * the source ontology, and the right part is null. * @throws OWLOntologyCreationException * If there is an error loading the source ontology. * @throws IllegalAccessException * @throws InstantiationException */ public static Pair<OWLOntology, OWLOntology> partition(OWLOntology sourceOnto, ReasonerCompatibilityMode compatibilityMode) throws OWLOntologyCreationException, InstantiationException, IllegalAccessException { OWLProfile elProfile = compatibilityMode.getProfileClass().newInstance(); OWLProfileReport report = elProfile.checkOntology(sourceOnto); if (report.isInProfile()) { return new ImmutablePair<OWLOntology, OWLOntology>(sourceOnto, null); } HashSet<OWLAxiom> nonELAxioms = new HashSet<OWLAxiom>(); Set<OWLProfileViolation> violations = report.getViolations(); for (OWLProfileViolation violation : violations) { nonELAxioms.add(violation.getAxiom()); } OWLOntologyID ontologyID = sourceOnto.getOntologyID(); IRI ontologyIRI = ontologyID.getOntologyIRI(); IRI targetELOntologyIRI = IRI.create(ontologyIRI.toString() + "/ELpart"); IRI targetNonELOntologyIRI = IRI.create(ontologyIRI.toString() + "/nonELpart"); OWLOntologyManager targetELOntoManager = OWLManager.createOWLOntologyManager(); targetELOntoManager.addIRIMapper(new NonMappingOntologyIRIMapper()); OWLOntology targetELOnto = targetELOntoManager.createOntology(new OWLOntologyID(targetELOntologyIRI)); OWLOntologyManager targetNonELOntoManager = OWLManager.createOWLOntologyManager(); targetNonELOntoManager.addIRIMapper(new NonMappingOntologyIRIMapper()); OWLOntology targetNonELOnto = targetNonELOntoManager.createOntology(new OWLOntologyID(targetNonELOntologyIRI)); Set<OWLAxiom> allAxioms = sourceOnto.getAxioms(); for (OWLAxiom axiom : allAxioms) { if (nonELAxioms.contains(axiom)) { targetNonELOntoManager.addAxiom(targetNonELOnto, axiom); System.out.println("- " + axiom); } else { targetELOntoManager.addAxiom(targetELOnto, axiom); System.out.println("+ " + axiom); } } return new ImmutablePair<OWLOntology, OWLOntology>(targetELOnto, targetNonELOnto); }
Example 17
Project: dog-master File: ModelLoader.java View source code |
/**
* Set the models to load and load the entry point
*
* @param models
* an {@link OntologyDescriptorSet} containing the references to
* the ontologies to load
* @param loadingMode
* the requested loading mode
*/
public void loadModel(Ontologies models, LoadingModes loadingMode) {
// get the requested loading mode
this.loadingMode = loadingMode;
// get the entry point, i.e., the ontology that imports all the
// other ontologies in the set
Ontology entryDesc = models.getEntryPoint();
// the file object to check that the local copies actually exist
File fCheck = null;
for (Ontology model : models.getOntology()) {
if (!model.getSrc().isEmpty()) {
// local copy
fCheck = new File(model.getSrc());
if (!fCheck.isAbsolute())
fCheck = new File(System.getProperty("configFolder", ".") + "/" + model.getSrc());
// check the file existence
if (fCheck.exists()) {
// use the local copy
this.manager.addIRIMapper(new SimpleIRIMapper(IRI.create(model.getHref()), IRI.create(fCheck)));
// debug
this.logger.log(LogService.LOG_DEBUG, "loaded: " + model.getHref() + "\n\tfrom local copy " + model.getSrc() + "\n\twith namespace " + model.getNamespace());
}
}
// store all the ontologies prefixes and namespaces
this.prefixes.setPrefix(model.getNamespace().toLowerCase() + ":", model.getHref() + "#");
}
// set the entry point ontology URI
String modelToLoad = entryDesc.getHref();
// load the ontology
try {
this.ontModel = this.manager.loadOntology(IRI.create(modelToLoad));
this.logger.log(LogService.LOG_INFO, "Loaded ontology: " + this.ontModel.getOntologyID().getOntologyIRI() + " [" + this.ontModel.getAxiomCount() + " axioms]\nfrom " + this.manager.getOntologyDocumentIRI(this.ontModel));
} catch (OWLOntologyCreationException e) {
this.logger.log(LogService.LOG_ERROR, "Impossible to load the ontology... interrupting...", e);
this.loadingMode = LoadingModes.UNDEFINED;
}
switch(this.loadingMode) {
case LOAD_REPLACE:
{
this.houseModelInstance.setModel(this.ontModel, this.prefixes);
break;
}
case LOAD_MERGE:
{
this.houseModelInstance.addModel(modelToLoad, this.ontModel, this.prefixes);
break;
}
default:
// do nothing, an error occurs
break;
}
}
Example 18
Project: ecco-master File: CategoricalDiff.java View source code |
/**
* Categorise effectual additions
* @param ea Effectual additions
* @param er Effectual removals
* @param ir Ineffectual removals
* @return Set of categorised effectual additions
*/
@SuppressWarnings("unchecked")
private Set<CategorisedEffectualAddition> categoriseEffectualAdditions(Set<OWLAxiom> ea, Set<OWLAxiom> er, Set<OWLAxiom> ir) {
if (verbose)
System.out.println("\n Categorising effectual additions... ");
Set<CategorisedEffectualAddition> effAdds = new HashSet<CategorisedEffectualAddition>();
if (!ea.isEmpty())
try {
effAdds = (Set<CategorisedEffectualAddition>) categoriseEffectualChanges(true, ea, ont1, er, ir);
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
else if (verbose)
System.out.println(" done (no effectual additions)");
return effAdds;
}
Example 19
Project: iconvis-master File: OntologyValidator.java View source code |
public boolean validateOntology(String ontologyPath) throws Exception { log.debug("[OntologyValidator::validateOntology] BEGIN"); boolean result = false; try { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); File file = new File(ontologyPath); OWLOntology localont = manager.loadOntologyFromOntologyDocument(file); ontologyUri = localont.getOntologyID().getOntologyIRI().toString(); log.info("[iconviz] Loaded ontology with URI: " + ontologyUri); IRI documentIRI = manager.getOntologyDocumentIRI(localont); log.info("[iconviz] Artefact: " + documentIRI); result = true; } catch (OWLOntologyCreationIOException e) { IOException ioException = e.getCause(); if (ioException instanceof FileNotFoundException) { log.error("[OntologyValidator::validateOntology] Could not load ontology. File not found: " + ioException.getMessage()); } else if (ioException instanceof UnknownHostException) { log.error("[OntologyValidator::validateOntology] Could not load ontology. Unknown host: " + ioException.getMessage()); } else { log.error("[OntologyValidator::validateOntology] Could not load ontology: " + ioException.getClass().getSimpleName() + " " + ioException.getMessage()); } throw e; } catch (UnparsableOntologyException e) { log.error("[OntologyValidator::validateOntology] Could not parse the ontology: " + e.getMessage()); Map<OWLParser, OWLParserException> exceptions = e.getExceptions(); for (OWLParser parser : exceptions.keySet()) { log.error("Tried to parse the ontology with the " + parser.getClass().getSimpleName() + " parser"); log.error("Failed because: " + exceptions.get(parser).getMessage()); } throw e; } catch (UnloadableImportException e) { log.error("[OntologyValidator::validateOntology] Could not load import: " + e.getImportsDeclaration()); OWLOntologyCreationException cause = e.getOntologyCreationException(); log.error("Reason: " + cause.getMessage()); throw e; } catch (OWLOntologyCreationException e) { log.error("[OntologyValidator::validateOntology] Could not load ontology: " + e.getMessage()); throw e; } catch (Exception e) { log.error("[OntologyValidator::validateOntology] Ontology validation unsuccessful. Check ontology and parameters in input.", e); throw e; } log.debug("[OntologyValidator::validateOntology] END"); return result; }
Example 20
Project: myequivalents-master File: MappingTest.java View source code |
@Test
public void testMockupModel() throws OWLOntologyStorageException, FileNotFoundException, OWLOntologyCreationException {
TestModel tm = new TestModel("", "http://test.rdf.net/");
MyEqRdfMapperFactory.init();
OWLOntologyManager owlMgr = OWLManager.createOWLOntologyManager();
OWLOntology kb = owlMgr.createOntology(IRI.create("http://test.rdf.net"));
MyEqRdfMapperFactory mapFact = new MyEqRdfMapperFactory(kb);
for (Bundle b : tm.mappings.getBundles()) mapFact.map(b);
// Save
PrefixOWLOntologyFormat fmt = new TurtleOntologyFormat();
for (Entry<String, String> nse : getNamespaces().entrySet()) fmt.setPrefix(nse.getKey(), nse.getValue());
String outPath = "target/mapping_test.ttl";
owlMgr.saveOntology(kb, fmt, new FileOutputStream(new File(outPath)));
// Test
SparqlBasedTester tester = new SparqlBasedTester(outPath, NamespaceUtils.asSPARQLProlog());
tester.testRDFOutput("service1 not found!", "ASK {\n" + " myeqres:service_" + tm.service1.getName() + " a myeq:Service;\n" + " dc-terms:identifier '" + tm.service1.getName() + "';\n" + " dc-terms:title '" + tm.service1.getTitle() + "';\n" + " dc-terms:description '" + tm.service1.getDescription() + "';\n" + " myeq:has-uri-pattern '" + tm.service1.getUriPattern() + "';\n" + " dc:type '" + tm.service1.getEntityType() + "';\n" + " myeq:has-repository myeqres:repo_" + tm.service1.getRepositoryName() + ";\n" + " myeq:has-service-collection myeqres:servcoll_" + tm.service1.getServiceCollectionName() + ".\n" + "}\n");
tester.testRDFOutput("service2 not found!", "ASK {\n" + " myeqres:service_" + tm.service2.getName() + " a myeq:Service.\n" + "}\n");
tester.testRDFOutput("repo1 not found!", "ASK {\n" + " myeqres:repo_" + tm.repo1.getName() + " a myeq:Repository;\n" + " dc-terms:identifier '" + tm.repo1.getName() + "';\n" + " dc-terms:title '" + tm.repo1.getTitle() + "';\n" + " dc-terms:description '" + tm.repo1.getDescription() + "'.\n" + "}\n");
tester.testRDFOutput("sc1 not found!", "ASK {\n" + " myeqres:servcoll_" + tm.sc1.getName() + " a myeq:ServiceCollection;\n" + " dc-terms:identifier '" + tm.sc1.getName() + "';\n" + " dc-terms:title '" + tm.sc1.getTitle() + "';\n" + " dc-terms:description '" + tm.sc1.getDescription() + "'.\n" + "}\n");
// Test the mappings
RdfUriGenerator<Entity> eUriGen = mapFact.getRdfUriGenerator(Entity.class);
for (Bundle bundle : tm.mappings.getBundles()) {
Entity[] es = bundle.getEntities().toArray(new Entity[0]);
for (int i = 0; i < es.length; i++) {
Entity ei = es[i];
String urii = eUriGen.getUri(ei);
tester.testRDFOutput("Entity <" + urii + "> not found!", "ASK {\n" + " <" + urii + "> a myeq:Entity;\n" + " dc-terms:identifier '" + ei.getAccession() + "';\n" + " myeq:has-service myeqres:service_" + ei.getServiceName() + ".\n" + "}\n");
for (int j = i + 1; j < es.length; j++) {
Entity ej = es[j];
String urij = eUriGen.getUri(ej);
tester.testRDFOutput("Mapping ( <" + urii + ">, <" + urij + "> not found!", "ASK {\n" + format(// " { %1$s owl:sameAs %2$s } UNION { %2$s owl:sameAs %1$s } UNION { ?x owl:sameAs %1$s, %2$s }\n",
"%s (owl:sameAs|^owl:sameAs){1,2} %s", '<' + urii + '>', '<' + urij + '>') + "}\n");
}
}
}
}
Example 21
Project: neo4j-sparql-extension-master File: Rules.java View source code |
/**
* Returns a list of rules extracted from the given OWL-2 ontology document.
*
* @param src an ontology document
* @return a list of rules
*/
public static List<Rule> fromOntology(OWLOntologyDocumentSource src) {
try {
// use OWL-API to get a OWLOntology document from source
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
manager.loadOntologyFromOntologyDocument(src);
Set<OWLOntology> ontologies = manager.getOntologies();
if (ontologies.isEmpty()) {
return Collections.EMPTY_LIST;
} else {
// use first ontology from given source
return fromOntology(ontologies.iterator().next());
}
} catch (OWLOntologyCreationException ex) {
throw new IllegalArgumentException("Loading ontology stream failed", ex);
}
}
Example 22
Project: semantika-master File: OntologyLoader.java View source code |
public IOntology loadOntologyFromDocument(InputStream inputStream) throws OntologyCreationException {
try {
OWLOntology owlOntology = mOwlManager.loadOntologyFromOntologyDocument(inputStream);
return createOwlOntology(owlOntology);
} catch (OWLOntologyCreationException e) {
throw new OntologyCreationException("Failed load ontology from input stream.", e);
}
}
Example 23
Project: AceWiki-master File: GfSentence.java View source code |
public void update() {
Set<Set<OWLAxiom>> setOfSetOfAxiom = null;
String uri = getOntology().getURI();
try {
setOfSetOfAxiom = GfOwlConverter.convert(mGfGrammar, uri, mGfWikiEntry);
} catch (OWLOntologyCreationException e1) {
}
if (setOfSetOfAxiom == null || setOfSetOfAxiom.isEmpty()) {
isOWLSWRL = isOWL = isReasonable = false;
owlAxioms = new HashSet<OWLAxiom>();
} else {
isOWLSWRL = isOWL = isReasonable = true;
owlAxioms = GfOwlConverter.disambiguate(setOfSetOfAxiom);
// be controlled by the profile instead
for (OWLAxiom ax : owlAxioms) {
if (ax instanceof SWRLRule) {
isOWL = isReasonable = false;
mLogger.info("Axiom is SWRL rule: {}", ax);
break;
}
}
}
// TODO: check also questions somehow, e.g. EL probably does not allow inverse properties in questions
if (isReasonable && this instanceof Declaration) {
AceWikiOWLReasoner2 reasoner = (AceWikiOWLReasoner2) getOntology().getReasoner().getWrappedReasoner();
isReasonable = GfOwlConverter.isReasonable(reasoner, owlAxioms);
}
if (!isReasonable && isIntegrated()) {
super.setIntegrated(false);
}
}
Example 24
Project: BioSolr-master File: AbstractOWLOntologyLoader.java View source code |
protected void doInitialization() throws OWLOntologyCreationException {
// init owl fields
this.manager = OWLManager.createOWLOntologyManager();
if (getOntologyResource() != null) {
getLog().info("Mapping ontology IRI from {} to {}", getOntologyIRI(), getOntologyResource());
this.manager.addIRIMapper(new SimpleIRIMapper(getOntologyIRI(), IRI.create(getOntologyResource())));
}
if (getOntologyImportMappings() != null) {
for (IRI from : getOntologyImportMappings().keySet()) {
IRI to = getOntologyImportMappings().get(from);
getLog().info("Mapping imported ontology IRI from " + from + " to " + to);
this.manager.addIRIMapper(new SimpleIRIMapper(from, to));
}
}
this.factory = manager.getOWLDataFactory();
// collect things we want to ignore form OWL vocab
owlVocabulary.add(factory.getOWLThing().getIRI());
owlVocabulary.add(factory.getOWLNothing().getIRI());
owlVocabulary.add(factory.getOWLTopObjectProperty().getIRI());
owlVocabulary.add(factory.getOWLBottomObjectProperty().getIRI());
// load the ontology
this.ontology = loadOntology();
}
Example 25
Project: profilechecker-master File: ProfileChecker.java View source code |
public int check(String[] args) throws OWLOntologyCreationException {
if (args.length == 0 || args[0].equals("-h") || args[0].equals("--help")) {
printHelp();
return 0;
}
// args must be non-empty by now, first argument must be
// the ontology to check
String iri = args[0];
// Optional second argument: OWL Profile to check against
final Optional<OWLProfile> profile;
if (args.length < 2) {
profile = Optional.of(DEFAULT_PROFILE);
} else if (args[1].equals("--all")) {
profile = Optional.empty();
} else {
// Look up profile name
String profileName = args[1];
profile = owlProfilebyName(profileName);
if (!profile.isPresent()) {
throw new IllegalArgumentException("Unknown profile: " + profileName);
}
}
final boolean anyFailed = checkOntology(iri, profile);
return anyFailed ? 1 : 0;
}
Example 26
Project: molgenis-master File: OntologyRepositoryCollectionTest.java View source code |
@BeforeMethod
public void beforeMethod() throws IOException, OWLOntologyCreationException, NoSuchMethodException {
// ontology repository collection is not spring managed, see FileRepositoryCollectionFactory
File file = ResourceUtils.getFile("small_test_data_NGtest.owl.zip");
OntologyRepositoryCollection ontologyRepoCollection = BeanUtils.instantiateClass(OntologyRepositoryCollection.class.getConstructor(File.class), file);
autowireCapableBeanFactory.autowireBeanProperties(ontologyRepoCollection, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
ontologyRepoCollection.init();
ontologyRepository = ontologyRepoCollection.getRepository(ONTOLOGY);
ontologyTermDynamicAnnotationRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_DYNAMIC_ANNOTATION);
ontologyTermNodePathRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_NODE_PATH);
ontologyTermSynonymRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM_SYNONYM);
ontologyTermRepository = ontologyRepoCollection.getRepository(ONTOLOGY_TERM);
}
Example 27
Project: Widoco-master File: WidocoUtils.java View source code |
/**
* Method that will download the ontology to document with Widoco.
* @param c Widoco configuration object.
*/
public static void loadModelToDocument(Configuration c) {
if (!c.isFromFile()) {
String newOntologyPath = c.getTmpFile().getAbsolutePath() + File.separator + "Ontology";
downloadOntology(c.getOntologyURI(), newOntologyPath);
c.setFromFile(true);
c.setOntologyPath(newOntologyPath);
}
//reding the model with Jena (deprecated)
// OntModel model = ModelFactory.createOntologyModel();//ModelFactory.createDefaultModel();
// readOntModel(model, c);
// c.getMainOntology().setMainModel(model);
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntologyLoaderConfiguration loadingConfig = new OWLOntologyLoaderConfiguration();
loadingConfig = loadingConfig.setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);
OWLOntology ontology;
try {
ontology = manager.loadOntologyFromOntologyDocument(new FileDocumentSource(new File(c.getOntologyPath())), loadingConfig);
c.getMainOntology().setMainOntology(ontology);
c.getMainOntology().setMainOntologyManager(manager);
System.out.println("Ontology loaded successfully");
} catch (OWLOntologyCreationException e) {
System.err.println("Could not open the ontology: " + e.getMessage());
}
}
Example 28
Project: Brain-master File: BrainPopulationTest.java View source code |
@Test
public void contructorFromOntologyTest() throws OWLOntologyCreationException, ClassExpressionException, NewOntologyException, ExistingEntityException, BadPrefixException {
OWLOntologyManager man = OWLManager.createOWLOntologyManager();
OWLOntology ontology = man.loadOntologyFromOntologyDocument(new File("src/test/resources/dev.owl"));
Brain brain = new Brain(ontology);
List<String> subClasses = brain.getSubClasses("G", false);
brain.sleep();
assertEquals(3, subClasses.size());
}
Example 29
Project: FuzzyOntologyMiner-master File: FuzzyOntologyMiner.java View source code |
/** * Metodo che, a partire dal vettore dei concetti e dalle tassonomie, crea l'ontologia * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws FileNotFoundException **/ public void saveOWL2FuzzyOntology(Taxonomy tax, String fileName) throws OWLOntologyCreationException, OWLOntologyStorageException, FileNotFoundException { int i, j; OWLClass s, c; //iteratore dei concetti ArrayList<String> concetti = tax.getConcepts(); //gestore dell'ontologia OWLOntologyManager m = OWLManager.createOWLOntologyManager(); //iri di riferimento per l'ontologia IRI ontIRI = IRI.create("http://www.semanticweb.org/ontologies/concetti"); //crea ontologia OWLOntology ont = m.createOntology(ontIRI); //gestore interfaccia per l'ontologia OWLDataFactory factory = m.getOWLDataFactory(); //Per ogni concetto crea una classe nell'ontologia Map<String, OWLClass> classi = new HashMap<String, OWLClass>(); for (String con : concetti) { IRI iriClass = IRI.create(ontIRI + "#" + con); OWLClass cl = factory.getOWLClass(iriClass); classi.put(con, cl); } for (i = 0; i < concetti.size(); i++) { for (j = 0; j < concetti.size(); j++) { String sub = concetti.get(j); String cls = concetti.get(i); double spec = tax.getSpecificity(sub, cls); if (spec > 0) { OWLAnnotation fuzzyAnnotation = createFuzzyAnnotation(factory, spec); Set<OWLAnnotation> annotazioni = new HashSet<OWLAnnotation>(); annotazioni.add(fuzzyAnnotation); s = classi.get(sub); c = classi.get(cls); OWLAxiom axiom = factory.getOWLSubClassOfAxiom(s, c, annotazioni); AddAxiom add = new AddAxiom(ont, axiom); m.applyChange(add); } } } //salvo l'ontologia su file m.saveOntology(ont, new FileOutputStream(fileName)); }
Example 30
Project: hermit-maven-master File: CommandLine.java View source code |
public void run(Reasoner hermit, StatusOutput status, PrintWriter output, boolean ignoreOntologyPrefixes) {
status.log(2, "Checking whether the loaded ontology entails the conclusion ontology");
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
try {
OWLOntology conclusions = m.loadOntology(conclusionIRI);
status.log(2, "Conclusion ontology loaded.");
EntailmentChecker checker = new EntailmentChecker(hermit, m.getOWLDataFactory());
boolean isEntailed = checker.entails(conclusions.getLogicalAxioms());
status.log(2, "Conclusion ontology is " + (isEntailed ? "" : "not ") + "entailed.");
output.println(isEntailed);
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
output.flush();
}
Example 31
Project: hermit-reasoner-master File: CommandLine.java View source code |
public void run(Reasoner hermit, StatusOutput status, PrintWriter output, boolean ignoreOntologyPrefixes) {
status.log(2, "Checking whether the loaded ontology entails the conclusion ontology");
OWLOntologyManager m = OWLManager.createOWLOntologyManager();
try {
OWLOntology conclusions = m.loadOntology(conclusionIRI);
status.log(2, "Conclusion ontology loaded.");
EntailmentChecker checker = new EntailmentChecker(hermit, m.getOWLDataFactory());
boolean isEntailed = checker.entails(conclusions.getLogicalAxioms());
status.log(2, "Conclusion ontology is " + (isEntailed ? "" : "not ") + "entailed.");
output.println(isEntailed);
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
output.flush();
}
Example 32
Project: podd-redesign-master File: PoddOWLManagerImpl.java View source code |
/** * Computes the inferences using the given reasoner, which has previously been setup based on an * ontology. * * @param nextReasoner * The reasoner to use to compute the inferences. * @param inferredOntologyID * The OWLOntologyID to use for the inferred ontology. This must be unique and not * previously used in either the repository or the OWLOntologyManager * @return An OWLOntology instance containing the axioms that were inferred from the original * ontology. * @throws ReasonerInterruptedException * @throws TimeOutException * @throws InconsistentOntologyException * @throws OWLOntologyCreationException * @throws OWLOntologyChangeException */ private OWLOntology computeInferences(final OWLReasoner nextReasoner, final OWLOntologyID concreteOntologyID, final OWLOntologyID inferredOntologyID) throws ReasonerInterruptedException, TimeOutException, OWLOntologyCreationException, OWLOntologyChangeException { final List<InferredAxiomGenerator<? extends OWLAxiom>> axiomGenerators = new ArrayList<InferredAxiomGenerator<? extends OWLAxiom>>(); axiomGenerators.add(new InferredClassAssertionAxiomGenerator()); axiomGenerators.add(new InferredDataPropertyCharacteristicAxiomGenerator()); axiomGenerators.add(new InferredEquivalentClassAxiomGenerator()); axiomGenerators.add(new InferredEquivalentDataPropertiesAxiomGenerator()); axiomGenerators.add(new InferredEquivalentObjectPropertyAxiomGenerator()); axiomGenerators.add(new InferredInverseObjectPropertiesAxiomGenerator()); axiomGenerators.add(new InferredObjectPropertyCharacteristicAxiomGenerator()); // NOTE: InferredPropertyAssertionGenerator significantly slows down // inference computation axiomGenerators.add(new org.semanticweb.owlapi.util.InferredPropertyAssertionGenerator()); axiomGenerators.add(new InferredSubClassAxiomGenerator()); axiomGenerators.add(new InferredSubDataPropertyAxiomGenerator()); axiomGenerators.add(new InferredSubObjectPropertyAxiomGenerator()); IRI importIRI = concreteOntologyID.getVersionIRI(); if (importIRI == null) { importIRI = concreteOntologyID.getOntologyIRI(); } final InferredOntologyGenerator iog = new InferredOntologyGenerator(nextReasoner, axiomGenerators); nextReasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); final OWLOntology nextInferredAxiomsOntology = nextReasoner.getRootOntology().getOWLOntologyManager().createOntology(inferredOntologyID); nextReasoner.getRootOntology().getOWLOntologyManager().applyChange(new AddImport(nextInferredAxiomsOntology, new OWLImportsDeclarationImpl(importIRI))); iog.fillOntology(nextInferredAxiomsOntology.getOWLOntologyManager(), nextInferredAxiomsOntology); return nextInferredAxiomsOntology; }