### OBO Header Example with OWL Axioms
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Example of an OBO header containing metadata and owl-axioms clauses for disjoint class definitions.
```text
format-version: 1.2 ontology: go date: 17:04:2012 15:38 ... remark: this is an example of what a header in the GO might look like remark: We have two axioms, the first declares that nothing is part of remark: both a nucleus and a cytoplasm, the second declares that remark: nothing is part of both a cytoplasm and a plasma membrane. remark: (Note we could have chosen to use a single axiom with 3 remark: arguments, which is better as it also gives us the spatial remark: disjointness between nucleus and PM) owl-axioms: DisjointClasses(ObjectSomeValuesFrom(:BFO_0000050 :GO_0005737) ObjectSomeValuesFrom(:BFO_0000050 :GO_0005634)) owl-axioms: DisjointClasses(ObjectSomeValuesFrom(:BFO_0000050 :GO_0005737) ObjectSomeValuesFrom(:BFO_0000050 :GO_0005886)) [Term] ...
```
--------------------------------
### OBO Document Header with Imports
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Example of an OBO header using owl:imports translated to import directives.
```text
import: http://purl.obolibrary.org/obo/go/extensions/chebi_import.owl
import: http://purl.obolibrary.org/obo/go/extensions/cl_import.owl
import: http://purl.obolibrary.org/obo/go/extensions/po_import.owl
ontology: go
```
--------------------------------
### OBO-Edit Catalog File Mapping
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Example of a catalog file mapping OWL URIs to local OBO files.
```text
# GO imports mappings
http://purl.obolibrary.org/obo/go/extensions/chebi_import.owl ../extensions/chebi_import.obo
http://purl.obolibrary.org/obo/go/extensions/cl_import.owl ../extensions/cl_import.obo
http://purl.obolibrary.org/obo/go/extensions/po_import.owl ../extensions/po_import.obo
```
--------------------------------
### Get Axioms Count with Imports Flag
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Changed method to include an imports flag for counting axioms. Use this to get the total axiom count, including those from imported ontologies.
```Java
OWLOntology::getAxiomsCount()
```
--------------------------------
### Define Data Property Constraints in Functional Syntax
Source: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/resources/org/semanticweb/owlapi/apitest/profileNOQLTestCases.txt
Examples of data property range and functional constraints using OWL Functional Syntax.
```text
Prefix(:=) Prefix(xsd:=) Ontology( Declaration(NamedIndividual(:a)) Declaration(DataProperty(:hasAge)) DataPropertyRange(:hasAge xsd:integer) ClassAssertion(DataHasValue(:hasAge "aString"^^xsd:string) :a))
```
```text
Prefix(:=) Prefix(xsd:=) Ontology( Declaration(NamedIndividual(:a)) Declaration(DataProperty(:hasAge)) FunctionalDataProperty(:hasAge) ClassAssertion(DataHasValue(:hasAge "18"^^xsd:integer) :a) ClassAssertion(DataHasValue(:hasAge "19"^^xsd:integer) :a))
```
--------------------------------
### Get Axioms with Imports Flag
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Changed method to include an imports flag for retrieving axioms. Use this when you need to consider axioms from imported ontologies.
```Java
OWLOntology::getAxioms()
```
--------------------------------
### Get Same Individuals Axioms
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
This method retrieves axioms for same individuals. It's refactored to use the Searcher.different utility for comparison.
```Java
Searcher.different(ontology.getSameIndividualAxioms(individual))
```
--------------------------------
### OBO Format File Comments Example
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Illustrates how to add comments for opaque identifiers in OBO format files. Ensure comments are preceded by a tag-value pair and use a single space around the '!' character.
```obo
relationship: part_of ABC:1234567 ! hand
relationship: R:9999999 ABC:1234567 ! part_of hand
```
--------------------------------
### Get Axiom with Imports and Search Flags
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Use this method to retrieve an axiom, considering imported ontologies and search parameters. It replaces getAxiomIgnoreAnnotations().
```Java
getAxiom() with imports flag and Search flag
```
--------------------------------
### Get Equivalent Data Properties Axioms
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Use this method to retrieve equivalent data properties axioms for a given property. It leverages the Searcher utility for comparison.
```Java
Searcher.different(ontology.getEquivalentDataPropertiesAxioms(property))
```
--------------------------------
### Get Equivalent Classes Axioms
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves equivalent classes axioms for a specified class. This refactored method uses the Searcher utility for checking differences.
```Java
Searcher.different(ontology.getEquivalentClassesAxioms(class))
```
--------------------------------
### Data Property Assertions in OWL API
Source: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/resources/org/semanticweb/owlapi/apitest/inputSorting.txt
Provides examples of asserting data values for individuals using data properties. Supports various data types like strings and booleans.
```java
DataPropertyAssertion( _:genid1 "testString"^^xsd:int)
DataPropertyAssertion( _:genid1 "true"^^xsd:boolean)
```
--------------------------------
### Initialize DLQueryParser
Source: https://github.com/owlcs/owlapi/wiki/DL-Queries-with-a-real-reasoner
Configures the parser with an ontology and a short form provider to map strings to OWL entities.
```java
private final BidirectionalShortFormProvider bidiShortFormProvider;
public DLQueryParser(OWLOntology rootOntology, ShortFormProvider shortFormProvider) {
this.rootOntology = rootOntology;
OWLOntologyManager manager = rootOntology.getOWLOntologyManager();
Set importsClosure = rootOntology.getImportsClosure();
// Create a bidirectional short form provider to do the actual mapping.
// It will generate names using the input
// short form provider.
bidiShortFormProvider = new BidirectionalShortFormProviderAdapter(manager,
importsClosure, shortFormProvider);
}
public OWLClassExpression parseClassExpression(String classExpressionString) {
OWLDataFactory dataFactory = rootOntology.getOWLOntologyManager()
.getOWLDataFactory();
ManchesterOWLSyntaxEditorParser parser = new ManchesterOWLSyntaxEditorParser(
dataFactory, classExpressionString);
parser.setDefaultOntology(rootOntology);
OWLEntityChecker entityChecker = new ShortFormEntityChecker(bidiShortFormProvider);
parser.setOWLEntityChecker(entityChecker);
return parser.parseClassExpression();
}
}
```
--------------------------------
### Get Referencing Axioms for OWL Object
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
This refactored method directly calls OWLOntology.getReferencingAxioms() to get axioms that reference an OWL object.
```Java
OWLOntology::getReferencingAxioms()
```
--------------------------------
### Recommended Axiom Formatting
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Recommended practice of placing each axiom on its own line.
```text
owl-axioms: DisjointClasses(ObjectSomeValuesFrom(:BFO_0000050 :GO_0005737) ObjectSomeValuesFrom(:BFO_0000050 :GO_0005634)) owl-axioms: DisjointClasses(ObjectSomeValuesFrom(:BFO_0000050 :GO_0005737) ObjectSomeValuesFrom(:BFO_0000050 :GO_0005886))
```
--------------------------------
### Using Reasoners for Inference in OWL API
Source: https://context7.com/owlcs/owlapi/llms.txt
This snippet demonstrates building a simple ontology, creating a reasoner, precomputing inferences, checking consistency, retrieving unsatisfiable classes, finding subclasses and instances, and generating inferred axioms. For production, consider using HermiT or Pellet reasoners.
```Java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.reasoner.*;
import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory;
import org.semanticweb.owlapi.util.*;
import java.util.List;
import java.util.ArrayList;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(IRI.create("http://example.org/reasoning"));
OWLDataFactory factory = manager.getOWLDataFactory();
// Build a simple class hierarchy
OWLClass animal = factory.getOWLClass("http://example.org/reasoning#", "Animal");
OWLClass mammal = factory.getOWLClass("http://example.org/reasoning#", "Mammal");
OWLClass dog = factory.getOWLClass("http://example.org/reasoning#", "Dog");
OWLNamedIndividual fido = factory.getOWLNamedIndividual("http://example.org/reasoning#", "Fido");
manager.addAxiom(ontology, factory.getOWLSubClassOfAxiom(mammal, animal));
manager.addAxiom(ontology, factory.getOWLSubClassOfAxiom(dog, mammal));
manager.addAxiom(ontology, factory.getOWLClassAssertionAxiom(dog, fido));
// Create reasoner (use HermiT or Pellet for real reasoning)
// For production: OWLReasonerFactory reasonerFactory = new org.semanticweb.HermiT.ReasonerFactory();
OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
// Precompute inferences
reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
// Check consistency
boolean consistent = reasoner.isConsistent();
System.out.println("Ontology is consistent: " + consistent);
// Get unsatisfiable classes
Node unsatisfiable = reasoner.getUnsatisfiableClasses();
System.out.println("Unsatisfiable classes: " + unsatisfiable.getEntitiesMinusBottom());
// Get subclasses of Animal (direct=true for immediate subclasses only)
NodeSet subClasses = reasoner.getSubClasses(animal, false);
System.out.println("Subclasses of Animal: " + subClasses.getFlattened());
// Output: Subclasses of Animal: [Dog, Mammal, owl:Nothing]
// Get instances of Animal
NodeSet instances = reasoner.getInstances(animal, false);
System.out.println("Instances of Animal: " + instances.getFlattened());
// Output: Instances of Animal: [Fido]
// Generate inferred axioms
List> generators = new ArrayList<>();
generators.add(new InferredSubClassAxiomGenerator());
generators.add(new InferredClassAssertionAxiomGenerator());
OWLOntology inferredOnt = manager.createOntology();
InferredOntologyGenerator iog = new InferredOntologyGenerator(reasoner, generators);
iog.fillOntology(factory, inferredOnt);
System.out.println("Inferred axioms: " + inferredOnt.getAxiomCount());
```
--------------------------------
### Get Annotation Assertion Axioms
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Directly retrieves annotation assertion axioms for an OWL object using OWLOntology.getAnnotationAssertionAxioms().
```Java
OWLOntology::getAnnotationAssertionAxioms()
```
--------------------------------
### Manage Ontology Imports in Java
Source: https://context7.com/owlcs/owlapi/llms.txt
Shows how to declare imports, configure IRI mappers for local file resolution, and inspect the imports closure of an ontology.
```java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.model.AddImport;
import org.semanticweb.owlapi.util.SimpleIRIMapper;
import org.semanticweb.owlapi.util.AutoIRIMapper;
import java.io.File;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Create import declaration
IRI importedOntologyIRI = IRI.create("http://example.org/imported-ontology");
OWLImportsDeclaration importDeclaration = manager.getOWLDataFactory()
.getOWLImportsDeclaration(importedOntologyIRI);
// Create main ontology
OWLOntology mainOntology = manager.createOntology(IRI.create("http://example.org/main-ontology"));
// Add import declaration to ontology
manager.applyChange(new AddImport(mainOntology, importDeclaration));
// Configure IRI mapper to redirect remote IRI to local file
IRI localDocumentIRI = IRI.create(new File("/path/to/local/ontology.owl").toURI());
SimpleIRIMapper iriMapper = new SimpleIRIMapper(importedOntologyIRI, localDocumentIRI);
manager.getIRIMappers().add(iriMapper);
// AutoIRIMapper finds ontologies in a folder automatically
File ontologyFolder = new File("/path/to/ontology/folder");
AutoIRIMapper autoMapper = new AutoIRIMapper(ontologyFolder, true); // true = recursive
manager.getIRIMappers().add(autoMapper);
// Load the import manually (imports are resolved during loading)
// manager.loadOntology(importedOntologyIRI);
// Get imports closure (ontology + all imported ontologies)
for (OWLOntology ont : mainOntology.getImportsClosure()) {
System.out.println("In closure: " + ont.getOntologyID());
}
// Get direct imports only
mainOntology.directImports().forEach(imp ->
System.out.println("Direct import: " + imp.getOntologyID())
);
// Check imports declarations
mainOntology.importsDeclarations().forEach(decl ->
System.out.println("Import declaration: " + decl.getIRI())
);
```
--------------------------------
### Configure JNI library path for FaCT++
Source: https://github.com/owlcs/owlapi/wiki/Reasoners,-OWL-API-Support,-papers-about-the-OWL-API
Set the java.library.path system property to point to the directory containing native binaries for the FaCT++ reasoner.
```bash
-Djava.library.path=/path/to/FaCT++/folder/lib/native/64bit
```
--------------------------------
### Get Inverse Properties
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves inverse object property axioms for a given property. This refactored method uses Searcher.inverses.
```Java
Searcher.inverses(ontology.getInverseObjectPropertyAxioms(property))
```
--------------------------------
### Get Annotations for OWL Object
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves annotation assertion axioms for an OWL object. The refactored method uses Searcher.annotations.
```Java
Searcher.annotations(ontology.getAnnotationAssertionAxioms(annotationSubject))
```
--------------------------------
### Run japicmp for OWLAPI Version Comparison
Source: https://github.com/owlcs/owlapi/blob/version5/etc/versionChanges.md
Command to execute japicmp for comparing two OWLAPI distribution JARs. Use this to identify API changes between versions.
```bash
java -jar ~/Downloads/japicmp-0.14.4-jar-with-dependencies.jar -b --ignore-missing-classes -o v1/owlapi-distribution-v1.jar -n v2/owlapi-distribution-v2.jar
```
--------------------------------
### Get Types for OWL Object
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves class assertion axioms for an individual to determine its types. This refactored method uses Searcher.types.
```Java
Searcher.types(ontology.getClassAssertionAxioms(individual))
```
--------------------------------
### Define Class with Annotation and SameAs
Source: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/resources/org/semanticweb/owlapi/apitest/profileNOQLTestCases.txt
Demonstrates an OWL class with a custom annotation property and a sameAs relationship in RDF/XML.
```xml
description of c1
```
--------------------------------
### Implement DLQueryPrinter
Source: https://github.com/owlcs/owlapi/wiki/DL-Queries-with-a-real-reasoner
Handles the execution of queries against a DLQueryEngine and formats the resulting entities for console output.
```java
class DLQueryPrinter {
private final DLQueryEngine dlQueryEngine;
private final ShortFormProvider shortFormProvider;
public DLQueryPrinter(DLQueryEngine engine, ShortFormProvider shortFormProvider) {
this.shortFormProvider = shortFormProvider;
dlQueryEngine = engine;
}
public void askQuery(String classExpression) {
if (classExpression.length() == 0) {
System.out.println("No class expression specified");
} else {
try {
StringBuilder sb = new StringBuilder();
sb.append("\nQUERY: ").append(classExpression).append("\n\n");
Set superClasses = dlQueryEngine.getSuperClasses(
classExpression, false);
printEntities("SuperClasses", superClasses, sb);
Set equivalentClasses = dlQueryEngine
.getEquivalentClasses(classExpression);
printEntities("EquivalentClasses", equivalentClasses, sb);
Set subClasses = dlQueryEngine.getSubClasses(classExpression,
true);
printEntities("SubClasses", subClasses, sb);
Set individuals = dlQueryEngine.getInstances(
classExpression, true);
printEntities("Instances", individuals, sb);
System.out.println(sb.toString());
} catch (ParserException e) {
System.out.println(e.getMessage());
}
}
}
private void printEntities(String name, Set extends OWLEntity> entities,
StringBuilder sb) {
sb.append(name);
int length = 50 - name.length();
for (int i = 0; i < length; i++) {
sb.append(".");
}
sb.append("\n\n");
if (!entities.isEmpty()) {
for (OWLEntity entity : entities) {
sb.append("\t").append(shortFormProvider.getShortForm(entity))
.append("\n");
}
} else {
sb.append("\t[NONE]\n");
}
sb.append("\n");
}
}
```
--------------------------------
### Get Data Property Ranges
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves data property range axioms for a given property. The refactored method uses Searcher.range.
```Java
Searcher.range(ontology.getDataPropertyRangeAxioms(property))
```
--------------------------------
### Get Data Property Domains
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves data property domain axioms for a given property. This refactored method uses Searcher.domain.
```Java
Searcher.domain(ontology.getDataPropertyDomainAxioms(property))
```
--------------------------------
### Get Object Property Ranges
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves object property range axioms for a given property. The refactored method uses Searcher.range.
```Java
Searcher.range(ontology.getObjectPropertyRangeAxioms(property))
```
--------------------------------
### IntelliJ Code Style Configuration
Source: https://github.com/owlcs/owlapi/wiki/Style-for-patches
XML configuration for IntelliJ IDEA to enforce OWLAPI formatting rules.
```xml
```
--------------------------------
### Load and Print an Ontology
Source: https://github.com/owlcs/owlapi/wiki/Tutorial:-A-starter's-starter
Creates an ontology manager to load a remote ontology and output it in functional syntax.
```java
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntology(IRI.create("https://protege.stanford.edu/ontologies/pizza/pizza.owl"));
ontology.saveOntology(new FunctionalSyntaxDocumentFormat(), System.out);
```
--------------------------------
### Get Object Property Domains
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves object property domain axioms for a given property. This refactored method uses Searcher.domain.
```Java
Searcher.domain(ontology.getObjectPropertyDomainAxioms(property))
```
--------------------------------
### Perform DL Queries with HermiT in Java
Source: https://github.com/owlcs/owlapi/wiki/DL-Queries-with-a-real-reasoner
Uses the HermiT reasoner to process Manchester Syntax class expressions from standard input. Requires the HermiT library on the classpath.
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Set;
import org.coode.owlapi.manchesterowlsyntax.ManchesterOWLSyntaxEditorParser;
import org.semanticweb.HermiT.Reasoner;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.expression.OWLEntityChecker;
import org.semanticweb.owlapi.expression.ParserException;
import org.semanticweb.owlapi.expression.ShortFormEntityChecker;
import org.semanticweb.owlapi.io.StringDocumentSource;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.NodeSet;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.util.BidirectionalShortFormProvider;
import org.semanticweb.owlapi.util.BidirectionalShortFormProviderAdapter;
import org.semanticweb.owlapi.util.ShortFormProvider;
import org.semanticweb.owlapi.util.SimpleShortFormProvider;
public class DLQueriesWithHermiT {
public static void main(String[] args) throws Exception {
// Load an example ontology.
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager
.loadOntologyFromOntologyDocument(new StringDocumentSource(koala));
// We need a reasoner to do our query answering
// These two lines are the only relevant difference between this code and the original example
// This example uses HermiT: http://hermit-reasoner.com/
OWLReasoner reasoner = new Reasoner.ReasonerFactory().createReasoner(ontology);
ShortFormProvider shortFormProvider = new SimpleShortFormProvider();
// Create the DLQueryPrinter helper class. This will manage the
// parsing of input and printing of results
DLQueryPrinter dlQueryPrinter = new DLQueryPrinter(new DLQueryEngine(reasoner,
shortFormProvider), shortFormProvider);
// Enter the query loop. A user is expected to enter class
// expression on the command line.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
while (true) {
System.out
.println("Type a class expression in Manchester Syntax and press Enter (or press x to exit):");
String classExpression = br.readLine();
// Check for exit condition
if (classExpression == null || classExpression.equalsIgnoreCase("x")) {
break;
}
dlQueryPrinter.askQuery(classExpression.trim());
System.out.println();
}
}
// for convenience, the Koala ontology is stored in this string
private final static String koala = "\n"
+ "\n"
+ " \n"
+ " \n"
+ " \n"
```
--------------------------------
### Define SameAs Relationships
Source: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/resources/org/semanticweb/owlapi/apitest/profileNOQLTestCases.txt
Demonstrates direct and nested owl:sameAs assertions in RDF/XML.
```xml
```
```xml
```
--------------------------------
### Get Data Property Values for Individual
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves data property assertion axioms for an individual and property. The refactored method uses Searcher.values.
```Java
Searcher.values(ontology.getDataPropertyAssertionAxioms(individual), property)
```
--------------------------------
### Get Object Property Values for Individual
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves object property assertion axioms for an individual and property. The refactored method uses Searcher.values.
```Java
Searcher.values(ontology.getObjectPropertyAssertionAxioms(individual), property)
```
--------------------------------
### Get Individuals for OWL Object
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves class assertion axioms for a class to find associated individuals. This refactored method uses Searcher.instances.
```Java
Searcher.instances(ontology.getClassAssertionAxioms(class))
```
--------------------------------
### Load Ontology from Various Sources
Source: https://context7.com/owlcs/owlapi/llms.txt
Load ontologies using the OWLOntologyManager from an IRI (URL or file), a local file, or a string containing OWL content. Useful for testing and integrating existing ontologies.
```java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.io.StringDocumentSource;
import java.io.File;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Load from IRI (URL or file)
OWLOntology ontFromIRI = manager.loadOntology(
IRI.create("http://protege.stanford.edu/plugins/owl/owl-library/koala.owl")
);
// Load from local file
File localFile = new File("/path/to/ontology.owl");
OWLOntology ontFromFile = manager.loadOntologyFromOntologyDocument(localFile);
// Load from string content (useful for testing)
String owlContent = "Prefix(owl:=)
" +
"Ontology()
" +
"Declaration(Class())
" +
")";
OWLOntology ontFromString = manager.loadOntologyFromOntologyDocument(
new StringDocumentSource(owlContent)
);
System.out.println("Classes in ontology: " + ontFromString.classesInSignature().count());
// Output: Classes in ontology: 1
```
--------------------------------
### Delete Entities and Axioms in Java
Source: https://context7.com/owlcs/owlapi/llms.txt
Demonstrates three methods for removing entities and axioms: direct axiom removal, filtering axioms by signature, and using the OWLEntityRemover utility.
```java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.util.OWLEntityRemover;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(IRI.create("http://example.org/deletion"));
OWLDataFactory factory = manager.getOWLDataFactory();
// Create some entities and axioms
OWLClass person = factory.getOWLClass("http://example.org/deletion#", "Person");
OWLClass student = factory.getOWLClass("http://example.org/deletion#", "Student");
OWLNamedIndividual john = factory.getOWLNamedIndividual("http://example.org/deletion#", "John");
manager.addAxiom(ontology, factory.getOWLDeclarationAxiom(person));
manager.addAxiom(ontology, factory.getOWLSubClassOfAxiom(student, person));
manager.addAxiom(ontology, factory.getOWLClassAssertionAxiom(student, john));
System.out.println("Before deletion: " + ontology.getAxiomCount() + " axioms");
// Method 1: Remove specific axioms directly
OWLAxiom axiomToRemove = factory.getOWLClassAssertionAxiom(student, john);
manager.removeAxiom(ontology, axiomToRemove);
// Method 2: Remove all axioms mentioning an entity
Set axiomsToRemove = new HashSet<>();
for (OWLAxiom ax : ontology.getAxioms()) {
if (ax.getSignature().contains(student)) {
axiomsToRemove.add(ax);
System.out.println("Removing: " + ax);
}
}
manager.removeAxioms(ontology, axiomsToRemove);
// Method 3: Use OWLEntityRemover utility
OWLEntityRemover remover = new OWLEntityRemover(Collections.singleton(ontology));
person.accept(remover); // Mark person for removal
manager.applyChanges(remover.getChanges());
remover.reset(); // Reset if you want to reuse
System.out.println("After deletion: " + ontology.getAxiomCount() + " axioms");
```
--------------------------------
### Save Ontology to Various Formats
Source: https://context7.com/owlcs/owlapi/llms.txt
Use this code to save an ontology to different file formats including RDF/XML, OWL/XML, Turtle, Manchester Syntax, and Functional Syntax. Ensure the necessary OWL API format classes are imported.
```java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.formats.*;
import org.semanticweb.owlapi.io.StreamDocumentTarget;
import org.semanticweb.owlapi.io.StringDocumentTarget;
import java.io.File;
import java.io.ByteArrayOutputStream;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(IRI.create("http://example.org/save-test"));
// Add some content
OWLDataFactory factory = manager.getOWLDataFactory();
OWLClass person = factory.getOWLClass("http://example.org/save-test#", "Person");
manager.addAxiom(ontology, factory.getOWLDeclarationAxiom(person));
// Save to file in RDF/XML format (default)
File rdfXmlFile = new File("/tmp/ontology.owl");
manager.saveOntology(ontology, IRI.create(rdfXmlFile.toURI()));
// Save in OWL/XML format
OWLXMLDocumentFormat owlXmlFormat = new OWLXMLDocumentFormat();
manager.saveOntology(ontology, owlXmlFormat, IRI.create(new File("/tmp/ontology.owx").toURI()));
// Save in Turtle format
TurtleDocumentFormat turtleFormat = new TurtleDocumentFormat();
manager.saveOntology(ontology, turtleFormat, IRI.create(new File("/tmp/ontology.ttl").toURI()));
// Save in Manchester Syntax format
ManchesterSyntaxDocumentFormat manchesterFormat = new ManchesterSyntaxDocumentFormat();
manager.saveOntology(ontology, manchesterFormat, IRI.create(new File("/tmp/ontology.omn").toURI()));
// Save in Functional Syntax format
FunctionalSyntaxDocumentFormat funcFormat = new FunctionalSyntaxDocumentFormat();
manager.saveOntology(ontology, funcFormat, IRI.create(new File("/tmp/ontology.ofn").toURI()));
// Save to output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
manager.saveOntology(ontology, new StreamDocumentTarget(outputStream));
String content = outputStream.toString();
// Save to string (useful for debugging)
StringDocumentTarget stringTarget = new StringDocumentTarget();
manager.saveOntology(ontology, stringTarget);
System.out.println(stringTarget.toString());
```
--------------------------------
### Get Negative Data Property Values for Individual
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves negative data property assertion axioms for an individual and property. This refactored method uses Searcher.negValues.
```Java
Searcher.negValues(ontology.getNegativeDataPropertyAssertionAxioms(individual), property)
```
--------------------------------
### Merge Imports Closure with owltools
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Command to merge an OWL ontology's imports closure and export it as an OBO file.
```bash
owltools myont.owl --merge-imports-closure -o -f obo myont.obo
```
--------------------------------
### Get Negative Object Property Values for Individual
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Retrieves negative object property assertion axioms for an individual and property. This refactored method uses Searcher.negValues.
```Java
Searcher.negValues(ontology.getNegativeObjectPropertyAssertionAxioms(individual), property)
```
--------------------------------
### OWLManager.createOWLOntologyManager
Source: https://context7.com/owlcs/owlapi/llms.txt
Initializes the central manager instance for handling ontology lifecycles, IRI mappings, and access to parsers.
```APIDOC
## Java Method: OWLManager.createOWLOntologyManager
### Description
Creates the central manager instance for working with ontologies. The manager handles ontology lifecycle, maintains IRI mappings, and provides access to parsers and storers.
### Method
Static Factory Method
### Request Example
```java
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntologyManager concurrentManager = OWLManager.createConcurrentOWLOntologyManager();
```
```
--------------------------------
### Safely Get Ontology IRI from OWLOntologyID
Source: https://github.com/owlcs/owlapi/wiki/MigrateTo4Tricks
Retrieve the ontology IRI using `.getOntologyIRI().get()` as `getOntologyIRI()` now returns an Optional. This applies similarly to `getVersionIRI()` and `getDefaultDocumentIRI()`.
```java
ontologyId.getOntologyIRI().get()
```
--------------------------------
### DLQueryEngine Implementation
Source: https://github.com/owlcs/owlapi/wiki/DL-Queries-with-a-real-reasoner
A class that wraps an OWLReasoner to perform queries on class expressions.
```Java
class DLQueryEngine {
private final OWLReasoner reasoner;
private final DLQueryParser parser;
public DLQueryEngine(OWLReasoner reasoner, ShortFormProvider shortFormProvider) {
this.reasoner = reasoner;
parser = new DLQueryParser(reasoner.getRootOntology(), shortFormProvider);
}
public Set getSuperClasses(String classExpressionString, boolean direct) {
if (classExpressionString.trim().length() == 0) {
return Collections.emptySet();
}
OWLClassExpression classExpression = parser
.parseClassExpression(classExpressionString);
NodeSet superClasses = reasoner
.getSuperClasses(classExpression, direct);
return superClasses.getFlattened();
}
public Set getEquivalentClasses(String classExpressionString) {
if (classExpressionString.trim().length() == 0) {
return Collections.emptySet();
}
OWLClassExpression classExpression = parser
.parseClassExpression(classExpressionString);
Node equivalentClasses = reasoner.getEquivalentClasses(classExpression);
Set result = null;
if (classExpression.isAnonymous()) {
result = equivalentClasses.getEntities();
} else {
result = equivalentClasses.getEntitiesMinus(classExpression.asOWLClass());
}
return result;
}
public Set getSubClasses(String classExpressionString, boolean direct) {
if (classExpressionString.trim().length() == 0) {
return Collections.emptySet();
}
OWLClassExpression classExpression = parser
.parseClassExpression(classExpressionString);
NodeSet subClasses = reasoner.getSubClasses(classExpression, direct);
return subClasses.getFlattened();
}
public Set getInstances(String classExpressionString,
boolean direct) {
if (classExpressionString.trim().length() == 0) {
return Collections.emptySet();
}
OWLClassExpression classExpression = parser
.parseClassExpression(classExpressionString);
NodeSet individuals = reasoner.getInstances(classExpression,
direct);
return individuals.getFlattened();
}
}
```
--------------------------------
### Handling Optional Ontology IRI
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
The `getOntologyIRI()` method now returns an `Optional`. Avoid direct string concatenation without calling `get()` to prevent unexpected IRI formatting.
```java
ontology.getOntologyID().getOntologyIRI()
```
--------------------------------
### OWLDataFactory - Creating Entities
Source: https://context7.com/owlcs/owlapi/llms.txt
Provides methods to create OWL classes, properties, and individuals using the factory pattern.
```APIDOC
## Java Class: OWLDataFactory
### Description
The OWLDataFactory creates all OWL entities (classes, properties, individuals) and axioms. Entities are referenced by IRI and don't exist in an ontology until used in axioms.
### Request Example
```java
OWLDataFactory factory = manager.getOWLDataFactory();
OWLClass personClass = factory.getOWLClass(IRI.create("http://example.org/ontology#Person"));
OWLObjectProperty hasParent = factory.getOWLObjectProperty(":hasParent", pm);
OWLNamedIndividual john = factory.getOWLNamedIndividual(":John", pm);
```
```
--------------------------------
### Define HasKey and Individual Data
Source: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/resources/org/semanticweb/owlapi/apitest/profileNOQLTestCases.txt
Demonstrates the use of owl:hasKey to define a key for a class and individual data assertions in RDF/XML.
```xml
PeterKichwa-Tembo
```
--------------------------------
### Translation of OBO Qualifiers to OWL Annotations
Source: https://github.com/owlcs/owlapi/blob/version5/oboformat/doc/obo-syntax.html
Demonstrates the general translation of OBO qualifier expressions into OWL annotation structures. Qualifiers are mapped to T(Qualifier) terms.
```OWL
T(Qualifier1) ... T(QualifierN)
```
--------------------------------
### Using EntitySearcher for Class and Property Relationship Retrieval
Source: https://github.com/owlcs/owlapi/wiki/Migrate-from-version-3.4-and-3.5-to-4.0
Methods for retrieving superclasses, subclasses, disjoint classes, equivalent classes, individuals, disjoint properties, subproperties, equivalent properties, superproperties, domains, ranges, and inverses have been moved to `EntitySearcher`. Use the static methods provided.
```java
cls.getSuperClasses(ont) -> EntitySearcher.getSuperClasses(cls, ont)
```
```java
cls.getSubClasses(ont) -> EntitySearcher.getSubClasses(cls, ont)
```
```java
cls.getDisjointClasses(ont) -> EntitySearcher.getDisjointClasses(cls, ont)
```
```java
cls.getEquivalentClasses(ont) -> EntitySearcher.getEquivalentClasses(cls, ont)
```
```java
cls.getIndividuals(ont) -> EntitySearcher.getIndividuals(cls, ont)
```
```java
entity.getReferencingAxioms(ont, false) -> EntitySearcher.getReferencingAxioms(entity, ont)
```
```java
property.getDisjointProperties(ont) -> EntitySearcher.getDisjointProperties(property, ont)
```
```java
property.getSubProperties(ont) -> EntitySearcher.getSubProperties(property, ont)
```
```java
property.getEquivalentProperties(ont) -> EntitySearcher.getEquivalentProperties(property, ont)
```
```java
property.getSuperProperties(ont) -> EntitySearcher.getSuperProperties(property, ont)
```
```java
property.getDomains(ont) -> EntitySearcher.getDomains(property, ont)
```
```java
property.getRanges(ont) -> EntitySearcher.getRanges(property, ont)
```
```java
property.getInverses(ont) -> EntitySearcher.getInverses(property, ont)
```
--------------------------------
### Adding Annotations to Ontology Elements
Source: https://context7.com/owlcs/owlapi/llms.txt
Demonstrates how to add rdfs:label, rdfs:comment, custom annotations, and ontology-level annotations using OWLDataFactory and OWLManager. Requires OWL API imports.
```Java
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.change.AddOntologyAnnotation;
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(IRI.create("http://example.org/annotations"));
OWLDataFactory factory = manager.getOWLDataFactory();
OWLClass person = factory.getOWLClass("http://example.org/annotations#", "Person");
manager.addAxiom(ontology, factory.getOWLDeclarationAxiom(person));
// Add rdfs:label annotation
OWLAnnotation labelAnnotation = factory.getRDFSLabel(
factory.getOWLLiteral("Person", "en")
);
OWLAxiom labelAxiom = factory.getOWLAnnotationAssertionAxiom(person.getIRI(), labelAnnotation);
manager.addAxiom(ontology, labelAxiom);
// Add rdfs:comment annotation
OWLAnnotation commentAnnotation = factory.getRDFSComment(
factory.getOWLLiteral("A human being", "en")
);
manager.addAxiom(ontology, factory.getOWLAnnotationAssertionAxiom(person.getIRI(), commentAnnotation));
// Add custom annotation property
OWLAnnotationProperty creator = factory.getOWLAnnotationProperty(
IRI.create("http://purl.org/dc/elements/1.1/creator")
);
OWLAnnotation creatorAnnotation = factory.getOWLAnnotation(
creator,
factory.getOWLLiteral("John Doe")
);
manager.addAxiom(ontology, factory.getOWLAnnotationAssertionAxiom(person.getIRI(), creatorAnnotation));
// Add ontology-level annotation (e.g., version info)
OWLLiteral versionLiteral = factory.getOWLLiteral("Version 1.0");
OWLAnnotation versionAnnotation = factory.getOWLAnnotation(factory.getOWLVersionInfo(), versionLiteral);
manager.applyChange(new AddOntologyAnnotation(ontology, versionAnnotation));
// Retrieve and display annotations
System.out.println("Annotations on Person class:");
ontology.annotationAssertionAxioms(person.getIRI())
.forEach(ax -> System.out.println(" " + ax.getProperty().getIRI().getShortForm() +
": " + ax.getValue()));
// Output:
// Annotations on Person class:
// label: "Person"@en
// comment: "A human being"@en
// creator: "John Doe"
```