org.semanticweb.owlapi.apibinding.OWLManager Java Examples

The following examples show how to use org.semanticweb.owlapi.apibinding.OWLManager. 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
public static synchronized void silenceOboParser() {
  if (silencedParser) {
    return;
  }
  OWLManager.createOWLOntologyManager();
  /* TODO: Why does this logging never become silent?
   * Logger logger = Logger.getLogger("org.obolibrary");
  logger.setLevel(java.util.logging.Level.SEVERE);
  Handler[] handlers = logger.getHandlers();
  for (Handler handler : handlers) {
    handler.setLevel(Level.SEVERE);
  }*/
  // TODO: Why does this cause a concurrent modification exception if not synchronized
  OWLParserFactoryRegistry registry = OWLParserFactoryRegistry.getInstance();
  List<OWLParserFactory> factories = registry.getParserFactories();
  for (OWLParserFactory factory : factories) {
    if (factory instanceof OBOFormatParserFactory ||
        factory instanceof OBO12ParserFactory) {
      registry.unregisterParserFactory(factory);
    }
  }
  silencedParser = true;
}
 
Example #2
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 #3
Source File: QueryEngineStrictModeTest.java    From sparql-dl-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void oneTimeSetUp()
{
	try {
		// Create our ontology manager in the usual way.
		manager = OWLManager.createOWLOntologyManager();

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

		// We need to create an instance of Reasoner.
		StructuralReasonerFactory factory = new StructuralReasonerFactory();
		reasoner = factory.createReasoner(ont);
		reasoner.precomputeInferences();
       }
       catch(UnsupportedOperationException exception) {
           System.out.println("Unsupported reasoner operation.");
       }
       catch(OWLOntologyCreationException e) {
           System.out.println("Could not load the wine ontology: " + e.getMessage());
       }
}
 
Example #4
Source File: AxiomDeserialiser.java    From snomed-owl-toolkit with Apache License 2.0 6 votes vote down vote up
AxiomDeserialiser() {
	owlOntologyManager = OWLManager.createOWLOntologyManager();
	try {
		owlOntology = owlOntologyManager.loadOntologyFromOntologyDocument(
				new StringDocumentSource(ontologyDocStart + ontologyDocEnd));
	} catch (OWLOntologyCreationException e) {
		throw new RuntimeException(e);
	}
	OWLAPIConfigProvider owlapiConfigProvider = new OWLAPIConfigProvider();
	owlOntologyLoaderConfiguration = owlapiConfigProvider.get();
	owlFunctionalSyntaxOWLParser = new OWLFunctionalSyntaxOWLParser();
	owlOntologyManager.addOntologyChangeListener(list -> {
		for (OWLOntologyChange owlOntologyChange : list) {
			if (owlOntologyChange instanceof AddAxiom) {
				AddAxiom addAxiom = (AddAxiom) owlOntologyChange;
				owlAxiomsLoaded.add(addAxiom.getAxiom());
			}
		}
	});
	timeTakenDeserialisingAxioms = 0;
}
 
Example #5
Source File: ProofTest.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
@Test
public void inconsistentOwlThing() 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"));
	// top subclass bottom => inconsistent
	owlManager.addAxiom(ontology, factory.getOWLSubClassOfAxiom(
			factory.getOWLThing(), factory.getOWLNothing()));

	final OWLProver prover = OWLAPITestUtils.createProver(ontology);

	ProofTestUtils.provabilityTest(prover,
			factory.getOWLSubClassOfAxiom(a, b));
	ProofTestUtils.provabilityTest(prover,
			factory.getOWLSubClassOfAxiom(
					factory.getOWLObjectIntersectionOf(a, b),
					factory.getOWLNothing()));
}
 
Example #6
Source File: ProofTest.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
@Test
public void inconsistentClass() 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"));
	// A subclass of bottom => A is inconsistent
	owlManager.addAxiom(ontology,
			factory.getOWLSubClassOfAxiom(a, factory.getOWLNothing()));

	final OWLProver prover = OWLAPITestUtils.createProver(ontology);

	ProofTestUtils.provabilityTest(prover,
			factory.getOWLSubClassOfAxiom(a, b));
}
 
