Java Code Examples for org.semanticweb.owlapi.model.OWLOntology#getImportsClosure()

The following examples show how to use org.semanticweb.owlapi.model.OWLOntology#getImportsClosure() . 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: UnmergeOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given a list of ontologies and a target ontology, remove all the axioms from the listed
 * ontologies and their import closure from the target ontology.
 *
 * @param ontologies the list of ontologies to unmerge
 * @param targetOntology the ontology to remove axioms from
 * @param includeAnnotations true if ontology annotations should be remove
 */
public static void unmergeFrom(
    List<OWLOntology> ontologies, OWLOntology targetOntology, boolean includeAnnotations) {
  for (OWLOntology ontology : ontologies) {
    logger.info("Removing axioms from: " + ontology);
    targetOntology.getOWLOntologyManager().removeAxioms(targetOntology, ontology.getAxioms());
    if (includeAnnotations) {
      for (OWLAnnotation annotation : ontology.getAnnotations()) {
        RemoveOntologyAnnotation remove =
            new RemoveOntologyAnnotation(targetOntology, annotation);
        targetOntology.getOWLOntologyManager().applyChange(remove);
      }
    }
    for (OWLOntology imported : ontology.getImportsClosure()) {
      targetOntology.getOWLOntologyManager().removeAxioms(targetOntology, imported.getAxioms());
    }
  }
}
 
Example 2
Source File: OWLGraphWrapperBasic.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Each ontology in the import closure of the source ontology
 * (and the import closure of each existing support ontology, if
 * doForAllSupportOntologies is true) is added to
 * the list of support ontologies
 * 
 * @param doForAllSupportOntologies
 */
public void addSupportOntologiesFromImportsClosure(boolean doForAllSupportOntologies) {
	Set<OWLOntology> ios = new HashSet<OWLOntology>();
	ios.add(sourceOntology);

	if (doForAllSupportOntologies) {
		ios.addAll(getSupportOntologySet());
	}
	for (OWLOntology so : ios) {
		for (OWLOntology o : so.getImportsClosure()) {
			if (o.equals(sourceOntology))
				continue;
			addSupportOntology(o);
		}
	}
}
 
Example 3
Source File: EmptyImportTest.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
/**
 * @return the list of the axioms from the import closure of the given
 *         ontology
 */
private static List<OWLAxiom> getAxioms(OWLOntology main) {
	List<OWLAxiom> axioms = new ArrayList<OWLAxiom>();
	for (OWLOntology ont : main.getImportsClosure()) {
		axioms.addAll(ont.getAxioms());
	}
	return axioms;
}
 
Example 4
Source File: ElkReasonerTest.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
/**
 * @return the list of the axioms from the import closure of the given
 *         ontology
 */
private static List<OWLAxiom> getAxioms(OWLOntology main) {
	List<OWLAxiom> axioms = new ArrayList<OWLAxiom>();
	for (OWLOntology ont : main.getImportsClosure()) {
		axioms.addAll(ont.getAxioms());
	}
	return axioms;
}
 
Example 5
Source File: MirrorOperationTest.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Mirrors a given ontology plus its import closure, and tests the results are identical when
 * loaded.
 *
 * @param expectedPath resource path for the ontology.
 * @throws Exception on any problem
 */
public void testMirror(String expectedPath) throws Exception {
  OWLOntology inputOntology = loadOntologyWithCatalog(expectedPath);

  File catalogFile = new File("target/mirror-catalog.xml");
  MirrorOperation.mirror(inputOntology, new File("target"), catalogFile);

  IRI iri = inputOntology.getOntologyID().getOntologyIRI().orNull();
  OWLOntology loadedOntology;
  if (iri != null) {
    loadedOntology = loadOntologyWithCatalog(iri, catalogFile);
  } else {
    throw new Exception(String.format("Test ontology %s does not have an IRI", expectedPath));
  }
  assertIdentical(loadedOntology, inputOntology);
  int n = 0;
  for (OWLOntology importedOntology : inputOntology.getImportsClosure()) {
    n++;
    boolean isMatched = false;
    for (OWLOntology loadedImportedOntology : loadedOntology.getImportsClosure()) {
      if (loadedImportedOntology.getOntologyID().equals(importedOntology.getOntologyID())) {
        assertIdentical(loadedImportedOntology, importedOntology);
        isMatched = true;
      }
    }
    assertTrue(isMatched);
  }

  assertEquals(2, n);
  assertEquals(2, loadedOntology.getImportsClosure().size());
}
 
Example 6
Source File: TransformationUtils.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Names all inner ObjectSomeValuesFrom expressions
 * 
 * @param srcOntology
 * @param tgtOntology
 * @param qmap
 * @param isAddLabels
 * @return
 */
