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

The following examples show how to use org.semanticweb.owlapi.model.OWLOntology#getAxioms() . 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: FilterOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Remove axioms from the input ontology. This version expects a set of OWLObjectProperties.
 *
 * @param ontology the ontology to filter
 * @param properties a set of OWLObjectProperties to retain
 */
public static void filter(OWLOntology ontology, Set<OWLObjectProperty> properties) {
  logger.debug("Filtering ontology for axioms with ObjectProperties " + properties);

  OWLOntologyManager manager = ontology.getOWLOntologyManager();
  Set<OWLAxiom> axioms = ontology.getAxioms();
  logger.debug("Ontology has {} axioms before filtering", axioms.size());

  // For each axiom, get all its object properties,
  // then remove the properties that we're looking for.
  // If there are no object properties left, then we keep this axiom.
  // All annotation axioms, declarations, and subClass relations remains.
  for (OWLAxiom axiom : axioms) {
    Set<OWLObjectProperty> ps = axiom.getObjectPropertiesInSignature();
    ps.removeAll(properties);
    if (ps.size() > 0) {
      manager.removeAxiom(ontology, axiom);
    }
  }

  logger.debug("Ontology has {} axioms after filtering", ontology.getAxioms().size());
}
 
Example 2
Source File: NCBI2OWLTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void testSpecies(OWLOntology ontology) {
	IRI iri = IRI.create("http://purl.obolibrary.org/obo/NCBITaxon_species");
	OWLDataFactory df = ontology.getOWLOntologyManager().
		getOWLDataFactory();
	OWLClass taxon = df.getOWLClass(iri);
	assertTrue("Species class in signature",
		ontology.containsClassInSignature(iri));
	
	// Check axioms
	Set<OWLClassAxiom> axioms = ontology.getAxioms(taxon, Imports.EXCLUDED);
	assertEquals("Count class axioms", 1, axioms.size());
	assertEquals("SubClassOf(<http://purl.obolibrary.org/obo/NCBITaxon_species> <http://purl.obolibrary.org/obo/NCBITaxon#_taxonomic_rank>)", axioms.toArray()[0].toString());

	// Check annotations
	List<String> values = new ArrayList<String>();
	values.add("AnnotationAssertion(<http://www.geneontology.org/formats/oboInOwl#hasOBONamespace> <http://purl.obolibrary.org/obo/NCBITaxon_species> \"ncbi_taxonomy\"^^xsd:string)");
	values.add("AnnotationAssertion(rdfs:label <http://purl.obolibrary.org/obo/NCBITaxon_species> \"species\"^^xsd:string)");

	Set<OWLAnnotationAssertionAxiom> annotations = 
		ontology.getAnnotationAssertionAxioms(iri);
	assertEquals("Count annotations for Species", 2, annotations.size());

	checkAnnotations(annotations, values);
}
 
Example 3
Source File: NCBI2OWLTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void testExactSynonym(OWLOntology ontology) {
	IRI iri = IRI.create("http://www.geneontology.org/formats/oboInOwl#hasExactSynonym");
	OWLDataFactory df = ontology.getOWLOntologyManager().
		getOWLDataFactory();
	OWLAnnotationProperty property = df.getOWLAnnotationProperty(iri);
	assertTrue("Exact Synonym property in signature",
		ontology.containsAnnotationPropertyInSignature(iri));
	
	// Check axioms
	Set<OWLAnnotationAxiom> axioms = ontology.getAxioms(property, Imports.EXCLUDED);
	assertEquals("Count class axioms", 0, axioms.size());

	// Check annotations
	List<String> values = new ArrayList<String>();
	values.add("AnnotationAssertion(rdfs:label <http://www.geneontology.org/formats/oboInOwl#hasExactSynonym> \"has_exact_synonym\"^^xsd:string)");

	Set<OWLAnnotationAssertionAxiom> annotations = 
		ontology.getAnnotationAssertionAxioms(iri);
	assertEquals("Count annotations for Exact", 1, annotations.size());

	checkAnnotations(annotations, values);
}
 
