org.semanticweb.owlapi.model.OWLOntologyCreationException Java Examples

The following examples show how to use org.semanticweb.owlapi.model.OWLOntologyCreationException. 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: SimSpeedTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Ignore("This test requires an external resource. This can lead to false positive failures.")
public void bitmapTest() throws OWLOntologyCreationException, OBOFormatParserException, IOException {
	Set<Integer> ixs = new HashSet<Integer>();
	ixs.add(99);
	ixs.add(2000);
	ixs.add(7777);
	EWAHCompressedBitmap bm = bm(ixs);
	Set<Integer> ixs2 = new HashSet<Integer>();
	for (int i : bm.toArray()) {
		System.out.println(i);
		ixs.add(i);
	}
	assert(ixs.equals(ixs2));
	
}
 
Example #2
Source File: WEKAPipelineCharacterizer.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new pipeline characterizer that uses the given descriptions of
 * parameters to characterize MLPipelines.
 * 
 * @param componentParameters
 *            The description of parameters in the current configuration
 *            together with their refinements.
 */
public WEKAPipelineCharacterizer(
		Map<Component, Map<Parameter, ParameterRefinementConfiguration>> componentParameters) {
	TreeMiner miner = new TreeMiner();
	miner.setCountMultipleOccurrences(false);
	miner.setOnlySearchForPatternsThatStartWithTheRoot(true);
	this.treeMiner = new TreeMiner();
	this.componentParameters = componentParameters;

	try {
		ontologyConnector = new WEKAOntologyConnector();
	} catch (OWLOntologyCreationException e) {
		logger.error("Cannot connect to Ontology!");
		throw new OntologyNotFoundException(e);
	}
}
 
Example #3
Source File: QueryingWithNamedClasses.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws OWLOntologyCreationException {
	// Creation of a new Querier = Motor running the query
	System.out.println("Initialization of the querier...");

	QueryingWithNamedClasses querier = new QueryingWithNamedClasses();
	// Actual query:
	// "In our ontology, what are the subclasses of the named class MeatEater?"
	// It will work only if you use a reference to a class already present
	// in your ontology (named class).
	Set<OWLClass> results = querier.getSubClasses("MeatEater");
	// The result is the set of classes satisfying the query.
	for (OWLClass owlClass : results) {
		// Just iterates over it and print the name of the class
		System.out.println("Subclass: "
				+ querier.shortFormProvider.getShortForm(owlClass));
	}
}
 
Example #4
Source File: ExhaustiveSimPreProcessorTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void exhaustiveTestOnGO() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, MathException {
	/*
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOBO(getResourceIRIString("go-subset-t1.obo"));
	g = new OWLGraphWrapper(sourceOntol);
	IRI vpIRI = g.getOWLObjectPropertyByIdentifier("GOTESTREL:0000001").getIRI();
	TableToAxiomConverter ttac = new TableToAxiomConverter(g);
	ttac.config.axiomType = AxiomType.CLASS_ASSERTION;
	ttac.config.property = vpIRI;
	ttac.config.isSwitchSubjectObject = true;
	ttac.parse("src/test/resources/simplegaf-t1.txt");

	OWLPrettyPrinter pp = new OWLPrettyPrinter(g);
	
	AutomaticSimPreProcessor pproc = new AutomaticSimPreProcessor();
	pproc.setInputOntology(sourceOntol);
	pproc.setOutputOntology(sourceOntol);
	pproc.preprocess();
	*/
}
 
Example #5
Source File: BigFastOwlSimTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void t(String idspace, int size) throws OWLOntologyCreationException, OBOFormatParserException, IOException, UnknownOWLClassException {
	Runtime rt = Runtime.getRuntime();
	load(idspace);
	ABoxUtils.makeDefaultIndividuals(getOntology());
	long usedMB0 = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;
	precompute();
	long t1 = System.currentTimeMillis();
	long usedMB1 = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;
	msg("LOADED: "+idspace+"  NUM:"+size+" usedMB:"+usedMB0);
	msg("TEST: "+idspace+"  NUM:"+size+" usedMB:"+usedMB1);
	axa(size);
	long t2 = System.currentTimeMillis();
	long usedMB2 = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;
	msg("COMPLETED TEST: "+idspace+"  NUM:"+size+" usedMB:"+usedMB2+
			" usedMBDelta:" + (usedMB2-usedMB1) +
			" TIME (ms):"+(t2-t1));		

	if (idspace.equals("mp")) {
		OWLClass c1 = getCls("MP_0003737"); // ossification of pinnae
		OWLClass c2 = getCls("MP_0002895"); // abnormal otolithic membrane morphology
		assert(1 == owlsim.getAttributeJaccardSimilarity(c1, c1));
		assert(1 == owlsim.getAttributeJaccardSimilarity(c2, c2));
		msg("SIMTEST="+owlsim.getAttributeJaccardSimilarity(c1, c2));
	}
}
 
