org.semanticweb.owlapi.reasoner.OWLReasoner Java Examples

The following examples show how to use org.semanticweb.owlapi.reasoner.OWLReasoner. 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: BasicAnnotationPropagator.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Retrieve the non redundant set of linked classes using the given
 * relation. The reasoner is used to infer the super and subsets for the
 * subClass hierarchy. Only return classes, which are in the given super set
 * (a.k.a. ontology branch).<br>
 * <br>
 * This can be an expensive operation, especially the
 * {@link #reduceToNonRedundant(Set, OWLReasoner)}. Therefore the results of
 * that method are cached in a map.<br>
 * For example, using the cache for GO, there was a reduction of the startup
 * time from 95 seconds to 10 seconds.
 * 
 * @param c
 * @param properties
 * @param g
 * @param reasoner
 * @param superSet
 * @param cache
 * @return set of linked classes, never null
 */
protected static Set<OWLClass> getNonRedundantLinkedClasses(OWLClass c, Set<OWLObjectProperty> properties, OWLGraphWrapper g, OWLReasoner reasoner, Set<OWLClass> superSet, Map<Set<OWLClass>, Set<OWLClass>> cache) {
	// get all superClasses for the current class
	Set<OWLClass> currentSuperClasses = reasoner.getSuperClasses(c, false).getFlattened();
	currentSuperClasses.add(c);
	Set<OWLClass> linkedClasses = new HashSet<OWLClass>();
	for (OWLClass currentSuperClass : currentSuperClasses) {
		if (currentSuperClass.isBuiltIn()) {
			continue;
		}
		// find all direct links via the property to the selected super set
		linkedClasses.addAll(getDirectLinkedClasses(currentSuperClass, properties, g, superSet));
	}
	// create remove redundant super classes from link set
	Set<OWLClass> nonRedundantLinks = cache.get(linkedClasses);
	if (nonRedundantLinks == null) {
		nonRedundantLinks = reduceToNonRedundant(linkedClasses, reasoner);
		cache.put(linkedClasses, nonRedundantLinks);
	}
	
	return nonRedundantLinks;
}
 
Example #2
Source File: AbstractReasonerTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected Set<OWLClass> findDescendants(OWLReasoner r, String expr, Integer numExpected) throws TimeOutException, FreshEntitiesException, InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, OWLParserException {
	System.out.println("Query: "+expr);
	OWLClassExpression qc = parseOMN(expr);
	Set<OWLClass> clzs = r.getSubClasses(qc, false).getFlattened();
	clzs.remove(r.getRootOntology().getOWLOntologyManager().getOWLDataFactory().getOWLNothing());
	if (!qc.isAnonymous())
		clzs.add((OWLClass) qc);
	System.out.println("NumD:"+clzs.size());
	for (OWLClass c : clzs) {
		System.out.println("  D:"+c);
	}
	if (numExpected != null) {
		assertEquals(numExpected.intValue(), clzs.size());
	}
	return clzs;
}
 
Example #3
Source File: ElkProofService.java    From elk-reasoner with Apache License 2.0 6 votes vote down vote up
void changeReasoner() {
	ElkReasoner newReasoner = null;
	OWLReasoner reasoner = getEditorKit().getOWLModelManager()
			.getOWLReasonerManager().getCurrentReasoner();
	if (reasoner instanceof ElkReasoner) {
		newReasoner = (ElkReasoner) reasoner;
	}
	if (newReasoner == reasoner_) {
		return;
	}
	// else
	if (reasoner_ != null && reasoner_.equals(newReasoner)) {
		return;
	}
	// else
	reasoner_ = newReasoner;
	for (ChangeListener listener : listeners_) {
		listener.reasonerChanged();
	}
}
 
Example #4
Source File: SpeciesMergeUtilTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testMergeSpecies() throws Exception {
	ParserWrapper p = new ParserWrapper();
	OWLOntology owlOntology = p.parse(getResourceIRIString("speciesMergeTest.obo"));
	OWLGraphWrapper graph = new OWLGraphWrapper(owlOntology);
	OWLReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner reasoner = rf.createReasoner(graph.getSourceOntology());
	SpeciesMergeUtil smu = new SpeciesMergeUtil(graph);
	smu.viewProperty = graph.getOWLObjectPropertyByIdentifier("BFO:0000050");
	smu.taxClass = graph.getOWLClassByIdentifier("T:1");
	smu.reasoner = reasoner;
	smu.suffix = "coelocanth";
	smu.merge();
	
	p.saveOWL(smu.ont, new OBODocumentFormat(), "target/speciesMergeOut.obo");
	
}
 
Example #5
Source File: ReasonOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given an ontology, a reasoner factory, and a map of options, return the ontology with inferred
 * axioms added after reasoning.
 *
 * @param ontology the ontology to reason over
 * @param reasonerFactory the factory to create a reasoner instance from
 * @param options a map of option strings, or null
 * @throws OntologyLogicException if the ontology contains unsatisfiable classes, properties or
 *     inconsistencies
 * @throws OWLOntologyCreationException if ontology cannot be created
 * @throws InvalidReferenceException if the reference checker fails
 */
public static void reason(
    OWLOntology ontology, OWLReasonerFactory reasonerFactory, Map<String, String> options)
    throws OntologyLogicException, OWLOntologyCreationException, InvalidReferenceException {
  logger.info("Ontology has {} axioms.", ontology.getAxioms().size());

  // Check the ontology for reference violations
  // Maybe fail if prevent-invalid-references
  checkReferenceViolations(ontology, options);

  // Get the reasoner and run initial reasoning
  // No axioms are asserted in this step
  OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
  reason(ontology, reasoner, options);

  // Get the axiom generators
  // If none are provided, just default to subclass=
  List<InferredAxiomGenerator<? extends OWLAxiom>> gens = getInferredAxiomGenerators(options);

  // Assert inferred axioms in the ontology
  assertInferred(ontology, reasoner, gens, options);
}
 
Example #6
Source File: ProvenanceReasonerWrapper.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public boolean isEdgeEntailed(OWLEdge e, OWLOntology currentOntology, OWLReasoner reasoner) {
	OWLOntologyManager m = getManager();

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

	return isEntailed;
}
 
Example #7
Source File: QueryEngineImpl.java    From sparql-dl-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * QueryEngineImpl constructor
 *
 * @param manager    An OWLOntologyManager instance of OWLAPI v3
 * @param reasoner   An OWLReasoner instance.
 * @param strictMode If strict mode is enabled the query engine will throw a QueryEngineException if data types withing the query are not correct (e.g. Class(URI_OF_AN_INDIVIDUAL))
 */
public QueryEngineImpl(OWLOntologyManager manager, OWLReasoner reasoner, boolean strictMode) {
    this.manager = manager;
    this.reasoner = reasoner;
    this.factory = manager.getOWLDataFactory();
    this.strictMode = strictMode;
    reasoner.getRootOntology()
            .getAxioms(AxiomType.ANNOTATION_ASSERTION, Imports.INCLUDED)
            .stream()
            .filter(ax -> ax.getSubject() instanceof IRI)
            .forEach(ax -> {
                unannotatedAxioms.add(ax.getAxiomWithoutAnnotations());
                annotationAssertionsBySubject.put((IRI) ax.getSubject(), ax);
            });
    Set<OWLClass> classesInSignature = reasoner.getRootOntology().getClassesInSignature(Imports.INCLUDED);
    classesInSignature.add(factory.getOWLThing());
    classesInSignature.add(factory.getOWLNothing());
    classes = ImmutableSet.copyOf(classesInSignature);
    classIris = ImmutableSet.copyOf(classes.stream().map(OWLClass::getIRI).collect(toSet()));

    annotationPropertyIris = ImmutableSet.copyOf(reasoner.getRootOntology().getAnnotationPropertiesInSignature(Imports.INCLUDED).stream().map(
            OWLNamedObject::getIRI).collect(toSet()));
}
 
Example #8
Source File: ReasonerHelperTest.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test checking for inconsistencies.
 *
 * @throws IOException if file error
 * @throws IncoherentTBoxException if has unsatisfiable classes
 * @throws IncoherentRBoxException if has unsatisfiable properties
 */
@Test
public void testInconsistentOntology()
    throws IOException, IncoherentTBoxException, IncoherentRBoxException {
  OWLOntology ontology = loadOntology("/inconsistent.owl");
  OWLReasonerFactory reasonerFactory = new org.semanticweb.elk.owlapi.ElkReasonerFactory();
  OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
  boolean isCaughtException = false;
  try {
    ReasonerHelper.validate(reasoner);

  } catch (InconsistentOntologyException e) {
    isCaughtException = true;
  }
  assertTrue(isCaughtException);
}
 
Example #9
Source File: SpeciesSubsetterUtilTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSubsetterSpecies() throws Exception {
	ParserWrapper p = new ParserWrapper();
	p.setCheckOboDoc(false);
	OWLOntology owlOntology = p.parse(getResourceIRIString("speciesMergeTest.obo"));
	OWLGraphWrapper graph = new OWLGraphWrapper(owlOntology);
	OWLReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner reasoner = rf.createReasoner(graph.getSourceOntology());
	SpeciesSubsetterUtil smu = new SpeciesSubsetterUtil(graph);
	//smu.viewProperty = graph.getOWLObjectPropertyByIdentifier("BFO:0000050");
	smu.taxClass = graph.getOWLClassByIdentifier("T:1");
	smu.reasoner = reasoner;
	smu.removeOtherSpecies();
	
	p.saveOWL(smu.ont, new OBODocumentFormat(), "target/speciesSubset.obo");
	//p.saveOWL(smu.ont,  getResourceIRIString("target/speciesSubset.owl"));
	
	assertNull(graph.getOWLClassByIdentifier("U:24"));
}
 
Example #10
Source File: OwlReader2.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
/**
 * Print the class hierarchy from this class down, assuming this class is at
 * the given level. Makes no attempt to deal sensibly with multiple
 * inheritance.
 */
private void printHierarchy(OWLReasoner reasoner,
                            OWLClass clazz, int level) throws OWLException {
    /*
     * Only print satisfiable classes -- otherwise we end up with bottom
     * everywhere
     */
    if (reasoner.isSatisfiable(clazz)) {
        for (int i = 0; i < level * INDENT; i++) {
            out.print(" ");
        }
        out.println(labelFor(clazz));
        /* Find the children and recurse */
        for (OWLClass child : reasoner.getSubClasses(clazz, true)
                .getFlattened()) {
            if (!child.equals(clazz)) {
                printHierarchy(reasoner, child, level + 1);
            }
        }
    }
}
 
Example #11
Source File: RedundantInferences.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Remove the redundant and marked as inferred super class assertions for
 * each class in the ontology signature. Uses the reasoner to infer the
 * direct super classes.
 * 
 * @param ontology
 * @param reasoner
 * @return map of class to set of redundant axioms
 */
public static Map<OWLClass, Set<RedundantAxiom>> removeRedundantSubClassAxioms(OWLOntology ontology, OWLReasoner reasoner) {
	Iterable<OWLClass> classes = ontology.getClassesInSignature();
	Map<OWLClass, Set<RedundantAxiom>> axioms = findRedundantSubClassAxioms(classes, ontology, reasoner);
	if (!axioms.isEmpty()) {
		Set<OWLSubClassOfAxiom> allAxioms = new THashSet<OWLSubClassOfAxiom>();
		for(OWLClass cls : axioms.keySet()) {
			for(RedundantAxiom redundantAxiom : axioms.get(cls)) {
				allAxioms.add(redundantAxiom.getAxiom());
			}
		}
		OWLOntologyManager manager = ontology.getOWLOntologyManager();
		manager.removeAxioms(ontology, allAxioms);
		LOG.info("Removed "+axioms.size()+" redundant axioms.");
	}
	return axioms;
	
}
 
Example #12
Source File: InferredSubClassAxiomGeneratorIncludingIndirect.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void addAxioms(
    @Nonnull OWLClass entity,
    @Nonnull OWLReasoner reasoner,
    @Nonnull OWLDataFactory dataFactory,
    @Nonnull Set<OWLSubClassOfAxiom> result) {
  if (reasoner.isSatisfiable(entity)) {
    for (OWLClass superclass : reasoner.getSuperClasses(entity, false).getFlattened()) {
      result.add(dataFactory.getOWLSubClassOfAxiom(entity, superclass));
    }
  } else {
    result.add(dataFactory.getOWLSubClassOfAxiom(entity, dataFactory.getOWLNothing()));
  }
}
 
Example #13
Source File: ElkPreferencesPanel.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() throws Exception {
	// if the reasoner is ELK and has already been created, load the
	// preferences
	OWLReasoner reasoner = getOWLModelManager().getOWLReasonerManager()
			.getCurrentReasoner();
	if (reasoner instanceof ElkReasoner) {
		((ElkReasoner) reasoner)
				.setConfigurationOptions(ElkPreferences.getElkConfig());
	}
}
 
Example #14
Source File: SimJSONTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testFindCoAnnotationList() throws Exception {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOWL(getResourceIRIString("sim/mp-subset-1.obo"));
	g =  new OWLGraphWrapper(sourceOntol);
	parseAssociations(getResource("sim/mgi-gene2mp-subset-1.tbl"), g);

	owlpp = new OWLPrettyPrinter(g);
	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {

		createOwlSim();
			//sos.setReasoner(reasoner);
		LOG.info("Reasoner="+owlsim.getReasoner());
		reasoner.flush();
		owlsim.createElementAttributeMapFromOntology();

		owlsim.populateFullCoannotationMatrix();


		SimJSONEngine sj = new SimJSONEngine(g, owlsim);


		List<OWLClass> allClasses = new ArrayList<OWLClass>();
		allClasses.addAll(g.getAllOWLClasses());
		Collections.shuffle(allClasses);

		int limit = 5;
		String jsonStr = sj.getCoAnnotationListForAttribute(g.getOWLClassByIdentifier("MP:0002082"),limit);
		LOG.info("Dumping coannotations and scores for all annotated classes");
		
		LOG.info("EXAMPLE:"+jsonStr);
	
	}
	finally {
		reasoner.dispose();
	}
}
 
Example #15
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 #16
Source File: PhenoSimHQETest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testPhenoSimMouse() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, MathException {
	ParserWrapper pw = new ParserWrapper();
	sourceOntol = pw.parseOWL(getResourceIRIString("test_phenotype.owl"));
	g =  new OWLGraphWrapper(sourceOntol);
	 owlpp = new OWLPrettyPrinter(g);
	
	// assume buffering
	OWLReasoner reasoner = new ElkReasonerFactory().createReasoner(sourceOntol);
	try {
		pproc = new PhenoSimHQEPreProcessor();
		pproc.setInputOntology(sourceOntol);
		pproc.setOutputOntology(sourceOntol);
		pproc.setReasoner(reasoner);
		pproc.setOWLPrettyPrinter(owlpp);
		((PhenoSimHQEPreProcessor)pproc).defaultLCSElementFrequencyThreshold = 0.7;

		//sos.setSimPreProcessor(pproc);
		//sos.preprocess();
		pproc.preprocess();
		reasoner.flush();

		sos = new SimpleOwlSim(sourceOntol);
		sos.setSimPreProcessor(pproc);
		sos.createElementAttributeMapFromOntology();

		//sos.saveOntology("/tmp/z.owl");

		reasoner.flush();
		for (OWLNamedIndividual i : sourceOntol.getIndividualsInSignature()) {
			for (OWLNamedIndividual j : sourceOntol.getIndividualsInSignature()) {
				showSim(i,j);
			}
		}
	}
	finally {
		reasoner.dispose();
	}
}
 
Example #17
Source File: GafSolrDocumentLoaderIntegrationRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	// check runtime for parameters
	Properties properties = System.getProperties();
	gafLocation = properties.getProperty(GafSolrDocumentLoaderIntegrationRunner.class.getSimpleName()+".gaf-folder");
	catalogXmlFile = properties.getProperty(GafSolrDocumentLoaderIntegrationRunner.class.getSimpleName()+".catalog-xml");
	assertNotNull("Did not find a catalog-xml file.", catalogXmlFile);
	assertNotNull("Did not find a gaf-folder file.", gafLocation);
	
	// setup solr loader
	loader = new GafSolrDocumentLoader(null, 1000) {

		@Override
		protected void addToServer(Collection<SolrInputDocument> docs)
				throws SolrServerException, IOException {
			solrCount += docs.size();
			GafSolrDocumentLoaderIntegrationRunner.printMemoryStats();
			System.out.println("Cache size: "+graph.getCurrentEdgesAdvancedCacheSize());
		}
		
	};
	ParserWrapper pw = new ParserWrapper();
	pw.addIRIMapper(new CatalogXmlIRIMapper(catalogXmlFile));
	// ontology
	graph = new OWLGraphWrapper(pw.parse("http://purl.obolibrary.org/obo/go/extensions/go-plus.owl"));
	graph.mergeOntology(pw.parse("http://purl.obolibrary.org/obo/go/extensions/gorel.owl"));
	loader.setGraph(graph);
	
	// eco
	EcoTools ecoTools = new EcoTools(pw);
	loader.setEcoTools(ecoTools);
	
	// taxon information
	OWLOntology taxonOwl = pw.parseOWL(TaxonTools.TAXON_PURL);
	ElkReasonerFactory factory = new ElkReasonerFactory();
	OWLReasoner taxonReasoner = factory.createReasoner(taxonOwl);
	taxonTools = new TaxonTools(taxonReasoner, true);
	loader.setTaxonTools(taxonTools);
}
 