Example #7
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 #8
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 #9
Source File: FilterCommand.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given a command line and an input ontology, create a new output ontology to put filtered axioms
 * in.
 *
 * @param line command line to use
 * @param inputOntology input ontology to maybe copy IRI
 * @return OWLOntology output ontology
 * @throws OWLOntologyCreationException on problem creating a new ontology
 */
private static OWLOntology getOutputOntology(CommandLine line, OWLOntology inputOntology)
    throws OWLOntologyCreationException {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  // Get the output IRI for the new ontology
  IRI outputIRI;
  String outputIRIString = CommandLineHelper.getOptionalValue(line, "ontology-iri");
  if (outputIRIString != null) {
    outputIRI = IRI.create(outputIRIString);
  } else {
    // If it is not provided, copy the input IRI
    outputIRI = inputOntology.getOntologyID().getOntologyIRI().orNull();
  }

  // Create the output ontology
  OWLOntology outputOntology;
  if (outputIRI != null) {
    outputOntology = manager.createOntology(outputIRI);
  } else {
    outputOntology = manager.createOntology();
  }

  return outputOntology;
}
 
Example #10
Source File: Report.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a new report object with a QuotedEntityChecker loaded with entries from the label map.
 * Use labels for report output.
 *
 * @param labelMap Map of IRI to label for all entities in the ontology
 * @throws IOException on problem creating IOHelper
 */
public Report(Map<IRI, String> labelMap) throws IOException {
  this.ioHelper = new IOHelper();
  checker = new QuotedEntityChecker();
  checker.setIOHelper(ioHelper);
  checker.addProvider(new SimpleShortFormProvider());
  checker.addProperty(OWLManager.getOWLDataFactory().getRDFSLabel());
  if (labelMap != null) {
    useLabels = true;
    OWLDataFactory df = OWLManager.getOWLDataFactory();
    for (Entry<IRI, String> entry : labelMap.entrySet()) {
      // Set all the entities as class - will not matter for retrieving label
      OWLEntity e = df.getOWLEntity(EntityType.CLASS, entry.getKey());
      checker.add(e, entry.getValue());
    }
  }
}
 
Example #11
Source File: IOHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Load an ontology from an InputStream with a catalog file.
 *
 * @param ontologyStream the ontology stream to load
 * @param catalogPath the catalog file to use or null
 * @return a new ontology object, with a new OWLManager
 * @throws IOException on any problem
 */
public OWLOntology loadOntology(InputStream ontologyStream, String catalogPath)
    throws IOException {
  OWLOntology ontology;
  // Maybe load a catalog file
  File catalogFile = null;
  if (catalogPath != null) {
    catalogFile = new File(catalogPath);
    if (!catalogFile.isFile()) {
      throw new IOException(String.format(fileDoesNotExistError, catalogPath));
    }
  }
  try {
    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    if (catalogFile != null) {
      manager.setIRIMappers(Sets.newHashSet(new CatalogXmlIRIMapper(catalogFile)));
    }
    ontology = manager.loadOntologyFromOntologyDocument(ontologyStream);
  } catch (OWLOntologyCreationException e) {
    throw new IOException(invalidOntologyStreamError, e);
  }
  return ontology;
}
 
Example #12
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 #13
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 #14
Source File: OWLGraphManipulatorTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test that two {@code OWLClass}es that are equal have a same hashcode, 
 * because the OWLGraphEdge bug get me paranoid. 
 */
@Test
public void testOWLClassHashCode()
{
	 OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
	 OWLDataFactory factory = manager.getOWLDataFactory(); 
	 IRI iri = IRI.create("http://www.foo.org/#A");
	 OWLClass class1 = factory.getOWLClass(iri);
	 //get the class by another way, even if if I suspect the two references 
	 //will point to the same object
	 PrefixManager pm = new DefaultPrefixManager("http://www.foo.org/#"); 
	 OWLClass class2 = factory.getOWLClass(":A", pm);
	 
	 assertTrue("The two references point to different OWLClass objects", 
			 class1 == class2);
	 //then of course the hashcodes will be the same...
	 assertTrue("Two OWLClasses are equal but have different hashcode", 
			 class1.equals(class2) && class1.hashCode() == class2.hashCode());
}
 