Example #6
Source File: OGWSubAnnotationTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Load the ontology <code>/graph/subannotprops.owl</code> into {@link #wrapper}, 
 * and also loads the {@code OWLAnnotationProperty}s needed.
 */
@BeforeClass
public static void loadTestOntology() 
        throws OWLOntologyCreationException, OBOFormatParserException, 
        IOException {
    ParserWrapper parserWrapper = new ParserWrapper();
    OWLOntology ont = parserWrapper.parse(OGWSubAnnotationTest.class.getResource(
            "/graph/subannotprops.owl").getFile());
    wrapper = new OWLGraphWrapper(ont);
    OWLDataFactory f = wrapper.getManager().getOWLDataFactory();
    subsetProp = f.getOWLAnnotationProperty(
            IRI.create("http://www.geneontology.org/formats/oboInOwl#SubsetProperty"));
    groupProp = f.getOWLAnnotationProperty(
            IRI.create("http://purl.obolibrary.org/obo/uberon/core#grouping_class"));
    fake1Prop = f.getOWLAnnotationProperty(
            IRI.create("http://purl.obolibrary.org/obo/uberon/core#fake1"));
    fake2Prop = f.getOWLAnnotationProperty(
            IRI.create("http://purl.obolibrary.org/obo/uberon/core#fake2"));
    lonelyProp = f.getOWLAnnotationProperty(
            IRI.create("http://purl.obolibrary.org/obo/uberon/core#lonely"));
}
 
Example #7
Source File: OWLHandler.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Deprecated
public void deleteFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
	if (isHelp()) {
		info("generates ClassAssertion");
		return;
	}
	OWLOntology ont = resolveOntology(Param.ontology);
	OWLIndividual i = resolveIndividual(Param.individualId);
	OWLIndividual j = resolveIndividual(Param.fillerId);
	OWLObjectProperty p = resolveObjectProperty(Param.propertyId);
	for (OWLObjectPropertyAssertionAxiom ax : ont.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION)) {
		if (ax.getSubject().equals(i)) {
			if (p == null || ax.getProperty().equals(p)) {
				if (j == null || ax.getObject().equals(j)) {
					removeAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j));
				}
			}
		}
	}
	String jsonStr = "";
	response.getWriter().write(jsonStr);
}
 
Example #8
Source File: QueryOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests an update statement that adds a label.
 *
 * @throws IOException on IO error
 * @throws OWLOntologyStorageException on ontology error
 * @throws OWLOntologyCreationException on ontology error
 */
@Test
public void testExecUpdate()
    throws IOException, OWLOntologyCreationException, OWLOntologyStorageException {
  OWLOntology inputOntology = loadOntology("/simple.owl");
  Model model = QueryOperation.loadOntologyAsModel(inputOntology);
  String updateString =
      "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
          + "PREFIX s: <https://github.com/ontodev/robot/robot-core/src/test/resources/simple.owl#>"
          + "INSERT { "
          + "s:test2 rdfs:label \"test 2\" ."
          + " } WHERE {}";
  QueryOperation.execUpdate(model, updateString);
  OWLOntology outputOntology = QueryOperation.convertModel(model);
  assertIdentical("/simple_update.owl", outputOntology);
}
 
Example #9
Source File: DiffOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Compare one ontology to a modified copy.
 *
 * @throws IOException on file problem
 * @throws OWLOntologyCreationException on ontology problem
 */
@Test
public void testCompareModified() throws IOException, OWLOntologyCreationException {
  OWLOntology simple = loadOntology("/simple.owl");
  Set<OWLOntology> onts = new HashSet<>();
  onts.add(simple);
  OWLOntologyManager manager = simple.getOWLOntologyManager();
  OWLDataFactory df = manager.getOWLDataFactory();
  OWLOntology simple1 = manager.createOntology(IRI.create(base + "simple1.owl"), onts);
  IRI test1 = IRI.create(base + "simple.owl#test1");
  manager.addAxiom(
      simple1,
      df.getOWLAnnotationAssertionAxiom(df.getRDFSLabel(), test1, df.getOWLLiteral("TEST #1")));

  StringWriter writer = new StringWriter();
  boolean actual = DiffOperation.compare(simple, simple1, writer);
  System.out.println(writer.toString());
  assertFalse(actual);
  String expected = IOUtils.toString(this.getClass().getResourceAsStream("/simple1.diff"));
  assertEquals(expected, writer.toString());
}
 