Example 4
Source File: GAFOWLBridgeTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testConversion() throws Exception{
	ParserWrapper pw = new ParserWrapper();
	OWLOntology ont = pw.parse(getResourceIRIString("go_xp_predictor_test_subset.obo"));
	OWLGraphWrapper g = new OWLGraphWrapper(ont);
	g.addSupportOntology(pw.parse(getResourceIRIString("gorel.owl")));

	GafObjectsBuilder builder = new GafObjectsBuilder();

	GafDocument gafdoc = builder.buildDocument(getResource("xp_inference_test.gaf"));

	GAFOWLBridge bridge = new GAFOWLBridge(g);
	OWLOntology gafOnt = g.getManager().createOntology();
	bridge.setTargetOntology(gafOnt);
	bridge.translate(gafdoc);
	
	OWLDocumentFormat owlFormat = new RDFXMLDocumentFormat();
	g.getManager().saveOntology(gafOnt, owlFormat, IRI.create(new File("/tmp/gaf.owl")));
	
	for (OWLAxiom ax : gafOnt.getAxioms()) {
		LOG.info("AX:"+ax);
	}

}
 
Example 5
Source File: BasicAboxBridgeTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testConversion() throws Exception{
	ParserWrapper pw = new ParserWrapper();
	OWLOntology ont = pw.parse(getResourceIRIString("go_xp_predictor_test_subset.obo"));
	OWLGraphWrapper g = new OWLGraphWrapper(ont);
	g.addSupportOntology(pw.parse(getResourceIRIString("gorel.owl")));

	GafObjectsBuilder builder = new GafObjectsBuilder();

	GafDocument gafdoc = builder.buildDocument(getResource("xp_inference_test.gaf"));

	BasicABox bridge = new BasicABox(g);
	OWLOntology gafOnt = g.getManager().createOntology();
	bridge.setTargetOntology(gafOnt);
	bridge.translate(gafdoc);
	
	OWLDocumentFormat owlFormat = new RDFXMLDocumentFormat();
	g.getManager().saveOntology(gafOnt, owlFormat, IRI.create(new File("target/foo.owl")));
	
	for (OWLAxiom ax : gafOnt.getAxioms()) {
		LOG.info("AX:"+ax);
	}

}
 
Example 6
Source File: OWLGraphWrapperExtended.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Find all corresponding {@link OWLObject}s with an OBO-style alternate identifier.
 * <p>
 * WARNING: This methods scans all object annotations in all ontologies. 
 * This is an expensive method.
 * 
 * @return map of altId to OWLObject (never null)
 */
public Map<String, OWLObject> getAllOWLObjectsByAltId() {
	final Map<String, OWLObject> results = new HashMap<String, OWLObject>();
	final OWLAnnotationProperty altIdProperty = getAnnotationProperty(OboFormatTag.TAG_ALT_ID.getTag());
	if (altIdProperty == null) {
		return Collections.emptyMap();
	}
	for (OWLOntology o : getAllOntologies()) {
		Set<OWLAnnotationAssertionAxiom> aas = o.getAxioms(AxiomType.ANNOTATION_ASSERTION);
		for (OWLAnnotationAssertionAxiom aa : aas) {
			OWLAnnotationValue v = aa.getValue();
			OWLAnnotationProperty property = aa.getProperty();
			if (altIdProperty.equals(property) && v instanceof OWLLiteral) {
				String altId = ((OWLLiteral)v).getLiteral();
				OWLAnnotationSubject subject = aa.getSubject();
				if (subject instanceof IRI) {
					OWLObject obj = getOWLObject((IRI) subject);
					if (obj != null) {
						results.put(altId, obj);
					}
				}
			}
		}
	}
	return results;
}
 
Example 7
Source File: TemplatedTransformer.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Set<OWLOntologyChange> tr(OWLOntology o, Mapping m) {
	Set<OWLOntologyChange> chgs = new HashSet<OWLOntologyChange>();
	for (OWLAxiom ax : o.getAxioms()) {
		chgs.addAll(tr(ax, m));
	}
	return chgs;
}
 
