Java Code Examples for org.semanticweb.owlapi.reasoner.OWLReasoner#dispose()

The following examples show how to use org.semanticweb.owlapi.reasoner.OWLReasoner#dispose() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimJSONTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testInfoProfile() throws OWLOntologyCreationException, IOException, UnknownOWLClassException, OBOFormatParserException {

	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResource("sim/mp-subset-1.obo").getAbsolutePath());
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);
	final int truncLen = 200;
	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		createOwlSim();
			//sos.setReasoner(reasoner);
		LOG.info("Reasoner="+owlsim.getReasoner());

		SimJSONEngine sj = new SimJSONEngine(g, owlsim);

		//sos.saveOntology("/tmp/z.owl");

		reasoner.flush();
		
		owlsim.createElementAttributeMapFromOntology();
		owlsim.computeSystemStats();
		
		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			String jsonStr = sj.getAttributeInformationProfile(owlsim.getAttributesForElement(i));
			LOG.info("InformationInfo:"+jsonStr);
		}
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 2
Source File: SimStatsTests.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testIxI() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResource("sim/mp-subset-1.obo").getAbsolutePath());
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);
	setOutput("target/basic-owlsim-test.out");

	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {
		this.createOwlSim();
		owlsim.createElementAttributeMapFromOntology();
		
		reasoner.flush();
		owlsim.computeSystemStats();
		owlsim.calculateMetricStats(owlsim.getAllElements(),owlsim.getAllElements());

		String[] metrics = {"bmaAsymIC","bmaSymIC","bmaInverseAsymIC", "combinedScore", "simJ", "simGIC","maxIC"};
		for (String m : metrics) {
			LOG.info("Test Summary(mean) for "+m+": "+owlsim.getMetricStats(Stat.MEAN).get(m).getSummary());
			LOG.info("Test Summary(min) for "+m+": "+owlsim.getMetricStats(Stat.MIN).get(m).getSummary());
			LOG.info("Test Summary(max) for "+m+": "+owlsim.getMetricStats(Stat.MAX).get(m).getSummary());
		}
	} finally {
		reasoner.dispose();
	}
	
}
 
Example 3
Source File: BasicOWLSimTestUsingSOS.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test 
public void testGetEntropy() throws OWLOntologyCreationException, IOException, OBOFormatParserException, UnknownOWLClassException {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResourceIRIString("sim/mp-subset-1.obo"));
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);

	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		owlsim = new SimpleOwlSim(sourceOntol);
		((SimpleOwlSim) owlsim).setReasoner(reasoner);

		reasoner.flush();
		Double e = owlsim.getEntropy();
		LOG.info("ENTROPY OF ONTOLOGY = "+e);

		for (String subset : g.getAllUsedSubsets()) {
			LOG.info("SUBSET:"+subset);
			e = owlsim.getEntropy(g.getOWLClassesInSubset(subset));
			LOG.info(" ENTROPY OF "+subset+" = "+e);
		}
	}
	finally {
		reasoner.dispose();
	}		
}
 
Example 4
Source File: GOReciprocalAnnotationRule.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public GOReciprocalAnnotationRule(OWLGraphWrapper graph, TraversingEcoMapper eco) {
	this.graph = graph;
	evidences = eco.getAllValidEvidenceIds("IPI",  true);
	
	OWLClass proteinBindingCls = graph.getOWLClassByIdentifier(PROTEIN_BINDING_GO_ID);
	if (proteinBindingCls == null) {
		throw new RuntimeException("No class found for identifier: "+PROTEIN_BINDING_GO_ID);
	}
	ElkReasonerFactory factory = new ElkReasonerFactory();
	OWLReasoner reasoner = null;
	try {
		reasoner = factory.createReasoner(graph.getSourceOntology());
		proteinBindingClasses = new HashSet<OWLClass>();
		proteinBindingClasses.add(proteinBindingCls);
		Set<OWLClass> subClasses = reasoner.getSubClasses(proteinBindingCls, false).getFlattened();
		for (OWLClass cls : subClasses) {
			if (!cls.isBottomEntity() && !cls.isTopEntity()) {
				proteinBindingClasses.add(cls);
			}
		}
	}
	finally {
		if (reasoner != null) {
			reasoner.dispose();
		}
	}
}
 