Example #10
Source File: OldSimpleOwlSim.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * generates view ontologies and pre-computes all LCSs.
 * These are added to the source ontology
 * 
 * @throws OWLOntologyCreationException
 * @throws OWLOntologyStorageException 
 * @throws FileNotFoundException 
 */

@Deprecated
public void generateGroupingClasses() throws OWLOntologyCreationException, FileNotFoundException, OWLOntologyStorageException {
	createElementAttributeMapFromOntology();
	removeUnreachableAxioms();

	generateSourcePropertyViews();
	generatePropertyViews();
	this.saveOntology(Stage.VIEW);

	makeAllByAllLowestCommonSubsumer();
	this.saveOntology(Stage.LCS);
	attributeElementCount = null;

	reason();
}
 
Example #11
Source File: QuerySubsetGenerator.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a new sub ontology from a given DL query and source ontology. The
 * subset will be created in the target ontology.
 * 
 * @param namedQuery
 * @param sourceGraph
 * @param targetGraph
 * @param reasonerFactory
 * @param toMerge 
 */
public void createSubOntologyFromDLQuery(OWLClass namedQuery,
		OWLGraphWrapper sourceGraph, OWLGraphWrapper targetGraph, 
		OWLReasonerFactory reasonerFactory, Set<OWLOntology> toMerge)
{
	try {
		Set<OWLClass> subset = DLQueryTool.executeQuery(namedQuery, sourceGraph.getSourceOntology(), reasonerFactory);
		if (subset.isEmpty()) {
			return;
		}
		createSubSet(targetGraph, subset, toMerge);
	} catch (OWLOntologyCreationException e) {
		LOG.error("Could not create ontology.", e);
		// TODO throw Exception?
		return;
	}
}
 
Example #12
Source File: MaterializeOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test reasoning with Expression Materializing Reasoner.
 *
 * <p>This test effectively relaxes an equivalence axiom
 *
 * @throws IOException on file problem
 * @throws OWLOntologyCreationException on ontology problem
 * @throws OntologyLogicException on logic problem
 */
@Test
public void testMaterializeGCIs()
    throws IOException, OWLOntologyCreationException, OntologyLogicException {
  OWLOntology reasoned = loadOntology("/gci_example.obo");
  OWLReasonerFactory coreReasonerFactory = new ElkReasonerFactory();
  Map<String, String> opts = ReasonOperation.getDefaultOptions();
  // opts.put("exclude-owl-thing", "true");
  MaterializeOperation.materialize(reasoned, coreReasonerFactory, null, opts);
  assertIdentical("/gci_example_materialized.obo", reasoned);
}
 
Example #13
Source File: Owl2VowlController.java    From OWL2VOWL with MIT License 5 votes vote down vote up
@RequestMapping(value = GIZMO_INPUT, method = RequestMethod.POST)
public String uploadOntology(@RequestParam("ontology") MultipartFile[] files) throws IOException,
		OWLOntologyCreationException {
	if (files == null || files.length == 0) {
		loadingStatusMsg+="* <span style='color:red;'>No file uploaded!</span>";
		throw new IllegalArgumentException("No file uploaded!");
	}

	if (files.length > 1) {
		loadingStatusMsg+="* <span style='color:red;'>Please upload only the main ontology!</span>";
		throw new IllegalArgumentException("Please upload only the main ontology!");
	}

	List<InputStream> inputStreams = new ArrayList<>();

	for (MultipartFile file : files) {
		inputStreams.add(file.getInputStream());
	}

	String jsonAsString;

	try {
		Owl2Vowl owl2Vowl = new Owl2Vowl(inputStreams.get(0));
		//conversionSessionMap.put(sessionId, owl2Vowl);
		jsonAsString = owl2Vowl.getJsonAsString();
	} catch (Exception e) {
		conversionLogger.info("Uploaded files " + files[0].getName() + ": " + 0);
		throw e;
	}
	finally {
		//evaluateLifeCycleOfConversionObject(sessionId,5000);
	}
	return jsonAsString;
}
 
