org.semanticweb.owlapi.model.OWLOntologyManager Java Examples

The following examples show how to use org.semanticweb.owlapi.model.OWLOntologyManager. 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: OwlApiUtils.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/***
 * @param manager The ontology manager to use
 * @param ontology A string representing the ontology to load. This can be an URI or a file path
 * @return The loaded ontology
 * @throws OWLOntologyCreationException
 */
public static OWLOntology loadOntology(OWLOntologyManager manager, String ontology) throws OWLOntologyCreationException {
  logger.info(String.format("Loading ontology with owlapi: %s", ontology));
  String origThreadName = Thread.currentThread().getName();
  Thread.currentThread().setName("read - " + ontology);
  OWLOntology ont;

  if (validator.isValid(ontology)) {
    ont = manager.loadOntology(IRI.create(ontology));
  } else if (new File(ontology).exists()){
    ont = manager.loadOntologyFromOntologyDocument(new File(ontology));
  } else {
    try {
      ont = manager.loadOntologyFromOntologyDocument(Resources.getResource(ontology).openStream());
    } catch (Exception e) {
      throw new OWLOntologyCreationException("Failed to find ontology: " + ontology);
    }
  }
  logger.info(String.format("Finished loading ontology with owlapi: %s", ontology));
  Thread.currentThread().setName(origThreadName);
  return ont;
}
 
Example #2
Source File: OwlInternalProofTest.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
	Assume.assumeFalse(TestUtils.ignore(manifest_.getInput(),
			ElkTestUtils.TEST_INPUT_LOCATION, IGNORE_LIST));

	final InputStream input = manifest_.getInput().getUrl().openStream();
	OWLOntologyManager manager = TestOWLManager.createOWLOntologyManager();
	OWLOntology ontology = manager.loadOntologyFromOntologyDocument(input);

	this.prover_ = OWLAPITestUtils.createProver(ontology);

	this.query_ = manifest_.getInput().getQuery();

	this.adapter_ = new OwlInternalProof(
			prover_.getDelegate().getInternalReasoner(), query_);
}
 
Example #3
Source File: OboOntologyReleaseRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String handleVersion(String ontologyId) {
	// TODO add an option to set/overwrite the version manually via command-line
	// TODO re-use/create a method in obo2owl for creating an version IRI
	String version;
	OWLOntology ontology = mooncat.getOntology();
	OWLOntologyID owlOntologyId = ontology.getOntologyID();
	Optional<IRI> versionIRI = owlOntologyId.getVersionIRI();
	if (versionIRI.isPresent() == false) {
		// set a new version IRI using the current date
		version = OntologyVersionTools.format(new Date());
		versionIRI = Optional.of(IRI.create(Obo2OWLConstants.DEFAULT_IRI_PREFIX+ontologyId+"/"+oortConfig.getVersionSubdirectory()+"/"+version+"/"+ontologyId+".owl"));
		
		OWLOntologyManager m = mooncat.getManager();
		m.applyChange(new SetOntologyID(ontology, new OWLOntologyID(owlOntologyId.getOntologyIRI(), versionIRI)));
	}
	else {
		String versionIRIString = versionIRI.get().toString();
		version = OntologyVersionTools.parseVersion(versionIRIString);
		if (version == null) {
			// use the whole IRI? escape?
			logError("Could not parse a version from ontolgy version IRI: "+versionIRIString);
			version = versionIRIString;
		}
	}
	return version;
}
 
Example #4
Source File: Rules.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of rules extracted from the given OWL-2 ontology document.
 * @param in an ontology document as stream
 * @return a list of rules
 */