Example #18
Source File: TransformationUtils.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void addLabel(OWLNamedIndividual i, OWLGraphWrapper g, OWLReasoner reasoner) {
	OWLOntology ontology = g.getSourceOntology();
	Set<OWLClass> types = new HashSet<>();
	if (reasoner == null) {
		for (OWLClassExpression x : OwlHelper.getTypes(i, ontology)) {
			if (!x.isAnonymous()) {
				types.add((OWLClass) x);
			}
		}
	}
	else {
		 types = reasoner.getTypes(i, true).getFlattened();
	}
	StringBuffer iLabel = null;
	for (OWLClass type : types) {
		String label = g.getLabel(type);
		if (iLabel == null)
			iLabel = new StringBuffer("a");
		else
			iLabel.append(" & ");
		iLabel.append(" "+label);
	}
	OWLDataFactory df = g.getDataFactory();
	OWLAxiom ax =
			df.getOWLAnnotationAssertionAxiom(df.getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI()),
			i.getIRI(), 
			df.getOWLLiteral(iLabel.toString()));
	g.getManager().addAxiom(ontology,
			ax);
}
 
Example #19
Source File: ReasonOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an ontology, a reasoner, a list of axiom generators, and a map of options, assert the
 * inferred axioms in the ontology.
 *
 * @param ontology OWLOntology to assert new axioms in
 * @param reasoner OWLReasoner to use to assert axioms
 * @param gens InferredAxiomGenerators to use
 * @param options map of reason options
 * @throws OWLOntologyCreationException on problem creating a new axiom ontology
 */