Example 5
Source File: BasicOWLSimTestUsingSOS.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBasicSim() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, MathException, UnknownOWLClassException {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOWL(getResourceIRIString("sim/mp-subset-1.obo"));
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);

	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		owlsim = new SimpleOwlSim(sourceOntol);
		((SimpleOwlSim) owlsim).setReasoner(reasoner);
		LOG.info("Reasoner="+owlsim.getReasoner());

		//sos.saveOntology("/tmp/z.owl");

		reasoner.flush();
		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			//System.out.println("COMPARING: "+i);
			for (OWLNamedIndividual j : sourceOntol.getIndividualsInSignature()) {
				showSimOld(i,j);
			}
		}
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 6
Source File: SimJSONTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testFindCoAnnotationList() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOWL(getResourceIRIString("sim/mp-subset-1.obo"));
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);
	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		createOwlSim();
			//sos.setReasoner(reasoner);
		LOG.info("Reasoner="+owlsim.getReasoner());
		reasoner.flush();
		owlsim.createElementAttributeMapFromOntology();

		owlsim.populateFullCoannotationMatrix();


		SimJSONEngine sj = new SimJSONEngine(g, owlsim);


		List<OWLClass> allClasses = new ArrayList<OWLClass>();
		allClasses.addAll(g.getAllOWLClasses());
		Collections.shuffle(allClasses);

		int limit = 5;
		String jsonStr = sj.getCoAnnotationListForAttribute(g.getOWLClassByIdentifier("MP:0002082"),limit);
		LOG.info("Dumping coannotations and scores for all annotated classes");
		
		LOG.info("EXAMPLE:"+jsonStr);
	
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 7
Source File: BasicOWLSimTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test 
public void testGetEntropy() throws OWLOntologyCreationException, IOException, OBOFormatParserException, UnknownOWLClassException {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResourceIRIString("sim/mp-subset-1.obo"));
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);

	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		owlsim = new SimpleOwlSim(sourceOntol);
		((SimpleOwlSim) owlsim).setReasoner(reasoner);

		reasoner.flush();
		Double e = owlsim.getEntropy();
		LOG.info("ENTROPY OF ONTOLOGY = "+e);

		for (String subset : g.getAllUsedSubsets()) {
			LOG.info("SUBSET:"+subset);
			e = owlsim.getEntropy(g.getOWLClassesInSubset(subset));
			LOG.info(" ENTROPY OF "+subset+" = "+e);
		}
	}
	finally {
		reasoner.dispose();
	}		
}
 
Example 8
Source File: GCIUtilTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testOrganismPair() throws Exception{
	g =  getOntologyWrapper("limb_gci.owl");
	ElkReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner r = rf.createReasoner(g.getSourceOntology());
	try {
		Set<OWLSubClassOfAxiom> axioms = GCIUtil.getSubClassOfSomeValuesFromAxioms(r);
		int n = 0;
		for (OWLSubClassOfAxiom axiom : axioms) {
			String c = ((OWLClass) axiom.getSubClass()).getIRI().toString();
			OWLObjectSomeValuesFrom svf = (OWLObjectSomeValuesFrom) axiom.getSuperClass();
			String rel = ((OWLObjectProperty) svf.getProperty()).getIRI().toString();
			String p = ((OWLClass) svf.getFiller()).getIRI().toString();
			String axstr = c + " " + rel + " " + p;
			System.out.println(axstr);
			if ("http://x.org/phalanx-development http://x.org/part-of http://x.org/digit-development".equals(axstr)) {
				n |= 1;
			}
			if ("http://x.org/digit-development http://x.org/part-of http://x.org/autopod-development".equals(axstr)) {
				n |= 2;
			}
			if ("http://x.org/limb-development http://x.org/part-of http://x.org/organism-development".equals(axstr)) {
				n |= 4;
			}
			if ("http://x.org/autopod-development http://x.org/part-of http://x.org/limb-development".equals(axstr)) {
				n |= 8;
			}
		}
		assertEquals(4, axioms.size());
		assertEquals(15, n);
	}
	finally {
		r.dispose();
	}

}
 
