public OntologyBrowser(OWLOntology ontology, Set<String> rootsToRemove) { super(); this.ontology = ontology; this.rootConcept = "Thing"; this.buildTreeModel(); for (String concept : rootsToRemove) { DefaultMutableTreeNode node = getNodeFromName(concept); this.dtm.removeNodeFromParent(node); } this.setModel(this.dtm); // set the tree selection model DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel(); dtsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); this.setSelectionModel(dtsm); // set the tree renderer OntologyRenderer myRenderer = new OntologyRenderer(); this.setCellRenderer(myRenderer); this.setRootVisible(false); }
public OntologyBrowser(OWLOntology ontology, ImageIcon closedIcon, ImageIcon openedIcon) { super(); this.ontology = ontology; this.buildTreeModel(); this.setModel(this.dtm); // set the tree selection model DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel(); dtsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); this.setSelectionModel(dtsm); this.setRootVisible(false); // set the tree renderer OntologyRenderer myRenderer = new OntologyRenderer(); // Change the icon for closed nodes. myRenderer.setClosedIcon(closedIcon); // Change the icon for opened nodes. myRenderer.setOpenIcon(openedIcon); this.setCellRenderer(myRenderer); }
public static LoadedObjects open(File selectedFile, FileType... allowedFileType) { if (selectedFile == null) { selectedFile = IOUtility.selectFileToOpen(allowedFileType); } switch (IOUtility.getFileType(selectedFile)) { case ONTOLOGY: OWLOntology ontology = OWLImporter.loadOntologyFromFile(selectedFile); if (ontology != null) { return new LoadedObjects(selectedFile, ontology, OWLImporter.getShapes(ontology)); } break; case ANNOTATION: case UML: case QUERIES: case JSON: return new LoadedObjects(selectedFile, null, IOUtility.importJSON(selectedFile)); } return null; }
private SQLGeneratorExt createSQLGeneratorExt(OWLOntology ontology, OBDAModel inputOBDAModel) throws InvalidDataSourcesNumberException { //Get the data source Collection<OBDADataSource> sources = inputOBDAModel.getSources(); if (sources == null || !(sources.size() == 1)) throw new InvalidDataSourcesNumberException(sources.size()); OBDADataSource obdaSource = sources.iterator().next(); //END OF Get the data source DBMetadata metadata = this.getDBMetadata(); String jdbcClassName = obdaSource.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER); String jdbcDatabaseName = metadata.getDbmsVersion(); SQLDialectAdapter sqladapter = SQLAdapterFactory.getSQLDialectAdapter(jdbcClassName, jdbcDatabaseName); return new SQLGeneratorExt(metadata, sqladapter, this.isSqlGenerateReplace(), this.hasDistinctResultSet(), this.getUriMap()); }
/** * 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); } }
/** * Returns a list of rules extracted from the given OWL-2 ontology document. * @param in an ontology document as stream * @return a list of rules */ public static List<Rule> fromOntology(InputStream in) { try { // use OWL-API to get a OWLOntology document from source OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); manager.loadOntologyFromOntologyDocument(in); 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); } }
/** * Returns a list of rules extracted from the given OWL-2 ontology document. * @param ot an owl ontology object * @return list of rules */ public static List<Rule> fromOntology(OWLOntology ot) { ArrayList<Rule> list = new ArrayList<>(); List<Extractor> extractors = new ArrayList<>(); // create a list of extractors that will extract rules from the // given ontology extractors.add(new InverseObjectPropertiesExtractor()); extractors.add(new ObjectPropertyChainExtractor()); extractors.add(new PredicateVariableExtractor()); extractors.add(new SubClassOfExtractor()); extractors.add(new SubPropertyOfExtractor()); // call each extractor and accumulate rules for (Extractor extr : extractors) { list.addAll(extr.extract(ot)); } return list; }
/** * Open the OWL ontology (from the ontology resources of CartAGen) whose name * is passed as parameter. * @param name * @return * @throws OWLOntologyCreationException */ public static OWLOntology getOntologyFromName(String name) throws OWLOntologyCreationException { // create the URI from the name and the CartAGen ontologies folder path String uri = FOLDER_PATH + "/" + name + ".owl"; InputStream stream = OwlUtil.class.getResourceAsStream(uri); File file = new File(stream.toString()); String path = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf('\\')); path = path.replaceAll(new String("\\\\"), new String("//")); path = path + "//src/main//resources//ontologies//" + name + ".owl"; // create the ontology from the URI using an OWLOntologyManager OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); IRI physicalURI = IRI.create(new File(path)); OWLOntology ontology = manager .loadOntologyFromOntologyDocument(physicalURI); return ontology; }
/** * Train on resources of a given class. * * @param filename * @param strategy * @param classname * @return */ public static R2VModel train(String filename, TfidfFEXStrategy strategy, String classname) { OWLOntology o = getOntology(filename); R2VModel model = new R2VModel(o, strategy); for(OWLIndividual ind : getIndividuals(classname, o)) { model.add(ind.asOWLNamedIndividual()); } model.stringFeatures(); model.normalize(); return model; }
/** * @param filename * @return */ private static OWLOntology getOntology(String filename) { File file = new File(filename); OWLOntologyManager m = OWLManager.createOWLOntologyManager(); OWLOntology o; try { o = m.loadOntologyFromOntologyDocument(IRI.create(file.toURI())); } catch (OWLOntologyCreationException e) { fail("Cannot load ontology."); return null; } assertNotNull(o); return o; }
/** * @param superclass * @param o * @return */ private static Set<OWLIndividual> getIndividuals(String superclass, OWLOntology o) { OWLReasoner reasoner = PelletReasonerFactory.getInstance() .createReasoner(o); Set<OWLNamedIndividual> instances = reasoner.getInstances( OWL.Class(IRI.create(superclass)), false).getFlattened(); // filter out all owl:sameAs instances... Set<OWLIndividual> ind = new TreeSet<>(); for (OWLNamedIndividual i : instances) { ind.add(i); } logger.info("|I| = " + ind.size()); logger.debug("I = " + ind); return ind; }
protected void addPTBoxConstraints(OWLOntology ontology, PTBox ptbox, OWLOntologyManager manager, OWLDataFactory factory) { ConceptConverter converter = new ConceptConverter(ptbox.getClassicalKnowledgeBase(), factory); for (ConditionalConstraint cc : ptbox.getDefaultConstraints()) { OWLAnnotationProperty annProp = factory.getOWLAnnotationProperty( IRI.create(Constants.CERTAINTY_ANNOTATION_URI )); OWLAnnotationValue annValue = factory.getOWLStringLiteral( cc.getLowerBound() + ";" + cc.getUpperBound() ); OWLAnnotation annotation = factory.getOWLAnnotation( annProp, annValue ); OWLClassExpression clsEv = (OWLClassExpression)converter.convert( cc.getEvidence() ); OWLClassExpression clsCn = (OWLClassExpression)converter.convert( cc.getConclusion() ); OWLAxiom axiom = factory.getOWLSubClassOfAxiom( clsEv, clsCn, Collections.singleton( annotation ) ); try { manager.applyChange( new AddAxiom(ontology, axiom) ); } catch( OWLOntologyChangeException e ) { e.printStackTrace(); } } }
@Override public void read() throws IOException { InputStreamReader isr = new InputStreamReader(stream); BufferedReader reader = new BufferedReader(isr); OWLOntology ont = graph.getSourceOntology(); String row; if (graph.inferredEdgeBySource == null) { graph.inferredEdgeBySource = new HashMap<OWLObject,Set<OWLGraphEdge>>(); } while (true) { row = reader.readLine(); if (row == null) { break; } String[] vals = row.split("\t"); int len = vals.length; OWLObject src = getObject(vals[0]); Collection<OWLGraphEdge> edges = new HashSet<OWLGraphEdge>(); for (int i=1; i<len; i++) { OWLGraphEdge e = parseEdge(ont, src, vals[i]); edges.add(e); } graph.inferredEdgeBySource.put(src, new HashSet<OWLGraphEdge>(edges)); } }
@Test public void testReason() throws Exception { ParserWrapper pw = new ParserWrapper(); pw.getManager().getIRIMappers().add(new CatalogXmlIRIMapper(getResource("mooncat/eq-lattice/catalog-v001.xml"))); OWLOntology o = pw.parseOWL(getResourceIRIString("mooncat/eq-lattice/eq-with-imports.owl")); ProvenanceReasonerWrapper pr = new ProvenanceReasonerWrapper(o, new ElkReasonerFactory()); pr.reason(); // OWLEdge [c=<http://example.org/test/BCell-size>, p=<http://example.org/test/ImmuneCell-size>] REQUIRES: [http://example.org/test/auto, http://example.org/test/entity.owl] // OWLEdge [c=<http://example.org/test/Bone-size>, p=<http://example.org/test/Bone-morphology>] REQUIRES: [http://example.org/test/auto, http://example.org/test/quality.owl] assertEquals(143, pr.edges.size()); o.getOWLOntologyManager().saveOntology(o, new FileOutputStream("target/eq-inf.ttl")); }
/** * Test for {@link AxiomAnnotationTools#reduceAxiomAnnotationsToOboBasic(org.semanticweb.owlapi.model.OWLOntology)}. * * @throws Exception */ @Test public void testReduceAxiomAnnotationsToOboBasicOWLOntology() throws Exception { final File inputFile = getResource("qualifiers/with-qualifiers.obo"); final File referenceFile = getResource("qualifiers/no-qualifiers.obo"); OBOFormatParser p = new OBOFormatParser(); OBODoc inputOboDoc = p.parse(inputFile); Obo2Owl obo2Owl = new Obo2Owl(); OWLOntology owlOntology = obo2Owl.convert(inputOboDoc); Owl2Obo owl2Obo = new Owl2Obo(); // check round-trip first before removing equals(inputFile, owl2Obo.convert(owlOntology)); // remove axiom annotations AxiomAnnotationTools.reduceAxiomAnnotationsToOboBasic(owlOntology); equals(referenceFile, owl2Obo.convert(owlOntology)); }
/** * Print string representations of all the axioms in an ontology, * one axiom statement per line. Sorted lists of axioms can be used * to compare ontologies. * * @param ontology the ontology to print * @param outputPath the path for the output file * @throws IOException if it cannot write to the outputPath */ public static void printAxioms(OWLOntology ontology, String outputPath) throws IOException { logger.debug("Printing axioms..."); java.util.Set<OWLAxiom> axioms = ontology.getAxioms(); Iterator<OWLAxiom> iterator = axioms.iterator(); FileWriter fw = new FileWriter(outputPath); BufferedWriter bw = new BufferedWriter(fw); while(iterator.hasNext()) { OWLAxiom axiom = iterator.next(); bw.write(axiom.toString() + "\n"); } bw.close(); }
public Set<IRI> removeFact(ModelContainer model, OWLObjectPropertyExpression p, OWLIndividual i, OWLIndividual j, METADATA metadata) { OWLDataFactory f = model.getOWLDataFactory(); OWLOntology ont = model.getAboxOntology(); OWLAxiom toRemove = null; Set<IRI> iriSet = new HashSet<IRI>(); Set<OWLObjectPropertyAssertionAxiom> candidates = ont.getObjectPropertyAssertionAxioms(i); for (OWLObjectPropertyAssertionAxiom axiom : candidates) { if (p.equals(axiom.getProperty()) && j.equals(axiom.getObject())) { toRemove = axiom; extractEvidenceIRIValues(axiom.getAnnotations(), iriSet); break; } } if (toRemove == null) { // fall back solution toRemove = f.getOWLObjectPropertyAssertionAxiom(p, i, j); } removeAxiom(model, toRemove, metadata); return iriSet; }
@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")); }
@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"); }
public static InferenceProvider create(OWLReasoner r, OWLOntology ont) { Map<OWLNamedIndividual, Set<OWLClass>> inferredTypes = new HashMap<>(); boolean isConsistent = r.isConsistent(); if (isConsistent) { Set<OWLNamedIndividual> individuals = ont.getIndividualsInSignature(); for (OWLNamedIndividual individual : individuals) { Set<OWLClass> inferred = new HashSet<>(); Set<OWLClass> flattened = r.getTypes(individual, true).getFlattened(); for (OWLClass cls : flattened) { if (cls.isBuiltIn() == false) { inferred.add(cls); } } inferredTypes.put(individual, inferred); } } return new MapInferenceProvider(isConsistent, inferredTypes); }
@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)); }
/** * @param args * @throws OWLOntologyCreationException */ public static void main(String[] args) throws OWLOntologyCreationException { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); // Load your ontology. OWLOntology ont = manager.loadOntologyFromOntologyDocument(new File("/path/to/your/ontology/ontology.owl")); // Create an instance of ELK ElkProverFactory proverFactory = new ElkProverFactory(); OWLProver prover = proverFactory.createReasoner(ont); // Pre-compute classification prover.precomputeInferences(InferenceType.CLASS_HIERARCHY); // Pick the entailment for which we are interested in proofs OWLAxiom entailment = getEntailment(); // Get the inferences used to prove the entailment DynamicProof<? extends Inference<OWLAxiom>> proof = prover.getProof(entailment); // Now we can recursively request inferences and their premises. Print them to std.out in this example. unwindProof(proof, entailment); // Terminate the worker threads used by the reasoner. prover.dispose(); }
UnfoldingVisitor(Set<OWLClass> unfoldClasses, OWLOntology ontology) throws NonDeterministicUnfoldException { this.unfoldClasses = new HashMap<OWLClass, OWLClassExpression>(); factory = ontology.getOWLOntologyManager().getOWLDataFactory(); for(OWLClass owlClass : unfoldClasses) { Set<OWLEquivalentClassesAxiom> eqAxioms = ontology.getEquivalentClassesAxioms(owlClass); if (eqAxioms != null && !eqAxioms.isEmpty()) { if(eqAxioms.size() > 1) { throw new NonDeterministicUnfoldException("Non deterministic unfold for class: "+owlClass.getIRI()); } OWLEquivalentClassesAxiom eqAxiom = eqAxioms.iterator().next(); Set<OWLClassExpression> expressions = eqAxiom.getClassExpressionsMinus(owlClass); if (expressions.size() == 1) { this.unfoldClasses.put(owlClass, expressions.iterator().next()); } else if (expressions.size() > 1) { OWLClassExpression ce = factory.getOWLObjectIntersectionOf(expressions); this.unfoldClasses.put(owlClass, ce); } } } // TODO check that there are no cycles in the unfold expressions, otherwise this unfold will not terminate! }
public AnnotationEditor(OWLOntology _ontology, AnnotationEditorListener _listener) { super(_ontology); supportedFormats = new FileType[]{FileType.ONTOLOGY, FileType.UML, FileType.ANNOTATION}; listener = _listener; diagramPanel = new AnnotationDiagramPanel(this); initUI(); if (ontology != null) { diagramPanel.load(OWLImporter.getShapes(ontology)); } setTitle("Annotation Editor"); }
private void loadEditor(final UIPluginContext _context, final OWLOntology ontology) { //set context to use with listener method context = _context; context.getProgress().setIndeterminate(true); //display editor dialog with loaded ontology new AnnotationEditor(ontology, this).display(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); }
public void store(String name, OWLOntology ontology) { if (ontology != null) { //Create OWL Ontology in the context context.getProvidedObjectManager().createProvidedObject(name, ontology, OWLOntology.class, context); } else { context.log("OWL ontology is not created", MessageLevel.ERROR); } }
private void loadUMLEditor(final UIPluginContext _context, OWLOntology ontology) { //set context to use with listener method context = _context; context.getProgress().setIndeterminate(true); //display editor dialog with loaded ontology new UMLEditor(ontology, this).display(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); }