Example #14
Source File: AbstractConverter.java    From OWL2VOWL with MIT License 5 votes vote down vote up
private void preLoadOntology() {
	try {
		loadOntology();
	} catch (OWLOntologyCreationException e) {
		throw new RuntimeException(e);
	}

	initialized = true;
}
 
Example #15
Source File: RepairOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test repair an ontology
 *
 * @throws IOException on file problem
 * @throws OWLOntologyCreationException on ontology problem
 */
@Test
public void testRepair() throws IOException, OWLOntologyCreationException {
  OWLOntology ontology = loadOntology("/need-of-repair.owl");
  IOHelper iohelper = new IOHelper();
  RepairOperation.repair(ontology, iohelper, true);
  iohelper.saveOntology(ontology, "target/foo.owl");
  assertIdentical("/repaired.owl", ontology);
}
 
Example #16
Source File: ProvenanceReasonerWrapper.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void reasonLeavingOneOut(OWLOntology leaveOutOntology) throws OWLOntologyCreationException {
	OWLOntologyManager m = getManager();
	OWLOntology ont2 = m.createOntology();
	
	LOG.info("LEAVE ONE OUT: "+leaveOutOntology);
	for (OWLOntology io : ontology.getImportsClosure()) {
		if (io.equals(leaveOutOntology)) {
			LOG.info("SKIPPING:"+io);
			continue;
		}
		m.addAxioms(ont2, io.getAxioms());
		
	}
	
	OWLReasoner reasoner = rf.createReasoner(ont2);
	for (OWLEdge e : edges) {
		if (!e.isJustified) {
			// there is no point checking unjustified edges;
			// these are edges that when removed cannot be re-inferred using the entire ontology set.
			// as reasoning is monotonic, removing imports cannot bring it back.
			continue;
		}
		//LOG.info("Testing "+e); 
		if (!isEdgeEntailed(e, ont2, reasoner)) {
			IRI req = leaveOutOntology.getOntologyID().getOntologyIRI().orNull();
			LOG.info(e + " requires "+req);
			e.requires.add(req);
			
		}
	}
	reasoner.dispose();
}
 
Example #17
Source File: PropertyExtractor.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 
 * @param newIRI
 * @return ontology
 * @throws OWLOntologyCreationException
 */
public OWLOntology extractPropertyOntology(IRI newIRI) throws OWLOntologyCreationException {
	Set<OWLProperty> props = new HashSet<OWLProperty>();
	for (OWLObjectProperty p : mainOntology.getObjectPropertiesInSignature(Imports.INCLUDED)) {
		LOG.info("mainOntology contains: "+p);
		props.add(p);
	}
	return extractPropertyOntology(newIRI, props);
}
 
Example #18
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 #19
Source File: SimSpeedTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@Ignore("This test requires an external resource. This can lead to false positive failures.")
public void testLCS() throws OWLOntologyCreationException, OBOFormatParserException, IOException {
	String idspace="mp";
	load(idspace);
	precompute(Method.BITMAP);
	OWLClass c1 = getCls("MP_0003737"); // ossification of pinnae
	OWLClass c2 = getCls("MP_0002895"); // abnormal otolithic membrane morphology
	Set<Node<OWLClass>> cs = this.getNamedCommonSubsumers(c1, c2);
	msg("CS="+cs);
	Set<Node<OWLClass>> lcs = this.getNamedLowestCommonSubsumers(c1, c2, Method.BITMAP);
	msg("LCS="+lcs);
}
 
Example #20
Source File: ReduceOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * If P is reflexive, and we have "A SubClassOf B" and "A SubClassOf P some B", then the second
 * becomes redundant.
 *
 * @throws IOException on file problem
 * @throws OWLOntologyCreationException if ontology cannot be created
 */
@Test
public void testReduceWithReflexivity() throws IOException, OWLOntologyCreationException {
  OWLOntology reasoned = loadOntology("/reduce_reflexivity_test.obo");
  OWLReasonerFactory reasonerFactory = new org.semanticweb.elk.owlapi.ElkReasonerFactory();

  Map<String, String> options = new HashMap<String, String>();
  options.put("remove-redundant-subclass-axioms", "true");

  ReduceOperation.reduce(reasoned, reasonerFactory, options);
  assertIdentical("/reduce_reflexivity_test_reduced.obo", reasoned);
}
 
