Java Code Examples for org.semanticweb.owlapi.apibinding.OWLManager#createOWLOntologyManager()

The following examples show how to use org.semanticweb.owlapi.apibinding.OWLManager#createOWLOntologyManager() . 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: OwlSimUtil.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void addElementLabels(OWLOntology ont, File file) throws IOException {
	OWLOntologyManager m = OWLManager.createOWLOntologyManager();
	OWLDataFactory df = m.getOWLDataFactory();
	List<String> lines = FileUtils.readLines(file);
	for (String line : lines) {
		if (line.startsWith("#"))
			continue;
		String[] colVals = line.split("\t");
		if (colVals.length != 2) {
			throw new IOException("Incorrect number of value: "+line);
		}
		IRI i = getIRIById(colVals[0]);
		OWLAnnotation ann = df.getOWLAnnotation(df.getRDFSLabel(), df.getOWLLiteral(colVals[1])); 
		m.addAxiom(ont, df.getOWLAnnotationAssertionAxiom(i, ann));
	}
}
 
Example 2
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 3
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 4
Source File: OwlSimUtil.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void addElementToAttributeAssociationsFromFile(OWLOntology ont, File file) throws IOException {
	OWLOntologyManager m = OWLManager.createOWLOntologyManager();
	OWLDataFactory df = m.getOWLDataFactory();
	List<String> lines = FileUtils.readLines(file);
	for (String line : lines) {
		if (line.startsWith("#"))
			continue;
		String[] colVals = line.split("\t");
		if (colVals.length != 2) {
			throw new IOException("Incorrect number of value: "+line);
		}
		OWLNamedIndividual i = df.getOWLNamedIndividual(getIRIById(colVals[0]));
		OWLClass c = df.getOWLClass(getIRIById(colVals[1]));
		m.addAxiom(ont, df.getOWLClassAssertionAxiom(c, i));
	}
}
 
Example 5
Source File: OwlSimUtil.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param file
 * @return
 * @throws OWLOntologyCreationException
 * @throws IOException 
 * @throws OBOFormatParserException 
 */
public static OwlSim createOwlSimFromOntologyFile(File file) throws OWLOntologyCreationException, OBOFormatParserException, IOException {
	OWLOntologyManager m = OWLManager.createOWLOntologyManager();
	OWLOntology ont;
	if (file.getPath().endsWith(".obo")) {
		OBOFormatParser p = new OBOFormatParser();
		OBODoc obodoc = p.parse(file);
		Obo2Owl bridge = new Obo2Owl(m);
		ont = bridge.convert(obodoc);
	}
	else {
		ont = m.loadOntology(IRI.create(file));
	}
	
	return new FastOwlSimFactory().createOwlSim(ont);
}
 
Example 6
Source File: OwlTestCase.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Before
public void loadOwl() throws Exception {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  String uri = Resources.getResource("ontologies/cases/" + getTestName() + ".owl").toURI()
      .toString();
  IRI iri = IRI.create(uri);
  OWLOntology ont = manager.loadOntologyFromOntologyDocument(iri);
  if (performInference) {
    ReasonerConfiguration config = new ReasonerConfiguration();
    config.setFactory(ElkReasonerFactory.class.getCanonicalName());
    config.setAddDirectInferredEdges(true);
    ReasonerUtil util = new ReasonerUtil(config, manager, ont);
    util.reason();
  }
  OWLOntologyWalker walker = new OWLOntologyWalker(manager.getOntologies());

  GraphOwlVisitor visitor = new GraphOwlVisitor(walker, graph, new ArrayList<MappedProperty>());
  walker.walkStructure(visitor);

  OwlPostprocessor postprocessor = new OwlPostprocessor(graphDb, Collections.<String, String>emptyMap());
  postprocessor.processSomeValuesFrom();

  drawGraph();
}
 