Example 9
Source File: SimJSONTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSearch() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResource("sim/mp-subset-1.obo").getAbsolutePath());
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);
	final int truncLen = 200;
	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		createOwlSim();
			//sos.setReasoner(reasoner);
		LOG.info("Reasoner="+owlsim.getReasoner());

		SimJSONEngine sj = new SimJSONEngine(g, owlsim);

		//sos.saveOntology("/tmp/z.owl");

		reasoner.flush();
		
		owlsim.createElementAttributeMapFromOntology();
		owlsim.computeSystemStats();
		

		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			Set<OWLClass> atts = owlsim.getAttributesForElement(i);
			String jsonStr = sj.search(atts, "MGI", true, false);
			
			LOG.info(jsonStr);
		}
		
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 10
Source File: IncrementalClassification.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws OWLOntologyStorageException,
		OWLOntologyCreationException {
	OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

	// Load your ontology
	OWLOntology ont = manager.loadOntologyFromOntologyDocument(new File("path-to-ontology"));

	// Create an ELK reasoner.
	OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
	OWLReasoner reasoner = reasonerFactory.createReasoner(ont);

	// Classify the ontology.
	reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);

	OWLDataFactory factory = manager.getOWLDataFactory();
	OWLClass subClass = factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#AbsoluteShapeState"));
	OWLAxiom removed = factory.getOWLSubClassOfAxiom(subClass, factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#ShapeState")));
	
	OWLAxiom added = factory.getOWLSubClassOfAxiom(subClass, factory.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/galen#GeneralisedStructure")));
	// Remove an existing axiom, add a new axiom
	manager.addAxiom(ont, added);
	manager.removeAxiom(ont, removed);
	// This is a buffering reasoner, so you need to flush the changes
	reasoner.flush();
	
	// Re-classify the ontology, the changes should be accommodated
	// incrementally (i.e. without re-inferring all subclass relationships)
	// You should be able to see it from the log output
	reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);		
	
	// Terminate the worker threads used by the reasoner.
	reasoner.dispose();
}
 
Example 11
Source File: BasicOWLSimTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBasicSim() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResource("sim/mp-subset-1.obo").getAbsolutePath());
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);
	setOutput("target/basic-owlsim-test.out");
	
	owlpp = new OWLPrettyPrinter(g);

	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		this.createOwlSim();
		owlsim.createElementAttributeMapFromOntology();
		
		//sos.saveOntology("/tmp/z.owl");

		reasoner.flush();
		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			for (OWLNamedIndividual j : sourceOntol.getIndividualsInSignature()) {
				showSim(i,j);
			}
		}
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 12
Source File: DLQueryTool.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Execute the DL query on the given ontology graph. Uses the factory to create 
 * the {@link OWLReasoner} for an internal query ontology.
 * 
 * @param queryObject
 * @param ontology
 * @param reasonerFactory
 * @return set of {@link OWLClass} which 
 */