private static void assertInferred(
    OWLOntology ontology,
    OWLReasoner reasoner,
    List<InferredAxiomGenerator<? extends OWLAxiom>> gens,
    Map<String, String> options)
    throws OWLOntologyCreationException {
  long startTime = System.currentTimeMillis();
  // Create an ontology with ONLY the newly inferred axioms
  // Use this to check against the updated ontology with both inferred and asserted axioms
  OWLOntology newAxiomOntology = getNewAxiomOntology(ontology, reasoner, gens, options);

  // If create-new-ontology or create-new-ontology-with-annotations
  // remove the axioms from the input ontology (maybe keeping annotations)
  maybeCreateNewOntology(ontology, options);

  // Add the inferred axioms to input ontology from the new axiom ontology
  addInferredAxioms(ontology, newAxiomOntology, options);

  // Maybe use the reasoner to remove redundant subclass axioms (reduce)
  if (OptionsHelper.optionIsTrue(options, "remove-redundant-subclass-axioms")) {
    removeRedundantSubClassAxioms(reasoner, options);
  }
  logger.info("Ontology has {} axioms after all reasoning steps.", ontology.getAxioms().size());

  float elapsedTime = System.currentTimeMillis() - startTime;
  long seconds = (long) Math.ceil(elapsedTime / 1000);
  logger.info("Filling took {} seconds.", seconds);
}
 