Example 8
Source File: ReasonerUtil.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
Collection<OWLOntologyChange> removeAxioms(AxiomType<?> type) {
  Collection<OWLOntologyChange> removals = new HashSet<>();
  for (OWLOntology importedOnt: ont.getImportsClosure()) {
    Set<? extends OWLAxiom> axioms = importedOnt.getAxioms(type);
    removals.addAll(manager.removeAxioms(importedOnt, axioms));
  }
  return removals;
}
 
Example 9
Source File: CardinalityContraintsTools.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Remove the cardinality constraints, by removing the axioms and replacing
 * them with the weaker axioms without the constraints.
 * 
 * @param ontology
 */
public static void removeCardinalityConstraints(OWLOntology ontology) {
	CardinalityRemover remover = new CardinalityRemover(ontology);
	for(OWLAxiom axiom : ontology.getAxioms()) {
		axiom.accept(remover);
	}
}
 
Example 10
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 11
Source File: PredicateVariableExtractor.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extracts {@link PredicateVariableExtractor} rules.
 * 
 * @param ot ontology
 * @return extracted rules
 */
@Override
public List<Rule> extract(OWLOntology ot) {
	List<Rule> list = new ArrayList<>();
	// list of predicates in ontology
	List<String> ps = new ArrayList<>();
	ps.add(TOPOBJ);
	ps.add(TOPDATA);
	OWLEntity e;
	String op;
	// check all declarations
	for (OWLDeclarationAxiom a : ot.getAxioms(AxiomType.DECLARATION)) {
		e = a.getEntity();
		if (e.isOWLObjectProperty()) {
			// if it is a object property declaration, add it to the list
			// and also add it as subproperty of owl:topObjectProperty
			op = getString(e.asOWLObjectProperty());
			ps.add(op);
			list.add(new SubPropertyOf(op, TOPOBJ));
		} else if (e.isOWLDataProperty()) {
			// if it is a data property declaration, add it to the list
			// and also add it as subproperty of owl:topDataProperty
			op = getString(e.asOWLDataProperty());
			ps.add(op);
			list.add(new SubPropertyOf(op, TOPDATA));
		}
	}
	list.add(new PredicateVariable(ps));
	return list;
}
 
Example 12
Source File: AbstractOwlSim.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void setInformationContentFromOntology(OWLOntology o) {
	OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager();
	OWLDataFactory df = mgr.getOWLDataFactory();
	clearInformationContentCache();
	for (OWLAnnotationAssertionAxiom ax : o.getAxioms(AxiomType.ANNOTATION_ASSERTION)) {
		if (ax.getProperty().getIRI().toString().equals(icIRIString)) {
			OWLLiteral lit = (OWLLiteral) ax.getValue();
			OWLClass c = df.getOWLClass((IRI) ax.getSubject());
			Double v = lit.parseDouble();
			setInformtionContectForAttribute(c, v);
		}
	}
	assignDefaultInformationContentForAllClasses();
}
 
Example 13
Source File: StanzaToOWLConverterTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testConvert() throws Exception{
	OWLGraphWrapper  wrapper = getOBO2OWLOntologyWrapper("caro.obo");
	File f = getResource("GO.xrf_abbs");
	StanzaToOWLConverter sc = new StanzaToOWLConverter(wrapper);
	OWLOntology tgt = wrapper.getManager().createOntology();
	sc.config.targetOntology = tgt;
	sc.config.defaultPrefix = "http://x.org/";
	sc.parse(f);
	assertTrue(tgt.getAxiomCount() > 0);
	for (OWLAxiom ax : tgt.getAxioms()) {
		LOG.debug(ax);
	}
	
}
 
Example 14
Source File: CardinalityContraintsTools.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Find the axioms with cardinality constraints. Creates also the weaker
 * axioms as potential replacement.
 * 
 * @param ontology
 * @return reporter with the axiom potential changes
 */