static Set<OWLClass> executeQuery(OWLClassExpression queryObject, OWLOntology ontology, 
		OWLReasonerFactory reasonerFactory) 
{
	Set<OWLClass> subset = new HashSet<OWLClass>();
	
	LOG.info("Create reasoner for query ontology.");
	// Create an instance of an OWL API reasoner
	OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
	try {
		LOG.info("Start evaluation for DL query subclass of: "+queryObject);
		NodeSet<OWLClass> node = reasoner.getSubClasses(queryObject, false);
		if (node != null) {
			Set<OWLClass> classes = node.getFlattened();
			for (OWLClass owlClass : classes) {
				if (!owlClass.isBottomEntity() && !owlClass.isTopEntity()) {
					subset.add(owlClass);
				}
			}
			LOG.info("Number of found classes for dl query subclass of: "+classes.size());
		}
		return subset;
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 13
Source File: ElkReasonerTest.java    From elk-reasoner with Apache License 2.0 4 votes vote down vote up
/**
 * Testing correctness of the reasoner with respect to ontology changes
 * 
 * removing an axiom ":X is-a :Y"
 */
@Test
public void testRemovingXY() throws Exception {

	OWLOntologyManager man = TestOWLManager.createOWLOntologyManager();
	OWLDataFactory dataFactory = man.getOWLDataFactory();

	// set up resolution of prefixes
	PrefixManager pm = new DefaultPrefixManager();
	pm.setDefaultPrefix("http://www.example.com/main#");
	pm.setPrefix("A:", "http://www.example.com/A#");
	pm.setPrefix("B:", "http://www.example.com/B#");

	// define query classes
	OWLClass mainX = dataFactory.getOWLClass(":X", pm);
	OWLClass mainY = dataFactory.getOWLClass(":Y", pm);
	OWLClass extA = dataFactory.getOWLClass("A:A", pm);
	OWLClass extB = dataFactory.getOWLClass("B:B", pm);
	OWLClass extC = dataFactory.getOWLClass("B:C", pm);

	// loading the root ontology
	OWLOntology root = loadOntology(man, "root.owl");

	// Create an ELK reasoner.
	OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
	OWLReasoner reasoner = reasonerFactory.createReasoner(root);

	try {

		// ************************************
		// ** removing an axiom ":X is-a :Y"
		// ************************************
		OWLAxiom axiom = dataFactory.getOWLSubClassOfAxiom(mainX, mainY);
		man.removeAxiom(root, axiom);
		reasoner.flush();

		// the root ontology contains one fewer axioms
		assertEquals(root.getAxiomCount(), 2);
		// the number of ontologies in the import closure does not change
		assertEquals(root.getImportsClosure().size(), 3);
		// the total number of axioms reduces
		assertEquals(getAxioms(root).size(), 5);

		// reasoner queries -- first subsumption is gone
		assertFalse(reasoner.getSuperClasses(mainX, true).containsEntity(
				mainY));
		assertTrue(reasoner.getSuperClasses(mainX, true).containsEntity(
				extA));
		assertTrue(reasoner.getSuperClasses(mainY, true).containsEntity(
				extB));
		assertTrue(reasoner.getSuperClasses(extA, true)
				.containsEntity(extB));
		assertTrue(reasoner.getSuperClasses(extB, true)
				.containsEntity(extC));

	} finally {
		reasoner.dispose();
	}

}
 
Example 14
Source File: PropertyViewOntologyBuilderTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * setup:
 * 
 * SourceOntology
 * O = (a subset of) GO, merged in with a relations ontology
 * 
 * elementsOntology
 * E = {gene1, gene2, ..., gene1 SubClassOf R some GO_classA, ....}
 * genes are represented as classes.  relationships to 
 * class expressions using GO (e.g. g1 SubClassOf has_prototype some involved_in some P)
 * [this may not be the final form used in GO]
 * 
 * property
 * P = has_attribute [GORELTEST:0000001]
 * this is a promiscuous property that has property chains defined such that it will
 * connect genes to GO processes plus the processes which they are part of
 * 
 *   has_attribute o part_of -> has_attribute
 * 
 * We expect the resulting ontology O(P,E)' to classify the genes
 * in a subsumption hierarchy that masks the partOf relations in O
 * 
 * @throws Exception 
 */
@Test
public void testGeneAssociationPropertyView() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	g = pw.parseToOWLGraph(getResourceIRIString("test_gene_association_mgi_gaf.owl"));
	OWLOntology relOnt = pw.parseOWL(getResourceIRIString("go-annot-rel.owl"));
	g.mergeOntology(relOnt);
	OWLOntology sourceOntol = pw.parseOBO(getResourceIRIString("test_go_for_mgi_gaf.obo"));
	g.addSupportOntology(sourceOntol);
	OWLOntology annotOntol = g.getSourceOntology(); // E=O

	OWLObjectProperty viewProperty = g.getOWLObjectPropertyByIdentifier("GORELTEST:0000001");

	PropertyViewOntologyBuilder pvob = 
		new PropertyViewOntologyBuilder(sourceOntol,
				annotOntol,
				viewProperty);
	pvob.setAssumeOBOStyleIRIs(true); // this is default but we assert anyway
	pvob.setViewLabelPrefixAndSuffix("", " gene");
	pvob.setFilterUnused(false);
	pvob.buildViewOntology(IRI.create("http://x.org"), IRI.create("http://y.org"));
	OWLOntology avo = pvob.getAssertedViewOntology();
	OWLReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner reasoner = rf.createReasoner(avo);
	try {
		pvob.buildInferredViewOntology(reasoner);
		OWLOntology ivo = pvob.getInferredViewOntology();
		g = new OWLGraphWrapper(ivo);
		OWLPrettyPrinter pp = new OWLPrettyPrinter(g);


		if (RENDER_ONTOLOGY_FLAG) {
			for (OWLAxiom a : ivo.getAxioms()) {
				LOG.info("GO: " + pp.render(a));
			}
		}
		LOG.info("Logical axioms: "+ivo.getLogicalAxiomCount());

		LOG.info("View entities: "+pvob.getViewEntities().size());

		// based on NT formation SubClassOf part_of NT development
		//assertOntologyContainsSubClassOf("neural tube formation", "embryonic epithelial tube formation");

		// based on NT formation SubClassOf part_of NT development
		assertOntologyContainsSubClassOf("neural tube formation gene", "neural tube development gene");
		assertOntologyContainsSubClassOf("neural tube formation gene", "embryonic epithelial tube formation gene");

		//pw.saveOWL(pvob.getAssertedViewOntology(), "file:///tmp/zz.owl", g);

		//pw.saveOWL(ivo, "file:///tmp/z.owl", g);
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 15
Source File: ElkReasonerTest.java    From elk-reasoner with Apache License 2.0 4 votes vote down vote up
/**
 * Testing correctness of the reasoner when changes are made to other, imported or not, ontologies
 * 
 */
@Test
public void testChangesToOtherOntologies() throws Exception {

	OWLOntologyManager man = TestOWLManager.createOWLOntologyManager();
	OWLDataFactory dataFactory = man.getOWLDataFactory();

	// set up resolution of prefixes
	PrefixManager pm = new DefaultPrefixManager();
	pm.setDefaultPrefix("http://www.example.com/main#");
	pm.setPrefix("A:", "http://www.example.com/A#");
	pm.setPrefix("B:", "http://www.example.com/B#");

	// define query classes
	OWLClass mainY = dataFactory.getOWLClass(":Y", pm);
	OWLClass extA = dataFactory.getOWLClass("A:A", pm);
	OWLClass extB = dataFactory.getOWLClass("B:B", pm);
	OWLClass extC = dataFactory.getOWLClass("B:C", pm);

	// loading the root ontology
	OWLOntology root = loadOntology(man, "root.owl");
	// the imported ontologies must be loaded
	OWLOntology ontoA = man.getOntology(IRI.create("http://www.example.com/A"));
	OWLOntology ontoB = man.getOntology(IRI.create("http://www.example.com/B"));

	// Create an ELK reasoner.
	OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
	OWLReasoner reasoner = reasonerFactory.createReasoner(root);

	try {
		
		assertTrue(reasoner.getSuperClasses(extA, false).containsEntity(
				extC));
		assertTrue(reasoner.getSuperClasses(mainY, false).containsEntity(
				extC));
		
		// ************************************
		// ** removing an axiom "A:A is-a B:B" from impA
		// ************************************
		OWLAxiom axiom = dataFactory.getOWLSubClassOfAxiom(extA, extB);
		man.removeAxiom(ontoA, axiom);
		reasoner.flush();
		
		assertFalse(reasoner.getSuperClasses(extA, false).containsEntity(
				extC));
		// put it back
		man.addAxiom(ontoA, axiom);
		reasoner.flush();
		
		assertTrue(reasoner.getSuperClasses(extA, false).containsEntity(
				extC));

		// ************************************
		// ** removing an axiom "B:B is-a B:C" from impB
		// ************************************
		axiom = dataFactory.getOWLSubClassOfAxiom(extB, extC);
		man.removeAxiom(ontoB, axiom);
		reasoner.flush();
		
		assertFalse(reasoner.getSuperClasses(mainY, false).containsEntity(
				extC));

	}
	finally {
		reasoner.dispose();
	}
}
 
Example 16
Source File: SparqlDLQueryTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testQuery() 
{
	OWLReasoner reasoner = null;
	try {
		// Create an ontology manager
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

		// Load the wine ontology from the web.
		OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create("http://www.w3.org/TR/owl-guide/wine.rdf"));

		// Create an instance of an OWL API reasoner (we use the OWL API built-in StructuralReasoner for the purpose of demonstration here)
		StructuralReasonerFactory factory = new StructuralReasonerFactory();
		reasoner = factory.createReasoner(ont);
		// Optionally let the reasoner compute the most relevant inferences in advance
		reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS,InferenceType.OBJECT_PROPERTY_ASSERTIONS);

		// Create an instance of the SPARQL-DL query engine
		engine = QueryEngine.create(manager, reasoner, true);

		// Some queries which cover important basic language constructs of SPARQL-DL

		// All white wines (all individuals of the class WhiteWine and sub classes thereof)
		processQuery(
				"SELECT * WHERE {\n" +
						"Type(?x, <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#WhiteWine>)" +
						"}"	
				);

		// The white wines (the individuals of WhiteWine but not of it's sub classes) 
		processQuery(
				"SELECT * WHERE {\n" +
						"DirectType(?x, <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#RedTableWine>)" +
						"}"
				);

		// Is PinotBlanc a sub class of Wine?
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" +
						"ASK {\n" +
						"SubClassOf(wine:PinotBlanc, wine:Wine)" +
						"}"
				);

		// The direct sub classes of FrenchWine
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" +
						"SELECT ?x WHERE {\n" +
						"DirectSubClassOf(?x, wine:FrenchWine)" +
						"}"	
				);

		// All individuals
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" +
						"SELECT * WHERE {\n" +
						"Individual(?x)" +
						"}"
				);

		// All functional ObjectProperties
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" +
						"SELECT * WHERE {\n" +
						"ObjectProperty(?x), " +
						"Functional(?x)" +
						"}"
				);

		// The strict sub classes of DryWhiteWine (sub classes with are not equivalent to DryWhiteWine)
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" +
						"SELECT ?x WHERE {\n" +
						"StrictSubClassOf(?x, wine:DryWhiteWine)" +
						"}"
				);

		// All the grapes from which RedTableWines are made from (without duplicates)
		processQuery(
				"PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n" + 
						"SELECT DISTINCT ?v WHERE {\n" +
						"Type(?i, wine:RedTableWine),\n" +
						"PropertyValue(?i, wine:madeFromGrape, ?v)" +
						"}"	
				);

	}
	catch(UnsupportedOperationException exception) {
		System.out.println("Unsupported reasoner operation.");
	}
	catch(OWLOntologyCreationException e) {
		System.out.println("Could not load the wine ontology: " + e.getMessage());
	}
	finally {
		if (reasoner != null) {
			reasoner.dispose();
		}
	}
}
 