Example #15
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 #16
Source File: AbstractOWLOntologyLoader.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
protected void doInitialization() throws OWLOntologyCreationException {
    // init owl fields
    this.manager = OWLManager.createOWLOntologyManager();
    if (getOntologyResource() != null) {
        getLog().info("Mapping ontology IRI from {} to {}", getOntologyIRI(), getOntologyResource());
        this.manager.addIRIMapper(new SimpleIRIMapper(getOntologyIRI(),
                IRI.create(getOntologyResource())));
    }
    if (getOntologyImportMappings() != null) {
        for (IRI from : getOntologyImportMappings().keySet()) {
            IRI to = getOntologyImportMappings().get(from);
            getLog().info("Mapping imported ontology IRI from " + from + " to " + to);
            this.manager.addIRIMapper(new SimpleIRIMapper(from, to));
        }
    }
    this.factory = manager.getOWLDataFactory();

    // collect things we want to ignore form OWL vocab
    owlVocabulary.add(factory.getOWLThing().getIRI());
    owlVocabulary.add(factory.getOWLNothing().getIRI());
    owlVocabulary.add(factory.getOWLTopObjectProperty().getIRI());
    owlVocabulary.add(factory.getOWLBottomObjectProperty().getIRI());

    // load the ontology
    this.ontology = loadOntology();
}
 
Example #17
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 src an ontology document
 * @return a list of rules
 */