Example #20
Source File: ReasonOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given an ontology, a reasoner, and a map of options, use the reasoner to validate the ontology,
 * compute class hierarchy, and find equivalencies.
 *
 * @param ontology OWLOntology to reason over
 * @param reasoner OWLReasoner to use
 * @param options Map of reason options
 * @throws OntologyLogicException on invalid ontology
 */
private static void reason(
    OWLOntology ontology, OWLReasoner reasoner, Map<String, String> options)
    throws OntologyLogicException {
  long startTime = System.currentTimeMillis();
  logger.info("Starting reasoning...");

  // Validate and maybe dump the unsat classes into a file
  String dumpFilePath = OptionsHelper.getOption(options, "dump-unsatisfiable", null);
  ReasonerHelper.validate(reasoner, dumpFilePath);

  logger.info("Precomputing class hierarchy...");
  reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);

  EquivalentClassReasoningMode mode =
      EquivalentClassReasoningMode.from(options.getOrDefault("equivalent-classes-allowed", ""));
  logger.info("Finding equivalencies...");

  EquivalentClassReasoning equivalentReasoning =
      new EquivalentClassReasoning(ontology, reasoner, mode);
  boolean passesEquivalenceTests = equivalentReasoning.reason();
  equivalentReasoning.logReport(logger);
  if (!passesEquivalenceTests) {
    throw new OntologyLogicException(equivalentClassAxiomError);
  }

  float elapsedTime = System.currentTimeMillis() - startTime;
  long seconds = (int) Math.ceil(elapsedTime / 1000);
  logger.info("Reasoning took {} seconds.", seconds);
}
 