Example 17
Source File: GraphReasonerTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void testOrganismPair() throws Exception{
	g =  getOntologyWrapper("q-in-e-v1.omn");
	g.getConfig().isGraphReasonedAndRelaxed = false;
	OWLReasoner r = getGraphReasoner(g);
	
	try {
	
		findDescendants(r, "part_of some limb", 3);

		findDescendants(r, "inheres_in_part_of some limb", 4);

		findDescendants(r, "limb", 3);
		findDescendants(r, "abnormal_morphology");
		findDescendants(r, "develops_from some limb_bud", 6);
		findDescendants(r, "part_of some hindlimb", 1);
		findDescendants(r, "autopod", 3);
		findDescendants(r, "autopod and (part_of some hindlimb)", 1);


		findDescendants(r, "(part_of some limb) and not foot", 2);
		findDescendants(r, "not foot and (part_of some limb)", 2);
		findDescendants(r, "not foot");

		findDescendants(r, "inheres_in some hand", 1);
		findDescendants(r, "inheres_in some limb", 2);
		findDescendants(r, "inheres_in some (hindlimb or forelimb)", 2);
		findDescendants(r, "inheres_in some (part_of some limb)", 2);
		findDescendants(r, "inheres_in_part_of some limb", 4);
		findDescendants(r, "hyperplastic and inheres_in_part_of some limb", 2);
		findDescendants(r, "hyperplastic and inheres_in some (part_of some (anterior_to some hindlimb))", 1);
		findDescendants(r, "(anterior_to some hindlimb)", 1);
		findDescendants(r, "part_of some (anterior_to some hindlimb)", 1);
		findDescendants(r, "hyperplastic and inheres_in some hand", 1);
		findDescendants(r, "hyperplastic_hand", 1);
		findDescendants(r, "hyperplastic", 3);

		findIndividuals(r, "metazoan", 5);
		findIndividuals(r, "human", 3);
		findIndividuals(r, "has_phenotype some hyperplastic_hand", 3);
		findIndividuals(r, "human and has_phenotype some hyperplastic_hand", 2); // underestimation without pre-reasoning
		findIndividuals(r, "human and has_phenotype some abnormal_morphology", 3);
		findIndividuals(r, "human and has_phenotype some hyperplastic", 3);
		////findIndividuals(r, "has_phenotype some (not hyperplastic)", 2);
		findIndividuals(r, "fly and has_phenotype some (inheres_in some compound_eye)", 1);
		findIndividuals(r, "fly and has_phenotype some (inheres_in some (has_part some ommatidium))", 1);

	}
	finally {
		r.dispose();
	}

}
 