public static List<Rule> fromOntology(InputStream in) {
	try {
		// use OWL-API to get a OWLOntology document from source
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		manager.loadOntologyFromOntologyDocument(in);
		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 #5
Source File: AssertInferenceTool.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static List<OWLOntologyChange> handleSupportOntologies(OWLGraphWrapper graph)
{
	OWLOntology ontology = graph.getSourceOntology();
	OWLOntologyManager manager = ontology.getOWLOntologyManager();
	OWLDataFactory factory = manager.getOWLDataFactory();
	
	List<OWLOntologyChange> removeImportChanges = new ArrayList<OWLOntologyChange>();
	Set<OWLOntology> supportOntologySet = graph.getSupportOntologySet();
	for (OWLOntology support : supportOntologySet) {
		Optional<IRI> supportIRI = support.getOntologyID().getOntologyIRI();
		if(supportIRI.isPresent()) {
			IRI ontologyIRI = supportIRI.get();
			OWLImportsDeclaration importDeclaration = factory.getOWLImportsDeclaration(ontologyIRI);
			ChangeApplied status = manager.applyChange(new AddImport(ontology, importDeclaration));
			if (ChangeApplied.SUCCESSFULLY == status) {
				// the change was successful, create remove import for later
				removeImportChanges.add(new RemoveImport(ontology, importDeclaration));
			}
		}
	}
	return removeImportChanges;
}
 
Example #6
Source File: OwlOntologyProducer.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
void addOntologyStructure(OWLOntologyManager manager, OWLOntology ontology) {
  long parent = graph.createNode(OwlApiUtils.getIri(ontology));
  graph.addLabel(parent, OwlLabels.OWL_ONTOLOGY);
  for (OWLImportsDeclaration importDeclaration : ontology.getImportsDeclarations()) {
    OWLOntology childOnt = manager.getImportedOntology(importDeclaration);
    if (null == childOnt) {
      // TODO: Why is childOnt sometimes null (when importing rdf)?
      continue;
    }
    long child = graph.createNode(OwlApiUtils.getIri(childOnt));
    graph.addLabel(parent, OwlLabels.OWL_ONTOLOGY);
    if (graph.getRelationship(child, parent, OwlRelationships.RDFS_IS_DEFINED_BY).isPresent()) {
      continue;
    }
    graph.createRelationship(child, parent, OwlRelationships.RDFS_IS_DEFINED_BY);
    addOntologyStructure(manager, childOnt);
  }
}
 
Example #7
Source File: GMTParser.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void parseRow(String[] row) {
	OWLDataFactory df = graph.getDataFactory();
	OWLOntologyManager mgr = graph.getManager();
	String geneSetId = row[0];
	IRI geneSetIRI = IRI.create(prefix + geneSetId);
	String desc = row[1];
	OWLClass geneSetCls = df.getOWLClass(geneSetIRI);
	OWLAxiom ax = df.getOWLAnnotationAssertionAxiom(df.getRDFSLabel(),geneSetIRI, literal(desc));
	mgr.addAxiom(graph.getSourceOntology(), ax);
			
	// assume each value is an entity, e.g. gene
	for (int i=2; i < row.length; i++) {
		OWLNamedIndividual individual = df.getOWLNamedIndividual(IRI.create(prefix + row[i]));
		mgr.addAxiom(graph.getSourceOntology(), df.getOWLClassAssertionAxiom(geneSetCls, individual));
	}
}
 
Example #8
Source File: ProvenanceReasonerWrapper.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public boolean isEdgeEntailed(OWLEdge e, OWLOntology currentOntology, OWLReasoner reasoner) {
	OWLOntologyManager m = getManager();

	Set<OWLSubClassOfAxiom> scas = currentOntology.getSubClassAxiomsForSubClass(e.c);
	Set<OWLSubClassOfAxiom> rmAxioms = new HashSet<OWLSubClassOfAxiom>();
	for (OWLSubClassOfAxiom sca : scas) {
		if (sca.getSuperClass().equals(e.p)) {
			LOG.info("REMOVING: "+sca);
			rmAxioms.add(sca);
		}
	}
	boolean isEdgeAsserted = rmAxioms.size() > 0;
	if (isEdgeAsserted) {
		m.removeAxioms(currentOntology, rmAxioms);
		reasoner.flush();
	}
	boolean isEntailed;
	isEntailed = reasoner.getSuperClasses(e.c, false).containsEntity(e.p);
	if (isEdgeAsserted) {
		m.addAxioms(currentOntology, rmAxioms);
		reasoner.flush();
	}

	return isEntailed;
}
 
Example #9
Source File: AbstractOwlSim.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public OWLOntology cacheInformationContentInOntology() throws OWLOntologyCreationException, UnknownOWLClassException {
	OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager();
	OWLDataFactory df = mgr.getOWLDataFactory();
	OWLOntology o = mgr.createOntology();
	OWLAnnotationProperty p = df.getOWLAnnotationProperty(IRI.create(icIRIString));
	for (OWLClass c : getSourceOntology().getClassesInSignature()) {
		Double ic = getInformationContentForAttribute(c);
		if (ic != null) {
			mgr.addAxiom(o,
					df.getOWLAnnotationAssertionAxiom(p, 
							c.getIRI(), 
							df.getOWLLiteral(ic)));
		}

	}
	return o;
}
 
Example #10
Source File: OWLGraphWrapperBasic.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void mergeImportClosure(boolean isRemovedImportsDeclarations) throws OWLOntologyCreationException {
	OWLOntologyManager manager = getManager();
	Set<OWLOntology> imports = sourceOntology.getImportsClosure();
	for (OWLOntology o : imports) {
		if (o.equals(sourceOntology))
			continue;

		String comment = "Includes "+summarizeOntology(o);
		LOG.info(comment);
		addCommentToOntology(sourceOntology, comment);

		manager.addAxioms(sourceOntology, o.getAxioms());
	}
	Set<OWLImportsDeclaration> oids = sourceOntology.getImportsDeclarations();
	for (OWLImportsDeclaration oid : oids) {
		RemoveImport ri = new RemoveImport(sourceOntology, oid);
		getManager().applyChange(ri);
	}
}
 
Example #11
Source File: OwlApiIncrementalReasoningTestDelegate.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
@Override
public void applyChanges(final Iterable<OWLAxiom> changes,
		final IncrementalChangeType type) {
	// the changes are applied indirectly by modifying the ontology
	final OWLOntologyManager manager = testOntology_
			.getOWLOntologyManager();

	for (OWLAxiom axiom : changes) {
		switch (type) {
		case ADD:
			manager.addAxiom(testOntology_, axiom);
			break;
		case DELETE:
			manager.removeAxiom(testOntology_, axiom);
			break;
		}
	}

	standardReasoner_.flush();
	incrementalReasoner_.flush();
}
 
Example #12
Source File: ExplainOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Render an Explanation object as Markdown text, linking text labels to term IRIs and indenting
 * axioms.
 *
 * @param explanation explanation to render
 * @param manager OWLOntologyManager containing source ontologies for explanation axioms
 * @return Markdown-formatted explanation text
 */
public static String renderExplanationAsMarkdown(
    Explanation<OWLAxiom> explanation, OWLOntologyManager manager) {
  ExplanationOrderer orderer = new ProtegeExplanationOrderer(manager);
  ExplanationTree tree =
      orderer.getOrderedExplanation(explanation.getEntailment(), explanation.getAxioms());
  ShortFormProvider labelProvider =
      new AnnotationValueShortFormProvider(
          Collections.singletonList(OWLManager.getOWLDataFactory().getRDFSLabel()),
          Collections.emptyMap(),
          manager);
  ShortFormProvider linkProvider = new MarkdownLinkShortFormProvider(labelProvider);
  ManchesterOWLSyntaxOWLObjectRendererImpl axiomRenderer =
      new ManchesterOWLSyntaxOWLObjectRendererImpl();
  axiomRenderer.setShortFormProvider(linkProvider);
  return renderTree(tree, axiomRenderer);
}
 
Example #13
Source File: OboOntologyReleaseRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void createModule(String ontologyId, String moduleName, Set<OWLEntity> signature)
		throws OWLOntologyCreationException, IOException, OWLOntologyStorageException 
{
	// create a new manager, avoid unnecessary change events
	final OWLOntologyManager m = OWLManager.createOWLOntologyManager();
	
	// extract module
	SyntacticLocalityModuleExtractor sme = new SyntacticLocalityModuleExtractor(m, mooncat.getOntology(), ModuleType.BOT);
	Set<OWLAxiom> moduleAxioms = sme.extract(signature);
	
	OWLOntology module = m.createOntology(IRI.generateDocumentIRI());
	m.addAxioms(module, moduleAxioms);
	
	// save module
	OutputStream moduleOutputStream = null;
	try {
		moduleOutputStream = getOutputSteam(getModuleFileName(ontologyId, moduleName));
		m.saveOntology(module, moduleOutputStream);
	}
	finally {
		IOUtils.closeQuietly(moduleOutputStream);
	}
}
 
Example #14
Source File: ProofTest.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyDisjointUnion() throws Exception {
	OWLOntologyManager owlManager = OWLManager
			.createConcurrentOWLOntologyManager();
	// creating an ontology
	final OWLOntology ontology = owlManager.createOntology();
	OWLClass a = factory.getOWLClass(IRI.create("http://example.org/A"));
	OWLClass b = factory.getOWLClass(IRI.create("http://example.org/B"));
	// DisjointUnion(A ) = EquivalentClasses(A owl:Nothing)
	owlManager.addAxiom(ontology, factory.getOWLDisjointUnionAxiom(a,
			Collections.<OWLClassExpression> emptySet()));
	owlManager.addAxiom(ontology, factory.getOWLSubClassOfAxiom(b, b));

	final OWLProver prover = OWLAPITestUtils.createProver(ontology);

	prover.precomputeInferences(InferenceType.CLASS_HIERARCHY);

	ProofTestUtils.provabilityTest(prover,
			factory.getOWLSubClassOfAxiom(a, b));
}
 
Example #15
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new SimpleOntology object using the provided OWLOntology and OWLOntologyManager. If the provided
 * OWLOntologyManager does not contain the provided OWLOntology, the provided OWLOntology is copied into the
 * OWLOntologyManager. Otherwise, the provided OWLOntology is used.
 */
protected SimpleOntology(OWLOntology ontology, OWLOntologyManager owlManager, Resource resource,
                         OntologyManager ontologyManager, SesameTransformer transformer,
                         BNodeService bNodeService, RepositoryManager repoManager, ForkJoinPool threadPool) {
    this.ontologyManager = ontologyManager;
    this.transformer = transformer;
    this.bNodeService = bNodeService;
    this.owlManager = owlManager;
    this.repoManager = repoManager;

    try {
        if (!owlManager.contains(ontology)) {
            owlOntology = owlManager.copyOntology(ontology, OntologyCopy.DEEP);
        } else {
            owlOntology = ontology;
        }
    } catch (OWLOntologyCreationException e) {
        throw new MobiOntologyException("Error in ontology creation", e);
    }

    createOntologyId(resource);
    owlReasoner = owlReasonerFactory.createReasoner(owlOntology);
}
 
Example #16
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 #17
Source File: IgnoreChangesInNonImportedOntologiesTest.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
/**
 * Testing correctness of the reasoner with respect to ontology changes
 */
@Test
public void ignoreChangesInNonImportedOntologies() throws Exception {

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

	// set up resolution of prefixes
	DefaultPrefixManager 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#");

	OWLClass extA = dataFactory.getOWLClass("A:A", pm);
	OWLClass extB = dataFactory.getOWLClass("B:B", pm);

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

	// Create an ELK reasoner.
	ElkReasoner reasoner = (ElkReasoner) new ElkReasonerFactory()
			.createReasoner(root);
	// make sure the reasoner loads the ontology
	reasoner.flush();
	reasoner.isConsistent();

	try {
		OWLOntology nonImported = loadOntology(man, "nonImported.owl");

		OWLAxiom axiom = dataFactory.getOWLSubClassOfAxiom(extA, extB);
		man.removeAxiom(nonImported, axiom);
		reasoner.flush();

		AbstractReasonerState state = reasoner.getInternalReasoner();

		assertTrue(state.stageManager.inputLoadingStage.isCompleted());
	} finally {
		reasoner.dispose();
	}
}
 
Example #18
Source File: PropertyViewOntologyBuilder.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param owlDataFactory
 * @param owlOntologyManager
 * @param sourceOntology
 * @param unitsOntology
 * @param viewProperty
 */
public PropertyViewOntologyBuilder(OWLDataFactory owlDataFactory,
		OWLOntologyManager owlOntologyManager, OWLOntology sourceOntology,
		OWLOntology unitsOntology, OWLObjectProperty viewProperty) {
	super();
	this.owlDataFactory = owlDataFactory;
	this.owlOntologyManager = owlOntologyManager;
	this.sourceOntology = sourceOntology;
	this.elementsOntology = unitsOntology;
	this.viewProperty = viewProperty;
	init();
}
 
Example #19
Source File: BridgeExtractor.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addObjectProperty(OWLObjectProperty p, OWLOntology xOnt) {
	if (xOnt.getDeclarationAxioms(p).size() > 0) {
		return;
	}
	OWLOntologyManager m = ontology.getOWLOntologyManager();
	OWLDataFactory df = m.getOWLDataFactory();
	m.addAxiom(xOnt, df.getOWLDeclarationAxiom(p));
	for (OWLAxiom ax : ontology.getAxioms(p, Imports.EXCLUDED)) {
		m.addAxiom(xOnt, ax);
	}
	// TODO

}
 
Example #20
Source File: Mooncat.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * For every pair X DisjointWith Y, generate an axiom
 * A and Y = Nothing
 * 
 * (may become deprecated after Elk supports disjoints)
 * 
 * @param ont
 * @param manager
 * @param dataFactory
 */
public static void translateDisjointsToEquivalents(OWLOntology ont, OWLOntologyManager manager, OWLDataFactory dataFactory) {
	for (OWLDisjointClassesAxiom dca : ont.getAxioms(AxiomType.DISJOINT_CLASSES, Imports.INCLUDED)) {
		for (OWLClassExpression ce1 : dca.getClassExpressions()) {
			for (OWLClassExpression ce2 : dca.getClassExpressions()) {
				if (ce1.compareTo(ce2) <= 0)
					continue;
				OWLEquivalentClassesAxiom eca = dataFactory.getOWLEquivalentClassesAxiom(dataFactory.getOWLNothing(),
						dataFactory.getOWLObjectIntersectionOf(ce1, ce2));
				manager.addAxiom(ont, eca);
				// TODO - remove if requested
			}
		}
	}
}
 
Example #21
Source File: OWLConverter.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convenience method for asserting a subAnnotationProperty relation 
 * between a parent and child property in an ontology.
 *
 * @param ontology the current ontology
 * @param child the child property
 * @param parent the parent property
 * @return the axiom
 */
protected static OWLSubAnnotationPropertyOfAxiom
		assertSubAnnotationProperty(
		OWLOntology ontology, OWLAnnotationProperty child,
		OWLAnnotationProperty parent) {
	OWLOntologyManager manager = ontology.getOWLOntologyManager();
	OWLDataFactory dataFactory = manager.getOWLDataFactory();
	OWLSubAnnotationPropertyOfAxiom axiom = 
		dataFactory.getOWLSubAnnotationPropertyOfAxiom(
			child, parent);
	manager.addAxiom(ontology, axiom);
	return axiom;
}
 
Example #22
Source File: AbstractConverter.java    From OWL2VOWL with MIT License 5 votes vote down vote up
private void parsing(OWLOntology ontology, VowlData vowlData, OWLOntologyManager manager) {
	processAnnotationProperties(ontology, vowlData);
	processClasses(ontology, vowlData);
	processObjectProperties(ontology, vowlData);
	processDataProperties(ontology, vowlData);
	processIndividuals(ontology, vowlData, manager);

	processGenericAxioms();
}
 
Example #23
Source File: GetOntologyId.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private OWLOntology getOntology() throws Exception{
	if(ontologyLocation.endsWith(".owl")){
		//oborelease.isObo2Owl			
		addProperty("oborelease.isowl", "true");
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		return manager.loadOntologyFromOntologyDocument(new File(ontologyLocation));
	}

	addProperty("oborelease.isobo", "true");
	
	Obo2Owl obo2owl = new Obo2Owl();
	
	return obo2owl.convert(ontologyLocation);
}
 
Example #24
Source File: InverseOfTautologyTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {

  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  String uri =
      Resources.getResource("ontologies/cases/TestInverseOfTautology.owl").toURI().toString();
  IRI iri = IRI.create(uri);
  manager.loadOntologyFromOntologyDocument(iri);
  OWLOntologyWalker walker = new OWLOntologyWalker(manager.getOntologies());

  MappedProperty mappedProperty = new MappedProperty(NodeProperties.LABEL);
  List<String> properties = new ArrayList<String>();
  properties.add("http://www.w3.org/2000/01/rdf-schema#label");
  properties.add("http://www.w3.org/2004/02/skos/core#prefLabel");
  mappedProperty.setProperties(properties);

  ArrayList<MappedProperty> mappedPropertyList = new ArrayList<MappedProperty>();
  mappedPropertyList.add(mappedProperty);

  GraphOwlVisitor visitor = new GraphOwlVisitor(walker, graph, mappedPropertyList);
  walker.walkStructure(visitor);
  Map<String, String> categories = new HashMap<>();
  try (Transaction tx = graphDb.beginTx()) {
    OwlPostprocessor postprocessor = new OwlPostprocessor(graphDb, categories);
    postprocessor.processCategories(categories);
    postprocessor.processSomeValuesFrom();
    tx.success();
  }
}
 
Example #25
Source File: OWLAPIIncrementalClassificationMultiDeltas.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
private OWLOntology loadFromDisk(String suffix) throws OWLOntologyCreationException {
	OWLOntologyManager changeManager = OWLManager.createOWLOntologyManager();
	
	for (File delta : deltaDir_.listFiles()) {
		if (delta.getName().endsWith(suffix)) {
			return changeManager.loadOntologyFromOntologyDocument(delta);
		}
	}
	
	return null;
}
 
Example #26
Source File: CliqueOntologyTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  CliqueConfiguration cliqueConfiguration = new CliqueConfiguration();
  Set<String> rel = new HashSet<String>();
  rel.add(OwlRelationships.OWL_EQUIVALENT_CLASS.name());
  cliqueConfiguration.setRelationships(rel);
  cliqueConfiguration.setLeaderAnnotation("http://www.monarchinitiative.org/MONARCH_cliqueLeader");
  clique = new Clique(graphDb, cliqueConfiguration);

  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  String uri = Resources.getResource("ontologies/equivalence-cliques-test.owl").toURI().toString();
  IRI iri = IRI.create(uri);
  manager.loadOntologyFromOntologyDocument(iri);
  OWLOntologyWalker walker = new OWLOntologyWalker(manager.getOntologies());

  MappedProperty mappedProperty = new MappedProperty(NodeProperties.LABEL);
  List<String> properties = new ArrayList<String>();
  properties.add("http://www.w3.org/2000/01/rdf-schema#label");
  properties.add("http://www.w3.org/2004/02/skos/core#prefLabel");
  mappedProperty.setProperties(properties);

  ArrayList<MappedProperty> mappedPropertyList = new ArrayList<MappedProperty>();
  mappedPropertyList.add(mappedProperty);

  GraphOwlVisitor visitor = new GraphOwlVisitor(walker, graph, mappedPropertyList);
  walker.walkStructure(visitor);
  Map<String, String> categories = new HashMap<>();
  try (Transaction tx = graphDb.beginTx()) {
    OwlPostprocessor postprocessor = new OwlPostprocessor(graphDb, categories);
    postprocessor.processCategories(categories);
    postprocessor.processSomeValuesFrom();
    tx.success();
  }
}
 
Example #27
Source File: OWLConverter.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convenience method for adding an annotation assertion to the
 * ontology itself, taking a CURIE for the property and an Boolean literal.
 *
 * @param ontology the current ontology
 * @param propertyCURIE will be expanded to the full annotation
 *	property IRI
 * @param value the literal value of the annotation
 * @return the annotation axiom
 */
protected static OWLAnnotation annotate(OWLOntology ontology,
		String propertyCURIE, IRI value) {
	OWLOntologyManager manager = ontology.getOWLOntologyManager();
	OWLDataFactory dataFactory = manager.getOWLDataFactory();
	IRI iri = format.getIRI(propertyCURIE);
	OWLAnnotationProperty property =
		dataFactory.getOWLAnnotationProperty(iri);
	OWLAnnotation annotation = dataFactory.getOWLAnnotation(
			property, value);
	manager.applyChange(
		new AddOntologyAnnotation(ontology, annotation));
	return annotation;
}
 
Example #28
Source File: ChEBIParser.java    From act with GNU General Public License v3.0 5 votes vote down vote up
private static void find(String subtreeRoot, IRI documentIRI, IRI inchiIRI) throws OWLException, IOException {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  // Load the ontology...
  OWLOntology ontology = manager.loadOntologyFromOntologyDocument(documentIRI);
  // Print metadata about ontology...
  System.err.println("Ontology Loaded...");
  System.err.println("Document IRI: " + documentIRI);
  System.err.println("Ontology    : " + ontology.getOntologyID());
  System.err.println("Format      : " + manager.getOntologyFormat(ontology));

  HashMap<String, String> inchis = readInchis(inchiIRI);

  ChEBIParser chebi = new ChEBIParser(ontology);

  OWLClass clazz = manager.getOWLDataFactory().getOWLThing();
  System.err.println("Toplevel    : " + clazz);
  clazz = chebi.recurseToSubtreeRoot(clazz, subtreeRoot);
  System.err.println("Requested   : " + clazz);
  // Print the hierarchy
  HashMap<OWLClass, OWLClass> treeParents = new HashMap<OWLClass, OWLClass>();
  boolean doPrintSubtree = true;
  chebi.readSubtree(clazz, treeParents, doPrintSubtree);

  Set<OWLClass> metabolite_categories = treeParents.keySet();
  // System.err.println("Metabolite categories: " + metabolite_categories);

  // The function getAllElementsWithParentsIn picks out elements from the ontology that
  // have a "has_role" relationship with any member of metabolite_categories.
  // E.g., chemA has_role eukaryotic_metabolite; chemB has_role metabolite
  //      then { chemA -> eukaryotic_metabolite, chemB -> metabolite } will be in the
  //      returned map.
  // The fn also gathers data for each of the elems
  // e.g., { Sy->Synonyms, X->xref, S->SMILES, I -> InChI, Ik -> InChIKey }
  HashMap<OWLClass, P<OWLClass, HashMap<String, EntryTypes>>> elems;
  elems = chebi.getAllElementsWithParentsIn(metabolite_categories);
  for (OWLClass e : elems.keySet())
    output(e, elems.get(e), inchis, ontology);
}
 
Example #29
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 #30
Source File: Mooncat.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Mooncat(OWLOntologyManager manager, OWLDataFactory dataFactory,
		OWLOntology ontology) {
	super();
	this.manager = manager;
	this.dataFactory = dataFactory;
	//this.ontology = ontology;
}