Example 7
Source File: OWLDataManager.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Get the ontology referred to by this data manager.
 *
 * <p>This will create the ontology when first called (or when called
 * after #dispose() has been called).</p>
 * @return the ontology.
 * @throws OntologyHelperException if the ontology cannot be created.
 */
public OWLOntology getOntology() throws OntologyHelperException {
	if (ontology == null) {
		try {
			LOGGER.info("Loading ontology from " + ontologyUri + "...");
			OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
			IRI iri = IRI.create(ontologyUri);
			ontology = manager.loadOntologyFromOntologyDocument(iri);
		} catch (OWLOntologyCreationException e) {
			LOGGER.error("Error creating ontology: {}", e.getMessage());
			throw new OntologyHelperException(e);
		}
	}

	return ontology;
}
 
Example 8
Source File: MireotOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given an ontology, a set of upper-level IRIs, and a set of annotation properties, return a new
 * ontology with just those terms and their named descendants, their subclass relations, and the
 * selected annotations. The input ontology is not changed.
 *
 * @deprecated replaced by {@link #getDescendants(OWLOntology, Set, Set, Map, Map)}
 * @param inputOntology the ontology to extract from
 * @param upperIRIs these terms and their descendants will be copied
 * @param annotationProperties the annotation properties to copy; if null, all will be copied
 * @param annotateSource if true, annotate copied classes with rdfs:isDefinedBy
 * @param sourceMap map of term IRI to source IRI
 * @return a new ontology with the target terms and their named ancestors
 * @throws OWLOntologyCreationException on problems creating new ontology
 */
@Deprecated
public static OWLOntology getDescendants(
    OWLOntology inputOntology,
    Set<IRI> upperIRIs,
    Set<OWLAnnotationProperty> annotationProperties,
    boolean annotateSource,
    Map<IRI, IRI> sourceMap)
    throws OWLOntologyCreationException {
  logger.debug("Extract with MIREOT ...");

  OWLOntologyManager outputManager = OWLManager.createOWLOntologyManager();
  OWLOntology outputOntology = outputManager.createOntology();

  Set<OWLEntity> upperEntities = OntologyHelper.getEntities(inputOntology, upperIRIs);
  for (OWLEntity entity : upperEntities) {
    OntologyHelper.copy(inputOntology, outputOntology, entity, annotationProperties);
    if (annotateSource) {
      maybeAnnotateSource(outputOntology, outputManager, entity, sourceMap);
    }
    copyDescendantsAllIntermediates(inputOntology, outputOntology, entity, annotationProperties);
  }

  return outputOntology;
}
 
Example 9
Source File: QueryingWithNamedClasses.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
public QueryingWithNamedClasses() throws OWLOntologyCreationException {
	// Traditional setup with the OWL-API
	manager = OWLManager.createOWLOntologyManager();
	IRI ontologyIri = IRI.create(EL_ONTOLOGY);
	ontology = manager.loadOntologyFromOntologyDocument(ontologyIri);

	System.out.println("Loaded ontology: " + ontology.getOntologyID());
	// But we use the Elk reasoner (add it to the classpath)
	reasonerFactory = new ElkReasonerFactory();
	reasoner = reasonerFactory.createReasoner(ontology);
	// IMPORTANT: Precompute the inferences beforehand, otherwise no results
	// will be returned
	reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
	// Ontologies are not easy to query with the full name of concept, so we
	// keep only the interesting bit ( = shortform)
	shortFormProvider = new SimpleShortFormProvider();

	Set<OWLOntology> importsClosure = ontology.getImportsClosure();
	mapper = new BidirectionalShortFormProviderAdapter(manager,
			importsClosure, shortFormProvider);
}
 
Example 10
Source File: HyperGeometricAnalyzerTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void loadPizza() throws Exception {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  String uri = Resources.getResource("pizza.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<>();
  categories.put("http://www.co-ode.org/ontologies/pizza/pizza.owl#NamedPizza", "pizza");
  categories.put("http://www.co-ode.org/ontologies/pizza/pizza.owl#PizzaTopping", "topping");
  try (Transaction tx = graphDb.beginTx()) {
    OwlPostprocessor postprocessor = new OwlPostprocessor(graphDb, categories);
    postprocessor.processCategories(categories);
    postprocessor.processSomeValuesFrom();
    tx.success();
  }

  Map<String, String> map = new HashMap<>();
  map.put("pizza", "http://www.co-ode.org/ontologies/pizza/pizza.owl#");
  util = new CurieUtil(map);
  CypherUtil cypherUtil = new CypherUtil(graphDb, util);
  analyzer = new HyperGeometricAnalyzer(graphDb, util, graph, cypherUtil);
}
 
Example 11
Source File: OWLAPIIncrementalClassificationMultiDeltas.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare() throws TaskException {
	try {
		//load the initial version of the ontology
		manager = OWLManager.createOWLOntologyManager();
		initial = manager.loadOntologyFromOntologyDocument(ontologyFile_);
		//create the OWL reasoner
		reasoner = getOWLReasonerFactory().createReasoner(initial);
	} catch (OWLOntologyCreationException e) {
		throw new TaskException(e);
	}
}
 
Example 12
Source File: RetrievingInstances.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws OWLOntologyCreationException
 */
public static void main(String[] args) throws OWLOntologyCreationException {
	OWLOntologyManager man = OWLManager.createOWLOntologyManager();

	// Load your ontology.
	OWLOntology ont = man
			.loadOntologyFromOntologyDocument(new File(args[0]));
	
	// Create an ELK reasoner.
	OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
	OWLReasoner reasoner = reasonerFactory.createReasoner(ont);
	
	// Precompute instances for each named class in the ontology
	reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS);

	// List representative instances for each class.
	for (OWLClass clazz : ont.getClassesInSignature()) {
		for (Node<OWLNamedIndividual> individual : reasoner.getInstances(
				clazz, true)) {
			System.out.println(clazz + "("
					+ individual.getRepresentativeElement() + ")");
		}
	}

	// Terminate the worker threads used by the reasoner.
	reasoner.dispose();
}
 
Example 13
Source File: ReasonerUtilTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  String uri = Resources.getResource("ontologies/reasoner.owl").toURI().toString();
  IRI iri = IRI.create(uri);
  manager = OWLManager.createOWLOntologyManager();
  ont = manager.loadOntologyFromOntologyDocument(iri);
  ReasonerConfiguration config = new ReasonerConfiguration();
  config.setFactory(ElkReasonerFactory.class.getCanonicalName());
  config.setAddDirectInferredEdges(true);
  config.setAddInferredEquivalences(true);
  util = new ReasonerUtil(config, manager, ont);
}
 
Example 14
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 15
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static OWLOntology load(File... inputFiles) throws OWLOntologyCreationException {
	OWLOntologyManager manager= OWLManager.createOWLOntologyManager();
	OWLOntology ont = manager.createOntology();
	for (File f:inputFiles) {
		manager= OWLManager.createOWLOntologyManager();
		manager.setSilentMissingImportsHandling(false);
		IRI documentIRI = IRI.create(f);
		OWLOntology ontology = manager.loadOntologyFromOntologyDocument(documentIRI);
		ont.getOWLOntologyManager().addAxioms(ont, ontology.getAxioms());
	}
	return ont;		
}
 
Example 16
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 17
Source File: Template.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Generate an OWLOntology with given IRI based on the rows of the template.
 *
 * @param outputIRI IRI for final ontology
 * @param force if true, do not exit on errors
 * @return new OWLOntology
 * @throws Exception on issue parsing rows to axioms or creating new ontology
 */
public OWLOntology generateOutputOntology(String outputIRI, boolean force) throws Exception {
  // Set to true on first exception
  boolean hasException = false;

  for (List<String> row : tableRows) {
    try {
      processRow(row);
    } catch (RowParseException e) {
      // If force = false, fail on the first exception
      if (!force) {
        throw e;
      }
      // otherwise print exceptions as they show up
      hasException = true;
      logger.error(e.getMessage().substring(e.getMessage().indexOf("#") + 1));
    }
  }

  if (hasException) {
    logger.warn("Ontology created from template with errors");
  }

  // Create a new ontology object to add axioms to
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  OWLOntology outputOntology;
  if (outputIRI != null) {
    IRI iri = IRI.create(outputIRI);
    outputOntology = manager.createOntology(iri);
  } else {
    outputOntology = manager.createOntology();
  }

  manager.addAxioms(outputOntology, axioms);

  return outputOntology;
}
 
Example 18
Source File: QueryingUnnamedClassExpressions.java    From elk-reasoner with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws OWLOntologyCreationException {
	OWLOntologyManager man = OWLManager.createOWLOntologyManager();
	OWLDataFactory dataFactory = man.getOWLDataFactory();

	// Load your ontology.
	OWLOntology ont = man.loadOntologyFromOntologyDocument(new File(
			"c:/ontologies/ontology.owl"));

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

	// Create your desired query class expression. In this example we
	// will query ObjectIntersectionOf(A ObjectSomeValuesFrom(R B)).
	PrefixManager pm = new DefaultPrefixManager("http://example.org/");
	OWLClass A = dataFactory.getOWLClass(":A", pm);
	OWLObjectProperty R = dataFactory.getOWLObjectProperty(":R", pm);
	OWLClass B = dataFactory.getOWLClass(":B", pm);
	OWLClassExpression query = dataFactory.getOWLObjectIntersectionOf(A,
			dataFactory.getOWLObjectSomeValuesFrom(R, B));

	// Create a fresh name for the query.
	OWLClass newName = dataFactory.getOWLClass(IRI.create("temp001"));
	// Make the query equivalent to the fresh class
	OWLAxiom definition = dataFactory.getOWLEquivalentClassesAxiom(newName,
			query);
	man.addAxiom(ont, definition);

	// Remember to either flush the reasoner after the ontology change
	// or create the reasoner in non-buffering mode. Note that querying
	// a reasoner after an ontology change triggers re-classification of
	// the whole ontology which might be costly. Therefore, if you plan
	// to query for multiple complex class expressions, it will be more
	// efficient to add the corresponding definitions to the ontology at
	// once before asking any queries to the reasoner.
	reasoner.flush();

	// You can now retrieve subclasses, superclasses, and instances of
	// the query class by using its new name instead.
	reasoner.getSubClasses(newName, true);
	reasoner.getSuperClasses(newName, true);
	reasoner.getInstances(newName, false);

	// After you are done with the query, you should remove the definition
	man.removeAxiom(ont, definition);

	// You can now add new definitions for new queries in the same way

	// After you are done with all queries, do not forget to free the
	// resources occupied by the reasoner
	reasoner.dispose();
}
 
Example 19
Source File: OwlApiUtilsTest.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
  manager = OWLManager.createOWLOntologyManager();
}
 
Example 20
Source File: IOHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Create an OWLLiteral.
 *
 * @param value the lexical value
 * @return a literal
 */
public static OWLLiteral createLiteral(String value) {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  OWLDataFactory df = manager.getOWLDataFactory();
  return df.getOWLLiteral(value);
}