public static Map<OWLClass, OWLClassExpression> nameObjectSomeValuesFrom(OWLOntology srcOntology,
		OWLOntology tgtOntology,
		Map<OWLClass,OWLClassExpression> qmap,
		boolean isAddLabels) {

	if (qmap == null) 
		qmap = new HashMap<OWLClass, OWLClassExpression>();
	OWLOntologyManager mgr = srcOntology.getOWLOntologyManager();
	OWLDataFactory df = mgr.getOWLDataFactory();
	for (OWLOntology ont : srcOntology.getImportsClosure()) {
		for (OWLAxiom ax : srcOntology.getAxioms()) {
			for (OWLClassExpression x : ax.getNestedClassExpressions()) {
				if (x instanceof OWLObjectSomeValuesFrom) {
					OWLObjectSomeValuesFrom svf = (OWLObjectSomeValuesFrom)x;
					OWLClass filler = (OWLClass) svf.getFiller();
					OWLObjectProperty p = (OWLObjectProperty) svf.getProperty();
					IRI iri = getSkolemIRI(filler, p);
					OWLClass c = df.getOWLClass(iri);
					mgr.addAxiom(tgtOntology, df.getOWLEquivalentClassesAxiom(c, svf));
					qmap.put(c, svf);
					if (isAddLabels) {
						Set<OWLAnnotation> anns = OwlHelper.getAnnotations(filler, df.getRDFSLabel(), ont);
						for (OWLAnnotation ann : anns) {
							mgr.addAxiom(tgtOntology, df.getOWLAnnotationAssertionAxiom(c.getIRI(), ann));
						}
					}
				}
			}
		}
	}
	return qmap;

}
 
Example 7
Source File: OntologySetMetadata.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public OntologySetMetadata(OWLOntology ont) {
	ontologies = new HashSet<OntologyMetadata>();
	for (OWLOntology io : ont.getImportsClosure()) {
		OntologyMetadata om = new OntologyMetadata(io);
		ontologies.add(om);
		if (io.equals(ont)) {
			om.isRoot = true;
		}
	}
}
 
Example 8
Source File: MirrorOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Mirrors ontologies on local filesystem.
 *
 * @param rootOntology The ontology to mirror.
 * @param baseFolder The folder.
 * @param catalogFile The catalog file to write to.
 * @throws IOException on most problems.
 * @throws OWLOntologyStorageException if the ontology cannot be saved.
 */
public static void mirror(OWLOntology rootOntology, File baseFolder, File catalogFile)
    throws IOException, OWLOntologyStorageException {

  logger.info("Mirroring ontologies: " + rootOntology);
  Map<IRI, String> iriMap = new HashMap<>();
  for (OWLOntology ont : rootOntology.getImportsClosure()) {
    logger.info("Mirroring: " + ont);
    validateImports(ont);

    OWLOntologyID ontologyID = ont.getOntologyID();
    IRI ontologyIRI = ontologyID.getOntologyIRI().orNull();

    // Not really sure why this is here, but apparently we can get
    // an ontology without an IRI, in which case we'll generate one
    // that is 'sort of' unique (only fails if two different machines
    // run this tool at the exact same time).
    //
    if (ontologyIRI == null) {
      ontologyIRI = IRI.generateDocumentIRI();
    }
    // Always write the actualIRI
    String localFilePath = getMirrorPathOfOntologyIRI(ontologyIRI);
    IRI outputStream = IRI.create(new File(baseFolder, localFilePath));
    ont.getOWLOntologyManager().saveOntology(ont, outputStream);
    iriMap.put(ontologyIRI, localFilePath);

    //
    // In case there is a difference between the source document IRI
    // and the IRI of the resolved target (e.g., there is an HTTP
    // redirect from a legacy IRI to a newer IRI), then write an entry
    // in the catalog that points the legacy IRI to the newer, canonical
    // one.
    // Examples of this include:
    //  http://purl.obolibrary.org/obo/so.owl
    // which redirects to:
    //  http://purl.obolibrary.org/obo/so-xp.obo.owl
    //

    IRI documentIRI = ont.getOWLOntologyManager().getOntologyDocumentIRI(ont);
    if (!documentIRI.toString().startsWith("file:") && documentIRI != ontologyIRI) {
      String sourceLocalFile = getMirrorPathOfOntologyIRI(ontologyIRI);
      logger.info("Mirroring " + documentIRI + " in " + sourceLocalFile);
      iriMap.put(documentIRI, sourceLocalFile);
    }
  }
  writeCatalog(catalogFile, iriMap);
}
 