public static CardinalityReporter findCardinalityConstraints(OWLOntology ontology) {
	CardinalityReporter reporter = new CardinalityReporter(ontology);
	for(OWLAxiom axiom : ontology.getAxioms()) {
		axiom.accept(reporter);
	}
	return reporter;
}
 
Example 15
Source File: OWLGraphWrapperBasic.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void mergeOntology(OWLOntology extOnt, LabelPolicy labelPolicy) throws OWLOntologyCreationException {
	OWLOntologyManager manager = getManager();
	LOG.info("Merging "+extOnt+" policy: "+labelPolicy);
	for (OWLAxiom axiom : extOnt.getAxioms()) {
		if (labelPolicy != LabelPolicy.ALLOW_DUPLICATES) {
			if (axiom instanceof OWLAnnotationAssertionAxiom) {
				OWLAnnotationAssertionAxiom aa = (OWLAnnotationAssertionAxiom)axiom;
				if (aa.getProperty().isLabel()) {
					OWLAnnotationSubject subj = aa.getSubject();
					if (subj instanceof IRI) {
						Optional<OWLLiteral> label = null;
						for (OWLAnnotationAssertionAxiom a1 : sourceOntology.getAnnotationAssertionAxioms(subj)) {
							if (a1.getProperty().isLabel()) {
								label = a1.getValue().asLiteral();
							}
						}
						if (label != null && label.isPresent()) {
							if (labelPolicy == LabelPolicy.PRESERVE_SOURCE) {
								LOG.info("Preserving existing label:" +subj+" "+label+" // ditching: "+axiom);
								continue;
							}
							if (labelPolicy == LabelPolicy.PRESERVE_EXT) {
								LOG.info("Replacing:" +subj+" "+label+" with: "+axiom);
								LOG.error("NOT IMPLEMENTED");
							}
						}
					}
				}
			}
		}
		manager.applyChange(new AddAxiom(sourceOntology, axiom));
	}
	for (OWLImportsDeclaration oid: extOnt.getImportsDeclarations()) {
		manager.applyChange(new AddImport(sourceOntology, oid));
	}
	addCommentToOntology(sourceOntology, "Includes "+summarizeOntology(extOnt));
}
 
Example 16
Source File: OWLAPIFunctionalSyntaxParser.java    From elk-reasoner with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Owl2ParserAxiomProcessor visitor)
		throws Owl2ParseException {
	// First, parse the ontology
	OWLOntology ontology = loadViaOWLAPI();
	// Second, convert it
	OwlConverter converter = OwlConverter.getInstance();

	for (OWLAxiom axiom : ontology.getAxioms()) {
		visitor.visit(converter.convert(axiom));
	}
}
 
Example 17
Source File: PropertyViewOntologyBuilderTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * In this test we filter view classes based on the individuals in the ontology
 * 
 * @throws IOException
 * @throws OWLOntologyCreationException
 * @throws OWLOntologyStorageException
 */