Example 18
Source File: SimJSONTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testInfoProfileWithSubscores() throws OWLOntologyCreationException, IOException, UnknownOWLClassException, OBOFormatParserException {

	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResource("sim/mp-subset-1.obo").getAbsolutePath());
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);

	Set<OWLClass> upperLevelClasses = new HashSet<OWLClass>();
	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0000001")); //root, should be the same as overall
	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0000003")); //Adipose Tissue Morphology
	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0001544")); //Abnormal Blood morphology
	String id = "BOGUS:1234567";
	IRI iri = g.getIRIByIdentifier(id);
	OWLClass c = g.getDataFactory().getOWLClass(iri);
	LOG.info("Unresolvable id:"+id+". Making temp class element:"+c.toString());
	upperLevelClasses.add(c);

	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0002160")); //Abnormal Reproductive System Morphology
	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0002152")); //Abnormal Brain Morphology
	upperLevelClasses.add(g.getOWLClassByIdentifier("MP:0003631")); //Nervous System Phenotype
	id = "BOGUS:2345678";
	iri = g.getIRIByIdentifier(id);
	c = g.getDataFactory().getOWLClass(iri);
	LOG.info("Unresolvable id:"+id+". Making temp class element:"+c.toString());
	upperLevelClasses.add(c);

	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		createOwlSim();
		LOG.info("Reasoner="+owlsim.getReasoner());

		SimJSONEngine sj = new SimJSONEngine(g, owlsim);

		reasoner.flush();
		
		owlsim.createElementAttributeMapFromOntology();
		owlsim.computeSystemStats();
		
		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			String jsonStr = sj.getAttributeInformationProfile(owlsim.getAttributesForElement(i),upperLevelClasses);
			LOG.info("InformationProfile:"+jsonStr);
		}
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 19
Source File: SolrCommandRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Experimental method for trying out the loading of complex_annotation doc type.
 * Works with --read-ca-list <file>.
 * 
 * @param opts
 * @throws Exception
 */