Example 9
Source File: OWLGraphManipulator.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
     * Merges {@code OWLAxiom}s from the import ontology closure, with the source ontology.
     * This method is similar to {@link OWLGraphWrapperBasic#mergeImportClosure(boolean)}, 
     * except that: i) an {@code OWLAxiom} will be added to the source ontology only if 
     * it is not already present in the source (without taking annotations into account); 
     * ii) a check is performed to ensure that there will not be more than 
     * one annotation axiom for a given subject, when the annotation property 
     * corresponds to a tag with max cardinality one in OBO format 
     * (see {@code org.obolibrary.oboformat.model.Frame#check()}). As for 
     * {@link OWLGraphWrapperBasic#mergeImportClosure(boolean)}, annotations on the ontology 
     * itself are not imported, and the import declarations are removed after execution. 
     */
    private void mergeImportClosure() {
        log.info("Merging axioms from import closure with source ontology...");
        OWLOntology sourceOnt = this.getOwlGraphWrapper().getSourceOntology();
        
        //the method OWLOntology.containsAxiomIgnoreAnnotations is really 
        //not well optimized, so we get all OWLAxioms without annotations 
        //from the source ontology. 
        log.debug("Retrieving OWLAxioms without annotations from source ontology...");
        Set<OWLAxiom> sourceAxiomsNoAnnots = new HashSet<OWLAxiom>();
        for (OWLAxiom ax: sourceOnt.getAxioms()) {
            sourceAxiomsNoAnnots.add(ax.getAxiomWithoutAnnotations());
        }
        if (log.isDebugEnabled()) {
            log.debug(sourceAxiomsNoAnnots.size() + " axioms without annotations retrieved " +
            		"over " + sourceOnt.getAxiomCount() + " axioms.");
        }
        
        for (OWLOntology importedOnt: sourceOnt.getImportsClosure()) {
            if (importedOnt.equals(sourceOnt)) {
                continue;
            }
            log.info("Merging " + importedOnt);
            
//            OWLDataFactory df = sourceOnt.getOWLOntologyManager().getOWLDataFactory();
//            OWLAnnotationProperty p = 
//                    df.getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_COMMENT.getIRI());
//            OWLLiteral v = df.getOWLLiteral("Imported " + importedOnt);
//            OWLAnnotation ann = df.getOWLAnnotation(p, v);
//            AddOntologyAnnotation addAnn = 
//                    new AddOntologyAnnotation(sourceOnt, ann);
//            sourceOnt.getOWLOntologyManager().applyChange(addAnn);
            
            //filter the axioms imported to avoid redundancy (too bad there is not 
            //a method OWLOntology.getAxiomsIgnoreAnnotations())
            int importedAxiomCount = 0;
            importAxioms: for (OWLAxiom importedAx: importedOnt.getAxioms()) {
                if (sourceAxiomsNoAnnots.contains(importedAx.getAxiomWithoutAnnotations())) {
                    continue importAxioms;
                }
                    
                //if it is an annotation axion, we need to ensure that 
                //there will not be more than one axiom for a given subject, 
                //when the annotation corresponds to a tag with max cardinality one 
                //in OBO format (see org.obolibrary.oboformat.model.Frame#check()).
                if (importedAx instanceof OWLAnnotationAssertionAxiom) {
                    OWLAnnotationAssertionAxiom castAx = 
                            (OWLAnnotationAssertionAxiom) importedAx;

                    if (maxOneCardinalityAnnots.contains(
                            castAx.getProperty().getIRI().toString()) || 
                            maxOneCardinalityAnnots.contains(
                                    this.getOwlGraphWrapper().getIdentifier(
                                            castAx.getProperty()))) {

                        //check whether we have an annotation for the same subject 
                        //in the source ontology.
                        for (OWLAnnotationAssertionAxiom sourceAnnotAx: 
                            sourceOnt.getAnnotationAssertionAxioms(
                                    castAx.getSubject())) {
                            if (sourceAnnotAx.getProperty().equals(
                                    castAx.getProperty())) {
                                //discard the axiom from import ontology, there is already 
                                //an annotation with same property on same subject
                                log.trace("Discarding axiom: " + castAx);
                                continue importAxioms;
                            }
                        }
                    }
                }
                
                //all verifications passed, include the axiom
                importedAxiomCount++;
                sourceAxiomsNoAnnots.add(importedAx.getAxiomWithoutAnnotations());
                sourceOnt.getOWLOntologyManager().addAxiom(sourceOnt, importedAx);
            }
            log.info(importedAxiomCount + " axioms imported.");
        }

        //remove the import declarations
        Set<OWLImportsDeclaration> oids = sourceOnt.getImportsDeclarations();
        for (OWLImportsDeclaration oid : oids) {
            RemoveImport ri = new RemoveImport(sourceOnt, oid);
            sourceOnt.getOWLOntologyManager().applyChange(ri);
        }
        
        log.info("Done merging axioms.");
    }