@Test
public void testPhenoViewWithIndividuals() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException {
	ParserWrapper pw = new ParserWrapper();
	OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
	OWLDataFactory df = manager.getOWLDataFactory();
	OWLOntology sourceOntol = pw.parseOWL(getResourceIRIString("q-in-e.omn"));

	OWLObjectProperty viewProperty = 
		df.getOWLObjectProperty(IRI.create("http://x.org#has_phenotype_inheres_in"));

	PropertyViewOntologyBuilder pvob = 
		new PropertyViewOntologyBuilder(sourceOntol,
				sourceOntol,
				viewProperty);

	pvob.setClassifyIndividuals(true);
	pvob.setFilterUnused(true);
	pvob.setViewLabelPrefix("involves ");
	pvob.setViewLabelSuffix("");
	pvob.setAssumeOBOStyleIRIs(false);
	//pvob.setUseOriginalClassIRIs(true);

	pvob.buildViewOntology(IRI.create("http://x.org"), IRI.create("http://y.org"));
	OWLOntology avo = pvob.getAssertedViewOntology();
	if (RENDER_ONTOLOGY_FLAG) {
		for (OWLAxiom a : avo.getAxioms()) {
			LOG.info("ASSERTED_VIEW_ONT: " + a);
		}
	}
	OWLReasonerFactory rf = new ElkReasonerFactory();
	OWLReasoner reasoner = rf.createReasoner(avo);
	try {
		OWLGraphWrapper g = new OWLGraphWrapper(pvob.getInferredViewOntology());
		OWLPrettyPrinter pp = new OWLPrettyPrinter(g);
		g.addSupportOntology(pvob.getAssertedViewOntology());
		LOG.info("Building inferred view");
		pvob.buildInferredViewOntology(reasoner);
		boolean ok1 = false;
		int numClassAssertions = 0;

		// iterate through all view entities - this should be the filtered set of view classes plus individuals.
		for (OWLEntity e : pvob.getViewEntities()) {
			if (RENDER_ONTOLOGY_FLAG) {
				LOG.info(" VE: " + e + " LABEL:" + g.getLabel(e));
			}
			if (e instanceof OWLClass) {
				if (g.getLabel(e) != null && g.getLabel(e).equals("involves limb")) {
					ok1 = true;
				}
			}
			else {
				if (e instanceof OWLNamedIndividual) {
					Set<OWLClassAssertionAxiom> caas = pvob.getInferredViewOntology().getClassAssertionAxioms((OWLNamedIndividual) e);

					for (OWLClassAssertionAxiom caa : caas) {
						if (RENDER_ONTOLOGY_FLAG) {
							LOG.info("  CAA:" + pp.render(caa));
						}
						numClassAssertions++;
					}	
				}

			}
		}
		assertTrue(ok1);
		LOG.info("class assertions:"+numClassAssertions);
		//assertEquals(12, numClassAssertions); // TODO - CHECK
		LOG.info(pvob.getViewEntities().size());
		//assertEquals(23, pvob.getViewEntities().size());
	}
	finally {
		reasoner.dispose();
	}
}
 
Example 18
Source File: AssertInferenceTool.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void assertAllInferences(OWLGraphWrapper graph, String idsInputFile) {
		final OWLOntology ontology = graph.getSourceOntology();
		final OWLOntologyManager manager = ontology.getOWLOntologyManager();
		final OWLDataFactory factory = manager.getOWLDataFactory();
		
		Set<String> ids = loadIdsInputFile(idsInputFile);
		
		final OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
		final OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
		try {
			logger.info("Start check all");
			// check all classes from the main ontology
			AllInferenceReport report = new AllInferenceReport();
			Set<OWLClass> classes = ontology.getClassesInSignature(Imports.EXCLUDED);
			int count = 0;
			int total = ids != null ? ids.size() : classes.size();
			int step = 100;
			for (final OWLClass owlClass : classes) {
				if (ids != null) {
					String id = graph.getIdentifier(owlClass);
					if (ids.contains(id) == false) {
						continue;
					}
				}
				count += 1;
				// get axioms for the current class
				Set<OWLClassAxiom> axioms = ontology.getAxioms(owlClass, Imports.EXCLUDED);
				
				handleAxioms(owlClass, axioms, ontology, manager, factory, reasoner, report);
//				handleAxioms2(owlClass, axioms, ontology, manager, factory, reasoner, report);
				if (count % step == 0) {
					logger.info("Current count "+count+" of "+total);
				}
			}
			PrintWriter writer = new PrintWriter(System.out);
			report.printReport(writer);
			writer.close();
		}
		finally {
			reasoner.dispose();
		}
	}
 
Example 19
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.");
    }
 
Example 20
Source File: AxiomAnnotationTools.java    From owltools with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Remove axiom annotations, which do not comply with the OBO-Basic level,
 * i.e. trailing qualifier values in OBO.
 * 
 * @param ontology
 */
public static void reduceAxiomAnnotationsToOboBasic(OWLOntology ontology) {
	for(OWLAxiom axiom : ontology.getAxioms()) {
		AxiomAnnotationTools.reduceAxiomAnnotationsToOboBasic(axiom, ontology);
	}
}