Example #21
Source File: TBoxUnFoldingTool.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a new instance for the given ontology graph. Use the given set of parent
 * ids to retrieve the classes which are to be unfolded.
 * 
 * @param graph ontology
 * @param parents set of OBO-style ids
 * @param reasonerName type of reasoner to be used for inferring the relevant sub classes of the parent set.
 * @throws NonDeterministicUnfoldException
 */
public TBoxUnFoldingTool(OWLGraphWrapper graph, Set<String> parents, String reasonerName) throws NonDeterministicUnfoldException {
	this.graph = graph;
	this.ontology = graph.getSourceOntology();
	
	final InferenceBuilder inferenceBuilder = new InferenceBuilder(graph, reasonerName);
	final OWLReasoner reasoner = inferenceBuilder.getReasoner(ontology);
	
	final Set<OWLClass> unfoldClasses = new HashSet<OWLClass>();
	try {
		for(String parent : parents) {
			OWLClass parentClass = graph.getOWLClassByIdentifier(parent);
			NodeSet<OWLClass> nodeSet = reasoner.getSubClasses(parentClass , false);
			if (nodeSet != null && !nodeSet.isEmpty() && !nodeSet.isBottomSingleton()) {
				unfoldClasses.addAll(nodeSet.getFlattened());
			}
		}
	}
	finally {
		inferenceBuilder.dispose();
	}
	
	if (unfoldClasses.isEmpty()) {
		throw new RuntimeException("No classes found for given parents.");
	}
	
	visitor = new UnfoldingVisitor(unfoldClasses, ontology);
}
 