Example #21
Source File: SavingInferredAxioms.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 inputOntologyManager = OWLManager.createOWLOntologyManager();
	OWLOntologyManager outputOntologyManager = OWLManager.createOWLOntologyManager();

	// Load your ontology.
	OWLOntology ont = inputOntologyManager.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);

	// To generate an inferred ontology we use implementations of
	// inferred axiom generators
	List<InferredAxiomGenerator<? extends OWLAxiom>> gens = new ArrayList<InferredAxiomGenerator<? extends OWLAxiom>>();
	gens.add(new InferredSubClassAxiomGenerator());
	gens.add(new InferredEquivalentClassAxiomGenerator());

	// Put the inferred axioms into a fresh empty ontology.
	OWLOntology infOnt = outputOntologyManager.createOntology();
	InferredOntologyGenerator iog = new InferredOntologyGenerator(reasoner,
			gens);
	iog.fillOntology(outputOntologyManager.getOWLDataFactory(), infOnt);

	// Save the inferred ontology.
	outputOntologyManager.saveOntology(infOnt,
			new FunctionalSyntaxDocumentFormat(),
			IRI.create((new File("path-to-output").toURI())));

	// Terminate the worker threads used by the reasoner.
	reasoner.dispose();
}
 
Example #22
Source File: MaterializeOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test reasoning with Expression Materializing Reasoner.
 *
 * @throws IOException on file problem
 * @throws OWLOntologyCreationException on ontology problem
 * @throws OntologyLogicException on logic problem
 */
@Test
public void testMaterialize()
    throws IOException, OWLOntologyCreationException, OntologyLogicException {
  OWLOntology reasoned = loadOntology("/relax_equivalence_axioms_test.obo");
  OWLReasonerFactory coreReasonerFactory = new ElkReasonerFactory();
  Map<String, String> opts = ReasonOperation.getDefaultOptions();
  // opts.put("exclude-owl-thing", "true");
  MaterializeOperation.materialize(reasoned, coreReasonerFactory, null, opts);
  assertIdentical("/relax_equivalence_axioms_expressions_materialized.obo", reasoned);
}
 
Example #23
Source File: GoMySQLDatabaseDumperTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDumpLarge() throws OWLOntologyCreationException, OBOFormatParserException, IOException, ReferentialIntegrityException, URISyntaxException {
	ParserWrapper pw = new ParserWrapper();
	g = pw.parseToOWLGraph(getResourceIRIString("mgi-go.obo"));
	g.addSupportOntology(pw.parseOBO(getResourceIRIString("taxon.obo")));
	GafObjectsBuilder b = new GafObjectsBuilder();
	GafDocument gafdoc = 
			b.buildDocument("src/test/resources/gene-associations/gene_association.mgi.gz");
	gafdocs.add( gafdoc );
	GoMySQLDatabaseDumper dumper = new GoMySQLDatabaseDumper(g);
	dumper.setGafdocs(gafdocs);
	dumper.setTargetDirectory("target/godb3");
	dumper.dump();
	
}
 
Example #24
Source File: BaseOWLAPILowLevelIncrementalClassTest.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
public void testReasoner() throws OWLOntologyCreationException {

		boolean bufferingMode = reasoner.getBufferingMode().equals(
				BufferingMode.BUFFERING);

		remove();
		if (bufferingMode) {
			// the changes are still not yet taken into account
			testPresent();
		} else {
			// the changes are taken into account
			testAbsent();
		}

		// this should take into account the changes for reasoning queries
		reasoner.flush();

		testAbsent();

		add();
		reasoner.flush();
		remove();

		if (bufferingMode) {
			// the reasoner should reflect only changes until the last flush()
			testPresent();
		} else {
			// the reasoner should reflect all changes
			testAbsent();
		}

		// take into account all changes
		reasoner.flush();

		testAbsent();

		// Terminate the reasoner.
		reasoner.dispose();

	}
 
Example #25
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 dlQuery
 * @param graph
 * @param reasonerFactory
 * @return set of {@link OWLClass} which 
 * @throws OWLParserException
 * @throws OWLOntologyCreationException
 */