@CLIMethod("--solr-load-complex-exp")
public void loadComplexAnnotationSolr(Opts opts) throws Exception {

	// Check to see if the global url has been set.
	String url = sortOutSolrURL(globalSolrURL);				

	// Only proceed if our environment was well-defined.
	if( caFiles == null || caFiles.isEmpty() ){
		LOG.warn("LEGO environment not well defined--will skip loading LEGO/CA.");
	}else{

		// NOTE: These two lines are remainders from old code, and I'm not sure of their place in this world of ours.
		// I wish there was an arcitecture diagram somehwere...
		OWLOntologyManager manager = pw.getManager();
		OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();

		// Actual loading--iterate over our list and load individually.
		for( String fname : caFiles ){
			OWLReasoner currentReasoner = null;
			OWLOntology ontology = null;

			// TODO: Temp cover for missing group labels and IDs.
			//String agID = legoFile.getCanonicalPath();
			String pretmp = StringUtils.removeEnd(fname, ".owl");
			String[] bits = StringUtils.split(pretmp, "/");
			String agID = bits[bits.length -1];
			String agLabel = new String(StringUtils.replaceOnce(agID, ":", "_"));

			try {
				ontology = pw.parseOWL(IRI.create(fname));
				currentReasoner = reasonerFactory.createReasoner(ontology);

				// Some sanity checks--some of the genereated ones are problematic.
				boolean consistent = currentReasoner.isConsistent();
				if( consistent == false ){
					LOG.info("Skip since inconsistent: " + fname);
					continue;
				}
				Set<OWLClass> unsatisfiable = currentReasoner.getUnsatisfiableClasses().getEntitiesMinusBottom();
				if (unsatisfiable.isEmpty() == false) {
					LOG.info("Skip since unsatisfiable: " + fname);
					continue;
				}

				Set<OWLNamedIndividual> individuals = ontology.getIndividualsInSignature();
				Set<OWLAnnotation> modelAnnotations = ontology.getAnnotations();
				OWLGraphWrapper currentGraph = new OWLGraphWrapper(ontology);						
				try {
					LOG.info("Trying complex annotation load of: " + fname);
					ComplexAnnotationSolrDocumentLoader loader =
							new ComplexAnnotationSolrDocumentLoader(url, currentGraph, currentReasoner, individuals, modelAnnotations, agID, agLabel, fname);
					loader.load();
				} catch (SolrServerException e) {
					LOG.info("Complex annotation load of " + fname + " at " + url + " failed!");
					e.printStackTrace();
					System.exit(1);
				}
			} finally {
				// Cleanup reasoner and ontology.
				if (currentReasoner != null) {
					currentReasoner.dispose();
				}
				if (ontology != null) {
					manager.removeOntology(ontology);
				}
			}
		}
	}
}
 