Example #22
Source File: RedundantAxiomTagger.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void tagRedundantAxioms(OWLReasoner reasoner) {
    OWLOntology ont = reasoner.getRootOntology();
    OWLOntologyManager mgr = ont.getOWLOntologyManager();
    OWLDataFactory df = mgr.getOWLDataFactory();
    OWLAnnotationProperty anProp = df.getOWLAnnotationProperty(IRI.create("http://www.geneontology.org/formats/oboInOwl#source"));
    for (OWLSubClassOfAxiom ax : ont.getAxioms(AxiomType.SUBCLASS_OF)) {
        if (!ax.getSuperClass().isAnonymous()) {
            OWLClass supc = (OWLClass) ax.getSuperClass();
            
            mgr.removeAxiom(ont, ax);
            reasoner.flush();
            NodeSet<OWLClass> ancs = reasoner.getSuperClasses(ax.getSubClass(), false);
            //LOG.info(ax + " ANCS="+ancs);
            if (ancs.containsEntity( supc)) {
                String direct = "indirect";
                if (reasoner.getSuperClasses(ax.getSubClass(), true).containsEntity( supc)) {
                    direct = "direct";
                }
                LOG.info("SCA = "+ax+" D="+direct);
                OWLAnnotation ann = df.getOWLAnnotation(anProp, df.getOWLLiteral(direct));
                OWLAxiom newAxiom = changeAxiomAnnotations(ax, Collections.singleton(ann), df);
                mgr.addAxiom(ont, newAxiom);
            }
            else {
                // put it back
                mgr.addAxiom(ont, ax);
            }
        }
    }
   
}
 