public static List<Rule> fromOntology(OWLOntologyDocumentSource src) {
	try {
		// use OWL-API to get a OWLOntology document from source
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		manager.loadOntologyFromOntologyDocument(src);
		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 #18
Source File: WEKAOntologyConnector.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates an ontology connector using the standard ontology.
 * 
 * @throws OWLOntologyCreationException
 *             If the ontology cannot be created
 */
public WEKAOntologyConnector() throws OWLOntologyCreationException {
	OWLOntologyManager ontologyManager = OWLManager.createOWLOntologyManager();
	dataFactory = ontologyManager.getOWLDataFactory();
	InputStream inputStream = Thread.currentThread().getContextClassLoader()
			.getResourceAsStream(ONTOLOGY_FILE_NAME);
	ontology = ontologyManager.loadOntologyFromOntologyDocument(inputStream);
}
 
Example #19
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 #20
Source File: SimpleOntology.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initialize(OntologyManager ontologyManager, SesameTransformer transformer, BNodeService bNodeService,
                        RepositoryManager repoManager, boolean resolveImports, ForkJoinPool threadPool) {
    this.threadPool = threadPool;
    this.ontologyManager = ontologyManager;
    this.transformer = transformer;
    this.bNodeService = bNodeService;
    this.repoManager = repoManager;
    this.owlManager = OWLManager.createOWLOntologyManager();
    owlManager.addMissingImportListener((MissingImportListener) arg0 -> {
        missingImports.add(SimpleOntologyValues.mobiIRI(arg0.getImportedOntologyURI()));
        LOG.warn("Missing import {} ", arg0.getImportedOntologyURI());
    });
    owlManager.setOntologyLoaderConfiguration(config);
    OWLOntologyWriterConfiguration writerConfig = new OWLOntologyWriterConfiguration()
            .withRemapAllAnonymousIndividualsIds(false)
            .withSaveIdsForAllAnonymousIndividuals(true);
    owlManager.setOntologyWriterConfiguration(writerConfig);
    owlManager.setOntologyConfigurator(owlManager.getOntologyConfigurator()
            .withRemapAllAnonymousIndividualsIds(false)
            .withSaveIdsForAllAnonymousIndividuals(true));
    if (resolveImports) {
        owlManager.getIRIMappers().add(new MobiOntologyIRIMapper(ontologyManager));
        OWLOntologyFactory originalFactory = owlManager.getOntologyFactories().iterator().next();
        owlManager.getOntologyFactories().add(new MobiOntologyFactory(ontologyManager, originalFactory,
                transformer));
    } else {
        owlManager.setIRIMappers(Collections.singleton(new NoImportLoader()));
    }

    RDFParserRegistry parserRegistry = RDFParserRegistry.getInstance();
    Set<RioAbstractParserFactory> owlParsers = new HashSet<>(Arrays.asList(new RioOWLXMLParserFactory(),
            new RioManchesterSyntaxParserFactory(), new RioFunctionalSyntaxParserFactory()));
    owlParsers.forEach(parserRegistry::add);
}
 
Example #21
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 #22
Source File: SatisfiabilityChecker.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
  OWLOntology ont = manager.loadOntology(IRI.create(args[0]));
  ReasonerConfiguration config = new ReasonerConfiguration();
  config.setFactory(ElkReasonerFactory.class.getCanonicalName());
  ReasonerUtil util = new ReasonerUtil(config, manager, ont);
  Collection<OWLOntologyChange> removals = util.removeUnsatisfiableClasses();
  if (!removals.isEmpty()) {
    logger.info("Removed " + removals.size() + " to help prevent unsatisfiable classes.");
    for (OWLOntologyChange removal: removals) {
      logger.info(removal.toString());
    }
  }
  OWLReasoner reasoner = util.getReasoner();
  if (!reasoner.isConsistent()) {
    logger.severe("Ontology is inconsistent");
    System.exit(1);
  }
  Collection<OWLClass> unsatisfiableClasses = util.getUnsatisfiableClasses();
  if (!unsatisfiableClasses.isEmpty()) {
    logger.severe("Ontology is unsatisfiable");
     for (OWLClass unsatisfiableClass: unsatisfiableClasses) {
       logger.severe(unsatisfiableClass.toString());
     }
     System.exit(2);
  }
  logger.info("Ontology is consistent and satisfiable");
  System.exit(0);
}
 
Example #23
Source File: RepairOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testXrefRepair() throws IOException {
  OWLAnnotationProperty hasDbXref =
      OWLManager.getOWLDataFactory()
          .getOWLAnnotationProperty(
              IRI.create("http://www.geneontology.org/formats/oboInOwl#hasDbXref"));
  OWLOntology ontology = loadOntology("/xref-need-of-repair.obo");
  IOHelper iohelper = new IOHelper();
  RepairOperation.repair(ontology, iohelper, true, Collections.singleton(hasDbXref));
  assertIdentical("/xref-repaired.obo", ontology);
}
 
Example #24
Source File: OntologyHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an ontology, a threshold, and a set of precious IRIs (or empty set), minimize the input
 * ontology's class hierarchy based on the threshold. The threshold is the minimum number of child
 * classes that an intermediate class should have. Any intermediate class that has less than the
 * threshold number of children will be removed and its children will become children of the next
 * level up. Bottom-level and top-level classes are not removed. Any class with an IRI in the
 * precious set is not removed. If not repeat, collapse will only be performed once, meaning that
 * some intermediate classes may remain.
 *
 * @param ontology OWLOntology to minimize
 * @param threshold minimum number of child classes
 * @param precious set of IRIs to keep
 * @param repeat if true, repeat collapsing until no intermediate classes remain
 */
public static void collapseOntology(
    OWLOntology ontology, int threshold, Set<IRI> precious, boolean repeat)
    throws OWLOntologyCreationException {
  OWLOntology copy =
      OWLManager.createOWLOntologyManager().copyOntology(ontology, OntologyCopy.DEEP);
  logger.debug("Classes before collapsing: " + ontology.getClassesInSignature().size());

  Set<OWLObject> removeClasses = getClassesToRemove(ontology, threshold, precious);

  boolean collapsedOnce = false;

  // Remove axioms based on classes
  // Get all axioms that involve these classes
  // Continue to get remove classes until there's no more to remove
  while (!removeClasses.isEmpty()) {
    if (collapsedOnce && !repeat) {
      break;
    }
    Set<OWLAxiom> axiomsToRemove =
        RelatedObjectsHelper.getPartialAxioms(ontology, removeClasses, null);
    OWLOntologyManager manager = ontology.getOWLOntologyManager();
    manager.removeAxioms(ontology, axiomsToRemove);
    // Span gaps to maintain hierarchy
    manager.addAxioms(
        ontology, RelatedObjectsHelper.spanGaps(copy, OntologyHelper.getObjects(ontology)));
    // Repeat until there's no more to remove
    removeClasses = getClassesToRemove(ontology, threshold, precious);
    collapsedOnce = true;
  }
  logger.debug("Classes after collapsing: " + ontology.getClassesInSignature().size());
}
 
Example #25
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 #26
Source File: ReasonOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an input ontology, a new axiom ontology (created from reasoning), and a map of options,
 * maybe remove asserted axioms from the input ontology if create-new-ontology or
 * create-new-ontology-with-annotations. The input ontology is updated in place.
 *
 * @param ontology OWLOntology to maybe update
 * @param options Map of reason options
 */
private static void maybeCreateNewOntology(OWLOntology ontology, Map<String, String> options) {
  OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

  // If we need to "create" a new ontology,
  // we actually just remove any asserted axioms from the input ontology
  if (OptionsHelper.optionIsTrue(options, "create-new-ontology")
      || OptionsHelper.optionIsTrue(options, "create-new-ontology-with-annotations")) {
    if (OptionsHelper.optionIsTrue(options, "create-new-ontology-with-annotations")) {
      logger.info("Placing inferred axioms with annotations into a new ontology");
      manager.removeAxioms(
          ontology,
          ontology
              .getAxioms()
              .stream()
              .filter(nonap -> !(nonap instanceof OWLAnnotationAssertionAxiom))
              .collect(Collectors.toSet()));

    } else {
      logger.info("Placing inferred axioms into a new ontology");
      manager.removeAxioms(ontology, ontology.getAxioms());
    }

    Set<OWLImportsDeclaration> oids = ontology.getImportsDeclarations();
    for (OWLImportsDeclaration oid : oids) {
      RemoveImport ri = new RemoveImport(ontology, oid);
      manager.applyChange(ri);
    }
  }
}
 
Example #27
Source File: ReasonOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a tautology checker.
 *
 * @param structural if true, return null - we do not need a checker for the structural patterns
 * @return new OWLReasoner for empty ontology or null
 * @throws OWLOntologyCreationException on issue creating empty ontology
 */
public static OWLReasoner getTautologyChecker(boolean structural)
    throws OWLOntologyCreationException {
  if (!structural) {
    OWLOntology empty = OWLManager.createOWLOntologyManager().createOntology();
    return new ReasonerFactory().createReasoner(empty);
  } else {
    return null;
  }
}
 
Example #28
Source File: MireotOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 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.
 *
 * @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 options map of options
 * @param inputSourceMap map of source IRIs (or null)
 * @return a new ontology with the target terms and their named ancestors
 * @throws OWLOntologyCreationException on problems creating new ontology
 */
public static OWLOntology getDescendants(
    OWLOntology inputOntology,
    Set<IRI> upperIRIs,
    Set<OWLAnnotationProperty> annotationProperties,
    Map<String, String> options,
    Map<IRI, IRI> inputSourceMap)
    throws OWLOntologyCreationException {
  logger.debug("Extract with MIREOT ...");

  // Get options
  setOptions(options, inputSourceMap);

  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 ("none".equals(intermediates)) {
      copyDescendantsNoIntermediates(
          inputOntology, outputOntology, entity, entity, annotationProperties);
    } else {
      copyDescendantsAllIntermediates(
          inputOntology, outputOntology, entity, annotationProperties);
    }
    if (annotateSource) {
      maybeAnnotateSource(outputOntology, outputManager, entity, sourceMap);
    }
  }

  if ("minimal".equalsIgnoreCase(intermediates)) {
    OntologyHelper.collapseOntology(outputOntology, upperIRIs);
  }

  return outputOntology;
}
 