Example 20
Source File: GafCommandRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected int preCheckOntology(String inConsistentMsg, String unsatisfiableMsg, String unsatisfiableModule) throws OWLException, IOException {
	// pre-check: only try to load ontology iff:
	// * ontology is consistent 
	// * no unsatisfiable classes
	OWLReasoner currentReasoner = reasoner;
	boolean disposeReasoner = false;
	try {
		if (currentReasoner == null) {
			disposeReasoner = true;
			currentReasoner = new ElkReasonerFactory().createReasoner(g.getSourceOntology());
		}
		boolean consistent = currentReasoner.isConsistent();
		if (consistent == false) {
			LOG.error(inConsistentMsg);
			return -1;
		}
		Set<OWLClass> unsatisfiable = currentReasoner.getUnsatisfiableClasses().getEntitiesMinusBottom();
		if (unsatisfiable.isEmpty() == false) {
			LOG.error(unsatisfiableMsg);
			OWLPrettyPrinter prettyPrinter = getPrettyPrinter();
			for (OWLClass owlClass : unsatisfiable) {
				LOG.error("Unsatisfiable: "+prettyPrinter.render(owlClass));
			}
			LOG.info("Creating module for unsatisfiable classes in file: "+unsatisfiableModule);
			ModuleType mtype = ModuleType.BOT;
			OWLOntologyManager m = g.getManager();
			SyntacticLocalityModuleExtractor sme = new SyntacticLocalityModuleExtractor(m, g.getSourceOntology(), mtype );
			Set<OWLEntity> seeds = new HashSet<OWLEntity>(unsatisfiable);
			Set<OWLAxiom> axioms = sme.extract(seeds);
			OWLOntology module = m.createOntology();
			m.addAxioms(module, axioms);
			File moduleFile = new File(unsatisfiableModule).getCanonicalFile();
			m.saveOntology(module, IRI.create(moduleFile));
			return -1;
		}
	}
	finally {
		if (disposeReasoner && currentReasoner != null) {
			currentReasoner.dispose();
		}
	}
	return 0;
}