public static Set<OWLClass> executeDLQuery(String dlQuery, OWLGraphWrapper graph, 
		OWLReasonerFactory reasonerFactory) throws OWLParserException, OWLOntologyCreationException 
{
	// create parser and parse DL query string
	ManchesterSyntaxTool parser = null;
	
	OWLClassExpression ce;
	try {
		parser = new ManchesterSyntaxTool(graph.getSourceOntology(), graph.getSupportOntologySet());
		ce = parser.parseManchesterExpression(dlQuery);
	} finally {
		// always dispose parser to avoid a memory leak
		if (parser != null) {
			parser.dispose();
		}
	}
	
	// create query ontology
	OWLOntologyManager m = OWLManager.createOWLOntologyManager();
	OWLOntology queryOntology = m.createOntology(IRI.generateDocumentIRI(), graph.getAllOntologies());
	OWLDataFactory f = m.getOWLDataFactory();
	OWLClass qc = f.getOWLClass(IRI.create("http://owltools.org/Q"));
	OWLEquivalentClassesAxiom ax = f.getOWLEquivalentClassesAxiom(ce, qc);
	m.addAxiom(queryOntology, ax);
	
	Set<OWLClass> subset = executeQuery(ce, queryOntology, reasonerFactory);
	if(subset.isEmpty()) {
		LOG.warn("No classes found for query subclass of:"+dlQuery);
	}
	return subset;
}
 
Example #26
Source File: OboOntologyReleaseRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void saveInAllFormats(String ontologyId, String ext, String version, OWLOntology ontologyToSave, OWLOntology gciOntology) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException {
	if (ext == null || ext.isEmpty()) {
		saveOntologyInAllFormats(ontologyId, ontologyId, version, ontologyToSave, gciOntology, false);
	}
	else {
		saveOntologyInAllFormats(ontologyId, ontologyId + "-" + ext, version, ontologyToSave, gciOntology, true);
	}
}
 
Example #27
Source File: OWLRenderer.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private OWLOntology getOntology() {
	if (ontology == null) {
		try {
			ontology = getOWLOntologyManager().createOntology();
		} catch (OWLOntologyCreationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	return ontology;
}
 
Example #28
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 #29
Source File: OWLGraphWrapperEdgesExtendedTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test {@link OWLGraphWrapperEdgesExtended#getIncomingEdgesWithGCI(OWLObject)}
 */
@Test
public void shouldGetIncomingEdgesWithGCI() throws OWLOntologyCreationException, 
OBOFormatParserException, IOException {
    ParserWrapper parserWrapper = new ParserWrapper();
    OWLOntology ont = parserWrapper.parse(this.getClass().getResource(
            "/graph/gciRelRetrieval.obo").getFile());
    OWLGraphWrapper wrapper = new OWLGraphWrapper(ont);
    
    OWLObjectProperty partOf = wrapper.getOWLObjectPropertyByIdentifier("BFO:0000050");
    OWLObjectProperty developsFrom = wrapper.getOWLObjectPropertyByIdentifier("RO:0002202");
    OWLClass cls8 = wrapper.getOWLClassByIdentifier("ID:8");
    OWLClass cls4 = wrapper.getOWLClassByIdentifier("ID:4");
    OWLClass cls10 = wrapper.getOWLClassByIdentifier("ID:10");
    OWLClass cls6 = wrapper.getOWLClassByIdentifier("ID:6");
    OWLClass taxon1 = wrapper.getOWLClassByIdentifier("NCBITaxon:10090");
    
    Set<OWLGraphEdge> expectedEdges = new HashSet<OWLGraphEdge>();
    //class with no incoming GCI relations
    expectedEdges.add(new OWLGraphEdge(cls6, cls4, partOf, Quantifier.SOME, 
            ont, null));
    assertEquals("Incorrect incoming edges with GCI retrieved", expectedEdges, 
            wrapper.getIncomingEdgesWithGCI(cls4));
    //class with both a classical relation and a GCI relation incoming
    expectedEdges = new HashSet<OWLGraphEdge>();
    expectedEdges.add(new OWLGraphEdge(cls8, cls6, partOf, Quantifier.SOME, 
            ont, null));
    expectedEdges.add(new OWLGraphEdge(cls10, cls6, developsFrom, Quantifier.SOME, 
            ont, null, taxon1, partOf));
    assertEquals("Incorrect incoming edges with GCI retrieved", expectedEdges, 
            wrapper.getIncomingEdgesWithGCI(cls6));
}
 
Example #30
Source File: OWLGraphWrapperBasic.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void mergeSupportOntology(IRI ontologyIRI, boolean isRemoveFromSupportList) throws OWLOntologyCreationException {
	OWLOntology extOnt = null;
	for (OWLOntology ont : this.supportOntologySet) {
		Optional<IRI> supportIRI = ont.getOntologyID().getOntologyIRI();
		if (supportIRI.isPresent() && supportIRI.get().equals(ontologyIRI)) {
			extOnt = ont;
			break;
		}
	}

	mergeOntology(extOnt);
	if (isRemoveFromSupportList) {
		this.supportOntologySet.remove(extOnt);
	}
}