Example #29
Source File: IOHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an IRI and a path to a catalog file, load the ontology from the IRI with the catalog.
 *
 * @param ontologyIRI the ontology IRI to load
 * @param catalogPath the catalog file to use or null
 * @return a new ontology object, with a new OWLManager
 * @throws IOException on any problem
 */
public OWLOntology loadOntology(IRI ontologyIRI, String catalogPath) throws IOException {
  OWLOntology ontology;
  // Maybe load a catalog file
  File catalogFile = null;
  if (catalogPath != null) {
    catalogFile = new File(catalogPath);
    if (!catalogFile.isFile()) {
      throw new IOException(String.format(fileDoesNotExistError, catalogPath));
    }
  }
  try {
    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    // If a catalog file was loaded, set IRI mappers
    if (catalogFile != null) {
      manager.setIRIMappers(Sets.newHashSet(new CatalogXmlIRIMapper(catalogFile)));
    }
    // Maybe load a zipped ontology
    if (ontologyIRI.toString().endsWith(".gz")) {
      ontology = loadCompressedOntology(new URL(ontologyIRI.toString()), catalogPath);
    } else {
      // Otherwise load ontology as normal
      ontology = manager.loadOntologyFromOntologyDocument(ontologyIRI);
    }
  } catch (OWLOntologyCreationException e) {
    throw new IOException(e);
  }
  return ontology;
}
 
Example #30
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;
}