Example #23
Source File: ComplexAnnotationSolrDocumentLoader.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ComplexAnnotationSolrDocumentLoader(String url, OWLGraphWrapper g, OWLReasoner r, Set<OWLNamedIndividual> individuals, Set<OWLAnnotation> modelAnnotations, String agID, String agLabel, String agURL) throws MalformedURLException {
	super(url);
	//setGraph(g);
	current_doc_number = 0;
	currentGraph = g;
	currentReasoner  = r;
	legoIndividuals = individuals;
	this.modelAnnotations = modelAnnotations;
	currentGroupID = agID;
	currentGroupLabel = agLabel;
	currentGroupURL = agURL;
}
 
Example #24
Source File: TraversingEcoMapperTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@AfterClass
public static void afterClass() throws Exception {
	if (g != null) {
		OWLReasoner reasoner = g.getReasoner();
		if (reasoner != null) {
			reasoner.dispose();
		}
	}
}
 
Example #25
Source File: EquivalentClassReasoningTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test asserted only with asserted equiv axioms. Pass if true.
 *
 * @throws IOException on error
 */
@Test
public void testReasonOnlyAssertedAllowedOnAsserted() throws IOException {
  OWLOntology inferred = loadOntology("/asserted-equiv.owl");
  OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
  OWLReasoner reasoner = reasonerFactory.createReasoner(inferred);
  EquivalentClassReasoning assertedOnlyReasoning =
      new EquivalentClassReasoning(
          inferred, reasoner, EquivalentClassReasoningMode.ASSERTED_ONLY);

  assertTrue(assertedOnlyReasoning.reason());
}
 
Example #26
Source File: JustifyAssertionsTool.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Justify the given set of subClass axioms from the given ontology. Assumes that
 * the axioms are already removed and the reasoner is up-to-date. <br>
 * Does not modify the ontology.
 * 
 * @param ontology
 * @param reasoner
 * @param axioms
 * @return result
 */
public static JustifyResult justifySubClasses(OWLOntology ontology, OWLReasoner reasoner, Set<OWLSubClassOfAxiom> axioms) {
	
	InferenceBuilder infBuilder = new InferenceBuilder(null, (OWLReasonerFactory) null, false);
	try {
		Inferences inferences = infBuilder.buildInferences(ontology, reasoner, true);
		List<OWLAxiom> inferredAxioms = inferences.axiomsToAdd;
		return justifySubClasses(ontology, reasoner, axioms, inferredAxioms);
	}
	finally {
		infBuilder.dispose();
	}
}
 
Example #27
Source File: SpeciesMergeUtilTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testMergeFly() throws Exception {
	ParserWrapper p = new ParserWrapper();
	OWLOntology owlOntology = p.parse(getResourceIRIString("interneuron-fly.obo"));
	Set<OWLClass> clsBefore = owlOntology.getClassesInSignature();
	OWLGraphWrapper graph = new OWLGraphWrapper(owlOntology);
	OWLReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner reasoner = rf.createReasoner(graph.getSourceOntology());
	SpeciesMergeUtil smu = new SpeciesMergeUtil(graph);

	smu.viewProperty = graph.getOWLObjectPropertyByIdentifier("BFO:0000050");
	smu.taxClass = graph.getOWLClassByIdentifier("NCBITaxon:7227");
	smu.reasoner = reasoner;
	smu.suffix = "fly";
	smu.includedProperties = Collections.singleton(smu.viewProperty);
	//smu.includedProperties = Collections.singleton(graph.getOWLObjectPropertyByIdentifier("BFO:0000051"));
	smu.merge();
	
	Set<OWLClass> clsAfter = smu.ont.getClassesInSignature();
	
	LOG.info("Before: "+clsBefore.size());
	LOG.info("After: "+clsAfter.size());
	assertEquals(100, clsBefore.size());
	assertEquals(90, clsAfter.size());
	p.saveOWL(smu.ont, new OBODocumentFormat(), "target/flyMergeOut.obo");

}
 
Example #28
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 #29
Source File: OWLServer.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void destroy() {
	// clean up reasoners
	Set<String> reasonerNames = reasonerMap.keySet();
	Iterator<String> iterator = reasonerNames.iterator();
	while (iterator.hasNext()) {
		String reasonerName = iterator.next();
		OWLReasoner reasoner = reasonerMap.remove(reasonerName);
		if (reasoner != null) {
			reasoner.dispose();
		}
	}
	super.destroy();
}
 
Example #30
Source File: OWLHandler.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private OWLReasoner getReasoner() {
	String rn = getParam("reasoner");
	if (rn == null) {
		rn = "default";
	}
	return owlserver.getReasoner(rn);
}