/** * 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); } }
/** * 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; }
/** * @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; }
/** * Creates a dictionary for use by the ConceptMapper that includes GO terms * from the namespaces defined in the namespacesToInclude set. * * @param namespacesToInclude * @param workDirectory * @param cleanWorkDirectory * @param synonymType * @return * @throws IOException * @throws OWLOntologyCreationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws OBOParseException */ public static File buildConceptMapperDictionary(EnumSet<GoNamespace> namespacesToInclude, File workDirectory, CleanDirectory cleanWorkDirectory, SynonymType synonymType) throws IOException, IllegalArgumentException, IllegalAccessException, OWLOntologyCreationException { if (namespacesToInclude.isEmpty()) return null; boolean doClean = cleanWorkDirectory.equals(CleanDirectory.YES); GeneOntologyClassIterator goIter = new GeneOntologyClassIterator(workDirectory, doClean); File geneOntologyOboFile = goIter.getGeneOntologyOboFile(); goIter.close(); return buildConceptMapperDictionary(namespacesToInclude, workDirectory, geneOntologyOboFile, doClean, synonymType); }
@Test public void testExactSynonymOnly_SO_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_SO_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.EXACT); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/SO_0000012\" canonical=\"scRNA_primary_transcript\">", "<variant base=\"scRNA_primary_transcript\"/>", "<variant base=\"scRNA primary transcript\"/>", "<variant base=\"scRNA primary transcript\"/>", // this entry ends up in there twice due to underscore removal "<variant base=\"scRNA transcript\"/>", "<variant base=\"small cytoplasmic RNA transcript\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); }
@Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); try { ontUtil = new OntologyUtil(ontologyFile); /* * check that the term to remove is in the ontology -- if it is not, * it could be a format issue */ OWLClass cls = ontUtil.getOWLClassFromId(termIdToRemove); if (cls == null) { String errorMessage = "Ontology term ID selected for removal is not in the given ontology. " + "This could be a formatting issue. Term selected for removal: " + termIdToRemove + " Example term ID from the ontology: " + ontUtil.getClassIterator().next().toStringID(); throw new ResourceInitializationException(new IllegalArgumentException(errorMessage)); } } catch (OWLOntologyCreationException e) { throw new ResourceInitializationException(e); } annotationDataExtractor = (AnnotationDataExtractor) ConstructorUtil .invokeConstructor(annotationDataExtractorClassName); }
@Override public InferenceProvider create(final ModelContainer model) throws OWLOntologyCreationException, InterruptedException { synchronized (model.getAboxOntology()) { InferenceProvider inferenceProvider = inferenceCache.get(model); if (inferenceProvider == null) { addMiss(); inferenceProvider = super.create(model); model.registerListener(new ModelChangeListenerImplementation(model)); inferenceCache.put(model, inferenceProvider); } else { addHit(); } return inferenceProvider; } }
@Deprecated public void deleteFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLIndividual i = resolveIndividual(Param.individualId); OWLIndividual j = resolveIndividual(Param.fillerId); OWLObjectProperty p = resolveObjectProperty(Param.propertyId); for (OWLObjectPropertyAssertionAxiom ax : ont.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION)) { if (ax.getSubject().equals(i)) { if (p == null || ax.getProperty().equals(p)) { if (j == null || ax.getObject().equals(j)) { removeAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j)); } } } } String jsonStr = ""; response.getWriter().write(jsonStr); }
@Test public void testUnion() throws OWLOntologyCreationException, IOException, FrameMergeException { OWLObject cls = gw.getOWLObjectByIdentifier("NCBITaxon:6239"); // C elegans OWLObject uc = gw.getOWLObjectByIdentifier("NCBITaxon_Union:0000005"); // C elegans Set<OWLGraphEdge> edges = gw.getOutgoingEdgesClosure(cls); // TODO - test includes union boolean ok = false; for (OWLGraphEdge e : edges) { System.out.println(e); OWLObject t = e.getTarget(); String tid = gw.getIdentifier(t); System.out.println(" "+tid); // Nematoda or Protostomia if ("NCBITaxon_Union:0000005".equals(tid)) { ok = true; } } assertTrue(ok); assertTrue(gw.getAncestorsReflexive(cls).contains(uc)); }
/** * Merge a specific ontology from the import closure into the main ontology. * Removes the import statement. * * @param ontologyIRI id of the ontology to merge * @throws OWLOntologyCreationException */ public void mergeSpecificImport(IRI ontologyIRI) throws OWLOntologyCreationException { OWLOntologyManager manager = getManager(); Set<OWLOntology> imports = sourceOntology.getImportsClosure(); for (OWLOntology o : imports) { if (o.equals(sourceOntology)) continue; Optional<IRI> currentIRI = o.getOntologyID().getOntologyIRI(); if (currentIRI.isPresent() && currentIRI.get().equals(ontologyIRI)) { String comment = "Includes "+summarizeOntology(o); LOG.info(comment); addCommentToOntology(sourceOntology, comment); manager.addAxioms(sourceOntology, o.getAxioms()); } } Set<OWLImportsDeclaration> oids = sourceOntology.getImportsDeclarations(); for (OWLImportsDeclaration oid : oids) { if (ontologyIRI.equals(oid.getIRI())) { RemoveImport ri = new RemoveImport(sourceOntology, oid); getManager().applyChange(ri); } } }
/** * Read a data file, create an OWL representation, and save an OWL file. * Create alternate identifiers from the merge.dmp file information * * @param inputPath the path to the input data file (e.g. taxonomy.dat) * @param outputPath the path to the output OWL file * (e.g. ncbi_taxonomy.owl). * @param mergeInfo the input stream of the merged information * @param citationInfo the input stream of the citation information * @param uniqueNames * @return OWL ontology * @throws IOException if the paths do not resolve * @throws OWLOntologyCreationException if OWLAPI fails to create an * empty ontology * @throws OWLOntologyStorageException if OWLAPI can't save the file */ public static OWLOntology convertToOWL(String inputPath, String outputPath, InputStream mergeInfo, InputStream citationInfo, Map<String, String> uniqueNames) throws IOException, OWLOntologyCreationException, OWLOntologyStorageException { File outputFile = new File(outputPath); IRI outputIRI = IRI.create(outputFile); OWLOntology ontology = convertToOWL(inputPath, uniqueNames); if (mergeInfo != null) { addAltIds(ontology, mergeInfo); } if (citationInfo != null) { addCitationInfo(ontology, citationInfo); } logger.debug("Saving ontology..."); ontology.getOWLOntologyManager().saveOntology( ontology, outputIRI); return ontology; }
/** * Classifies a given ontology and checks whether another ontology is * entailed by the former. * * @param premiseFile * ontology file to be classified and used as premise * @param conclusionFile * file with the conclusion * @throws FileNotFoundException * if the file was not found * @throws OWLOntologyCreationException * if the ontology could not be created * @throws OWLRendererException * if a renderer error occurs * @return <code>true</code> if and only if the premise ontology entails the * conclusion ontology */ public boolean checkEntailment(File premiseFile, File conclusionFile) throws OWLOntologyCreationException, OWLRendererException, FileNotFoundException { Objects.requireNonNull(premiseFile); Objects.requireNonNull(conclusionFile); logger.fine("starting jcel console ..."); OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); logger.fine("loading premise ontology using the OWL API ..."); OWLOntology premiseOntology = manager.loadOntologyFromOntologyDocument(premiseFile); logger.fine("loading conclusion ontology using the OWL API ..."); OWLOntology conclusionOntology = manager.loadOntologyFromOntologyDocument(conclusionFile); logger.fine("starting reasoner ..."); JcelReasoner reasoner = new JcelReasoner(premiseOntology, false); logger.fine("precomputing inferences ..."); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); boolean ret = conclusionOntology.getAxioms().stream().allMatch(axiom -> reasoner.isEntailed(axiom)); logger.fine("jcel console finished."); return ret; }
@Test public void testDiffInCommon() throws OWLOntologyCreationException { ParserWrapper pw = new ParserWrapper(); OWLOntology ont1 = pw.parseOWL(getResourceIRIString("difftest1.obo")); OWLOntology ont2 = pw.parseOWL(getResourceIRIString("difftest2.obo")); Diff diff = new Diff(); diff.ontology1 = ont1; diff.ontology2 = ont2; diff.isCompareClassesInCommon = true; DiffUtil.getDiff(diff); System.out.println(diff.ontology1remaining.getAxioms()); System.out.println(diff.ontology2remaining.getAxioms()); System.out.println(diff.intersectionOntology.getAxioms()); assertEquals(4, diff.intersectionOntology.getAxiomCount()); assertEquals(5, diff.ontology1remaining.getAxiomCount()); assertEquals(6, diff.ontology2remaining.getAxiomCount()); }
/** * Returns a list of example configurations based on a list of files. * * @param list * list of files * @return a list of example configurations based on a list of files * @throws IOException * if something goes wrong with I/O * @throws OWLOntologyCreationException * if something goes wrong with the creation of the ontologies */ public List<ExampleConfiguration> getOntologyAndNetworkFiles(List<String> list) throws IOException, OWLOntologyCreationException { Objects.requireNonNull(list); List<ExampleConfiguration> ret = new ArrayList<>(); List<String> owlFiles = getFilesWithExtension(list, OWL_EXTENSION); for (String fileName : owlFiles) { String fileNamePrefix = fileName.substring(0, fileName.length() - OWL_EXTENSION.length()); String bayesianNetworkFileName = fileNamePrefix + NETWORK_EXTENSION; String queryFileName = fileNamePrefix + QUERY_EXTENSION; String owlOntologyName = fileName; OWLOntology owlOntology = readOntology(getInputStreamForFile(owlOntologyName)); String bayesianNetwork = getFile(getInputStreamForFile(bayesianNetworkFileName)); String query = getFile(getInputStreamForFile(queryFileName)); ExampleConfiguration exampleConf = new ExampleConfigurationImpl(getFileName(fileNamePrefix), owlOntologyName, owlOntology, bayesianNetworkFileName, bayesianNetwork, query); ret.add(exampleConf); } return ret; }
public static void main(String[] args) throws OWLOntologyCreationException { // Creation of a new Querier = Motor running the query System.out.println("Initialization of the querier..."); QueryingWithNamedClasses querier = new QueryingWithNamedClasses(); // Actual query: // "In our ontology, what are the subclasses of the named class MeatEater?" // It will work only if you use a reference to a class already present // in your ontology (named class). Set<OWLClass> results = querier.getSubClasses("MeatEater"); // The result is the set of classes satisfying the query. for (OWLClass owlClass : results) { // Just iterates over it and print the name of the class System.out.println("Subclass: " + querier.shortFormProvider.getShortForm(owlClass)); } }
@Test public void testDiffUnannotatedAll() throws OWLOntologyCreationException { ParserWrapper pw = new ParserWrapper(); OWLOntology ont1 = pw.parseOWL(getResourceIRIString("difftest1.obo")); OWLOntology ont2 = pw.parseOWL(getResourceIRIString("difftest2.obo")); Diff diff = new Diff(); diff.ontology1 = ont1; diff.ontology2 = ont2; diff.isCompareClassesInCommon = false; diff.isCompareUnannotatedForm = true; DiffUtil.getDiff(diff); System.out.println(diff.ontology1.getAxioms()); System.out.println(diff.ontology2.getAxioms()); System.out.println(diff.ontology1remaining.getAxioms()); System.out.println(diff.ontology2remaining.getAxioms()); System.out.println(diff.intersectionOntology.getAxioms()); assertEquals(8, diff.intersectionOntology.getAxiomCount()); assertEquals(10, diff.ontology1remaining.getAxiomCount()); assertEquals(6, diff.ontology2remaining.getAxiomCount()); }
/** * Keeps a count of the size of the extracted module from a randomly chosen * OWL class. This process can be repeated several times, but the OWL * classes are not necessarily distinct. * * @param ontologyFileName * file name of ontology * @param repetitions * number of times to run the module extraction * @param countFileName * file name of the results * @throws IOException * if something went wrong with I/O * @throws OWLException * if something went wrong when using the OWL API */ public void countRandom(String ontologyFileName, int repetitions, String countFileName) throws IOException, OWLException { Objects.requireNonNull(ontologyFileName); OWLOntology owlOntology = ProcessorConfigurationImpl.readOntology(new FileInputStream(ontologyFileName)); List<OWLClass> list = new ArrayList<>(); list.addAll(owlOntology.getClassesInSignature()); IntStream.range(0, repetitions).forEach(index -> { OWLClass chosenOwlClass = list.get((new Random()).nextInt(list.size())); Set<OWLClass> signature = Collections.singleton(chosenOwlClass); try { appendPair(countFileName, chosenOwlClass, extractModule(owlOntology, signature).getAxiomCount()); } catch (IOException | OWLOntologyCreationException e) { throw new RuntimeException(e); } }); }
/** * @throws OWLOntologyCreationException * if something goes wrong with the ontology creation */ @Test public void testTinyOntology8() throws OWLOntologyCreationException { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLDataFactory factory = manager.getOWLDataFactory(); Set<OWLAxiom> axiomSet = new HashSet<>(); OWLClass a = createNewClass(factory, "A"); OWLClass b = createNewClass(factory, "B"); OWLClass ab = createNewClass(factory, "AB"); Set<OWLClass> aAndBSet = new HashSet<>(); aAndBSet.add(a); aAndBSet.add(b); OWLClassExpression aAndB = factory.getOWLObjectIntersectionOf(aAndBSet); axiomSet.add(factory.getOWLEquivalentClassesAxiom(ab, aAndB)); OWLOntology ontology = manager.createOntology(axiomSet); JcelReasonerFactory reasonerFactory = new JcelReasonerFactory(); OWLReasoner reasoner = reasonerFactory.createReasoner(ontology); Set<OWLClass> expectedSet = new HashSet<>(); expectedSet.add(ab); Node<OWLClass> expected = new OWLClassNode(expectedSet); Assert.assertEquals(expected, reasoner.getEquivalentClasses(ab)); Assert.assertEquals(expected, reasoner.getEquivalentClasses(aAndB)); }
/** * Params: id * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException * @throws OWLParserException */ public void getAxiomsCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, OWLParserException { headerOWL(); boolean direct = getParamAsBoolean(Param.direct, false); OWLObject obj = this.resolveEntity(); LOG.info("finding axioms about: "+obj); Set<OWLAxiom> axioms = new HashSet<OWLAxiom>(); if (obj instanceof OWLClass) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLClass)obj, Imports.EXCLUDED)); } if (obj instanceof OWLIndividual) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLIndividual)obj, Imports.EXCLUDED)); } if (obj instanceof OWLObjectProperty) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLObjectProperty)obj, Imports.EXCLUDED)); } for (OWLAxiom ax : axioms) { output(ax); } }
@Bean @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.INTERFACES) public OWLMutableOntology owlOntology(PrefixManager prefixManager) throws OWLOntologyCreationException { if (prefixManager.getDefaultPrefix() == null) { throw new IllegalStateException("Default ontology prefix must not be null."); } OWLOntologyManager ontologyManager = OWLManager.createOWLOntologyManager(); // Cast to a mutable ontology to pass OWLApi's strange checks return (OWLMutableOntology) ontologyManager.createOntology(IRI.create(prefixManager.getDefaultPrefix())); }
public OWLAPIContainer(URI filename) throws OWLOntologyCreationException { try { this.filename = filename; manager = OWLManager.createOWLOntologyManager(); df = manager.getOWLDataFactory(); ontology = manager.loadOntologyFromOntologyDocument( new FileDocumentSource(new File(filename.getPath()))); System.out.println("Loaded"); StructuralReasonerFactory reasonerFact = new StructuralReasonerFactory(); reasoner = reasonerFact.createReasoner(ontology); System.out.println("Reasoned"); // Pour eviter un long calcul getAllLanguageInLabels(); System.out.println("Found"); // try { // System.out.println("Let's try Sesame"); // OwlTripleStore ts = Utilities.getOwlTripleStore(ontology, true); // Repository sesame_repo = ts.getRepository(); // RepositoryConnection sesame_connect = sesame_repo.getConnection(); // System.out.println("I have: "+sesame_connect.size()+" statements"); // } catch (RepositoryException e) { // System.err.println("Sesame Error!!!!"); // e.printStackTrace(); } catch(RuntimeException e) { e.printStackTrace(); throw e; } }
@Test public void testOWLXML() throws URISyntaxException, OWLOntologyCreationException { URI filename = TestContainer.class.getResource("TestOneConceptXml.owl").toURI(); DOEOWLContainer container = new DOEOWLContainer(filename); assertEquals(container.getAllConcepts().size(), 1); assertEquals(container.getAllLanguageInLabels(), Sets.newHashSet()); }
@Test public void testOWLTurtle() throws URISyntaxException, OWLOntologyCreationException { URI filename = TestContainer.class.getResource("TestOneConceptTurtle.owl").toURI(); DOEOWLContainer container = new DOEOWLContainer(filename); assertEquals(container.getAllConcepts().size(), 1); assertEquals(container.getAllLanguageInLabels(), Sets.newHashSet()); }
public StatisticalFunctionalityDetector(File ontologyFile, double threshold) { try { OWLOntologyManager man = OWLManager.createOWLOntologyManager(); ontology = man.loadOntologyFromOntologyDocument(ontologyFile); dataFactory = man.getOWLDataFactory(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } this.threshold = threshold; }
public StatisticalFunctionalityDetector(InputStream is, double threshold) { try { OWLOntologyManager man = OWLManager.createOWLOntologyManager(); ontology = man.loadOntologyFromOntologyDocument(is); dataFactory = man.getOWLDataFactory(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } this.threshold = threshold; }
public String getLabel(String entity){ String label= " "; try{ //Create OWL class for entity OWLClass entityClass = OWL.Class(entity); //Try to load ontology into OWLOntology object. If it fails, an exception is generated OWLOntology ontology = OWL.manager.loadOntologyFromOntologyDocument(entityClass.getIRI()); //Extract annotations associated to the OWL class Set<OWLAnnotation> annotations = entityClass.getAnnotations(ontology); //Remove ontology from manager OWL.manager.removeOntology(ontology); //For each annotation, if it is a label, set variable "label" Iterator it = annotations.iterator(); while(it.hasNext()){ OWLAnnotation annotation = (OWLAnnotation) it.next(); if(annotation.getProperty().isLabel()) label = annotation.getValue().toString().split("\"")[1]; } }catch(OWLOntologyCreationException ex){ return label; } return label; }
@Test public void testExactSynonymOnly_CL_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_CL_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.EXACT); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000000\" canonical=\"cell\">", "<variant base=\"cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000009\" canonical=\"fusiform initial\">", "<variant base=\"fusiform initial\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000041\" canonical=\"mature eosinophil\">", "<variant base=\"mature eosinophil\"/>", "<variant base=\"mature eosinocyte\"/>", "<variant base=\"mature eosinophil leucocyte\"/>", "<variant base=\"mature eosinophil leukocyte\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); }
@Test public void testIncludeAllSynonyms_CL_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_CL_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.ALL); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000000\" canonical=\"cell\">", "<variant base=\"cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000009\" canonical=\"fusiform initial\">", "<variant base=\"fusiform initial\"/>", "<variant base=\"xylem initial\"/>", "<variant base=\"xylem mother cell\"/>", "<variant base=\"xylem mother cell activity\"/>", "<variant base=\"xylem mother cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000041\" canonical=\"mature eosinophil\">", "<variant base=\"mature eosinophil\"/>", "<variant base=\"mature eosinocyte\"/>", "<variant base=\"mature eosinophil leucocyte\"/>", "<variant base=\"mature eosinophil leukocyte\"/>", "<variant base=\"polymorphonuclear leucocyte\"/>", "<variant base=\"polymorphonuclear leukocyte\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); }
public void getAnnotationSufficiencyScoreCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Specificity score for a set of annotations"); return; } headerText(); OwlSim sos = getOWLSim(); Set<OWLClass> atts = this.resolveClassList(Param.a); LOG.info("Calculating AnnotationSufficiency score for "+atts.toString()); SimJSONEngine sj = new SimJSONEngine(graph,sos); String jsonStr = sj.getAnnotationSufficiencyScore(atts); LOG.info("Finished getAnnotationSufficiencyScore"); response.setContentType("application/json"); response.getWriter().write(jsonStr); }
/** * Testing loading of ontologies that have no axioms (but possibly import * declarations). * * @see <a * href="http://code.google.com/p/elk-reasoner/issues/detail?id=7">Issue 7<a> * @throws OWLOntologyCreationException * @throws URISyntaxException */ @Test public void testImport() throws OWLOntologyCreationException, URISyntaxException { OWLOntologyManager man = TestOWLManager.createOWLOntologyManager(); // loading the root ontology OWLOntology root = loadOntology(man, "root.owl"); // Create an ELK reasoner. OWLReasonerFactory reasonerFactory = new ElkReasonerFactory(); OWLReasoner reasoner = reasonerFactory.createReasoner(root); try { // statistics about the root ontology assertEquals(root.getAxiomCount(), 0); // all two ontologies should be in the closure assertEquals(root.getImportsClosure().size(), 2); // all axioms from two ontologies should be in the closure assertEquals(getAxioms(root).size(), 0); // reasoner queries -- all subclasses are there reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } finally { reasoner.dispose(); } }
/** * Test the method {@link OWLGraphWrapperEdgesExtended#clearCachedEdges()}. */ @Test public void shouldClearCachedEdges() throws OWLOntologyCreationException, OBOFormatParserException, IOException { ParserWrapper parserWrapper = new ParserWrapper(); OWLOntology ont = parserWrapper.parse(this.getClass().getResource( "/graph/gciRelRetrieval.obo").getFile()); OWLGraphWrapper wrapper = new OWLGraphWrapper(ont); OWLClass cls1 = wrapper.getOWLClassByIdentifier("ID:1"); OWLClass cls2 = wrapper.getOWLClassByIdentifier("ID:2"); //get GCI relations, this will load the cache assertEquals("Incorrect number of gci_relations returned", 2, wrapper.getGCIOutgoingEdges(cls2).size()); //delete a gci_relation, without clearing the cache ont.getOWLOntologyManager().removeAxioms(ont, wrapper.getGCIOutgoingEdges(cls2).iterator().next().getAxioms()); //same number of axioms seen assertEquals("Incorrect number of gci_relations returned", 2, wrapper.getGCIOutgoingEdges(cls2).size()); assertEquals("Incorrect number of gci_relations returned", 2, wrapper.getGCIIncomingEdges(cls1).size()); //clear cache, we should see the change wrapper.clearCachedEdges(); assertEquals("Incorrect number of gci_relations returned", 1, wrapper.getGCIOutgoingEdges(cls2).size()); assertEquals("Incorrect number of gci_relations returned", 1, wrapper.getGCIIncomingEdges(cls1).size()); }
public void testReasoner() throws OWLOntologyCreationException { boolean bufferingMode = reasoner.getBufferingMode().equals( BufferingMode.BUFFERING); remove(); if (bufferingMode) { // the changes are still not yet taken into account testPresent(); } else { // the changes are taken into account testAbsent(); } // this should take into account the changes for reasoning queries reasoner.flush(); testAbsent(); add(); reasoner.flush(); remove(); if (bufferingMode) { // the reasoner should reflect only changes until the last flush() testPresent(); } else { // the reasoner should reflect all changes testAbsent(); } // take into account all changes reasoner.flush(); testAbsent(); // Terminate the reasoner. reasoner.dispose(); }
/** * Test the method {@link OWLGraphWrapperEdgesExtended#getAncestorsThroughIsA(OWLObject)} and * {@link OWLGraphWrapperEdgesExtended#getDescendantsThroughIsA(OWLObject)} * @throws IOException * @throws OBOFormatParserException * @throws OWLOntologyCreationException */ @Test public void shouldGetIsARelatives() throws OWLOntologyCreationException, OBOFormatParserException, IOException { ParserWrapper parserWrapper = new ParserWrapper(); OWLOntology ont = parserWrapper.parse(OWLGraphWrapperEdgesExtendedTest.class.getResource( "/graph/is_a_ancestors_test.obo").getFile()); OWLGraphWrapper wrapper = new OWLGraphWrapper(ont); OWLClass cls1 = wrapper.getOWLClassByIdentifier("FOO:0001"); OWLClass cls2 = wrapper.getOWLClassByIdentifier("FOO:0002"); OWLClass cls3 = wrapper.getOWLClassByIdentifier("FOO:0003"); OWLClass cls4 = wrapper.getOWLClassByIdentifier("FOO:0004"); Set<OWLClass> expectedAncestors = new HashSet<OWLClass>(); expectedAncestors.add(cls2); expectedAncestors.add(cls1); assertEquals("Incorrect ancestors through is_a returned", expectedAncestors, wrapper.getAncestorsThroughIsA(cls3)); expectedAncestors = new HashSet<OWLClass>(); assertEquals("Incorrect ancestors through is_a returned", expectedAncestors, wrapper.getAncestorsThroughIsA(cls4)); Set<OWLClass> expectedDescendants = new HashSet<OWLClass>(); expectedDescendants.add(cls2); expectedDescendants.add(cls3); assertEquals("Incorrect desendants through is_a returned", expectedDescendants, wrapper.getDescendantsThroughIsA(cls1)); }
/** * Create the GCIs for BioChEBI. Add the axioms into the given ontology graph. * * @param graph * @param ignoredSubset optional subset for ignored classes * @throws OWLOntologyCreationException */ public static void createBioChebi(OWLGraphWrapper graph, String ignoredSubset) throws OWLOntologyCreationException { Set<OWLClass> ignoredClasses = null; if (ignoredSubset != null) { ignoredClasses = new HashSet<OWLClass>(); for(OWLClass cls : graph.getAllOWLClasses()) { List<String> subsets = graph.getSubsets(cls); if (subsets.contains(ignoredSubset)) { ignoredClasses.add(cls); } } } createBioChebi(graph, ignoredClasses); }
ModelContainer createModel(String userId, Set<String> providerGroups, UndoMetadata token, VariableResolver resolver, JsonAnnotation[] annotationValues) throws UnknownIdentifierException, OWLOntologyCreationException { ModelContainer model = m3.generateBlankModel(token); Set<OWLAnnotation> annotations = extract(annotationValues, userId, providerGroups, resolver, model); annotations = addDefaultModelState(annotations, model.getOWLDataFactory()); if (annotations != null) { m3.addModelAnnotations(model, annotations, token); } updateModelAnnotations(model, userId, providerGroups, token, m3); // Disallow undo of initial annotations m3.clearUndoHistory(model.getModelId()); return model; }
/** * Creates a "fake" individual for every class. * * ABox IRI = TBox IRI + suffix * * if suffix == null, then we are punning * * @param srcOnt * @param iriSuffix * @throws OWLOntologyCreationException */ public static void makeDefaultIndividuals(OWLOntology srcOnt, String iriSuffix) throws OWLOntologyCreationException { OWLOntologyManager m = srcOnt.getOWLOntologyManager(); OWLDataFactory df = m.getOWLDataFactory(); for (OWLClass c : srcOnt.getClassesInSignature(Imports.INCLUDED)) { IRI iri; if (iriSuffix == null || iriSuffix.equals("")) iri = c.getIRI(); else iri = IRI.create(c.getIRI().toString()+iriSuffix); OWLNamedIndividual ind = df.getOWLNamedIndividual(iri); m.addAxiom(srcOnt, df.getOWLDeclarationAxiom(ind)); m.addAxiom(srcOnt, df.getOWLClassAssertionAxiom(c, ind)); } }
@Test public void testMerge() throws OWLOntologyCreationException, IOException, IncoherentOntologyException, OWLOntologyStorageException { ParserWrapper pw = new ParserWrapper(); OWLGraphWrapper g = pw.parseToOWLGraph(getResourceIRIString("equivalence-set-merge-util-test.obo")); OWLOntology ont1 = g.getSourceOntology(); ElkReasonerFactory rf = new ElkReasonerFactory(); OWLReasoner reasoner = rf.createReasoner(ont1); EquivalenceSetMergeUtil esmu = new EquivalenceSetMergeUtil(g, reasoner); esmu.setPrefixScore("A", 8.0); esmu.setPrefixScore("B", 6.0); esmu.setPrefixScore("C", 4.0); OWLAnnotationProperty lp = g.getDataFactory().getOWLAnnotationProperty( OWLRDFVocabulary.RDFS_LABEL.getIRI() ); esmu.setPropertyPrefixScore( lp, "C", 5.0); esmu.setPropertyPrefixScore( lp, "B", 4.0); esmu.setPropertyPrefixScore( lp, "A", 3.0); OWLAnnotationProperty dp = g.getDataFactory().getOWLAnnotationProperty( Obo2OWLVocabulary.IRI_IAO_0000115.getIRI() ); esmu.setPropertyPrefixScore( dp, "B", 5.0); esmu.setPropertyPrefixScore( dp, "A", 4.0); esmu.setPropertyPrefixScore( dp, "C", 3.0); esmu.setRemoveAxiomatizedXRefs(true); esmu.merge(); OWLDocumentFormat fmt = new OBODocumentFormat(); pw.saveOWL(g.getSourceOntology(), "target/esmu.owl"); //pw.setCheckOboDoc(false); pw.saveOWL(g.getSourceOntology(), fmt, "target/esmu.obo"); OWLOntology ont2 = pw.parseOWL(getResourceIRIString("equivalence-set-merge-util-expected.obo")); assertEquals(0, compare(ont1, ont2)); }
/** * visualize using QuickGO graphdraw. * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException */ public void qvizCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { String fmt = "png"; headerImage(fmt); GraphicsConfig gfxCfg = new GraphicsConfig(); Set<OWLObject> objs = resolveEntityList(); OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(graph); r.graphicsConfig = gfxCfg; r.addObjects(objs); r.renderImage(fmt, response.getOutputStream()); }