def get_files(): files_name = os.listdir(INSTANCES_FOLDER) onto_base = get_ontology("/home/marjorie/Bureau/uploads/ontology/Tbox.owl").load() if len(files_name) != 0: for instance in files_name: onto_base = get_ontology(INSTANCES_FOLDER + instance).load() continue
def find_bad_smells_argparse(args): if not (os.path.exists(P_ONTO_PATH) and os.path.isfile(P_ONTO_PATH)): print('Ontology "%s" does not exist ...' % os.path.basename(P_ONTO_PATH)) sys.exit(0) get_ontology(P_ONTO_PATH).load() find_bad_smells()
def test_parse_ontology(): """ If the ontology does not contains any class the parse_ontology function should return [] If the ontology contains any class the parse_ontology function should return a list with the ontology terms """ ontology = get_ontology('http://purl.obolibrary.org/obo/pizza.owl') gene_ontology = get_ontology( 'http://www.geneontology.org/formats/oboInOwl#') obo = get_ontology('http://purl.obolibrary.org/obo/') ontology_terms = parse_ontology(ontology) assert ontology_terms == [] with ontology: class Pizza(Thing): pass class HawaiianPizza(Pizza): pass with obo: class IAO_0000115(AnnotationProperty): pass with gene_ontology: class hasExactSynonym(AnnotationProperty): pass Pizza.label = 'Pizza' HawaiianPizza.label = 'Hawaiian Pizza' Pizza.IAO_0000115.append('Italian dish') HawaiianPizza.IAO_0000115.append( 'Controversial Italian dish with pineapple') HawaiianPizza.hasExactSynonym.append('Ham and pineapple pizza') ontology_terms = parse_ontology(ontology) assert ontology_terms == [{ 'ontologyId': 'pizza', 'ontologyTermId': 'Pizza', 'label': ['Pizza'], 'description': ['Italian dish'], 'synonyms': [], 'parents': ['Thing'], 'children': ['HawaiianPizza'] }, { 'ontologyId': 'pizza', 'ontologyTermId': 'HawaiianPizza', 'label': ['Hawaiian Pizza'], 'description': ['Controversial Italian dish with pineapple'], 'synonyms': ['Ham and pineapple pizza'], 'parents': ['Pizza'], 'children': [] }]
def load_ontology_modules(): global model_asset, model_fmea_iso, model_functional_system, model_iso onto_path.append("./owl-files") model_asset = get_ontology("asset.owl").load() model_fmea_iso = get_ontology("fmea-iso.owl").load() model_functional_system = get_ontology( "functional-system-ontology.owl").load() model_iso = get_ontology("LIS-14.owl").load() return model_asset, model_fmea_iso, model_functional_system, model_iso
def parse(file: str): onto = owl.get_ontology(file) onto.load() kb = get_kb(onto) pbox_restrictions = pbox_parser.get_restrictions(onto) return kb, pbox_restrictions
def main(): ontology = owl.get_ontology("./root-ontology.owl").load() print() for instrument in get_MIDI_instruments(): create_instrument_individual(ontology, instrument[1], instrument[0]) print_onto(ontology) ontology.save("./root-ontology.owl")
def __init__(self, *args, onto_uri=None, **kwargs): super().__init__(*args, **kwargs) self.port = None self.subgraph = None self.bel_graph = None self.url = "localhost:" self.jid_domain = "@gtirouter.dsic.upv.es" self.presence.approve_all = True self.source = ColumnDataSource(dict(iterations=[], values=[])) self.new_data = dict(iterations=[], values=[]) self.avail_contacts = {} self.avail_observers = [] self.onto_uri = onto_uri if onto_uri != None: self.onto = owl.get_ontology(onto_uri).load() print("Ontology: ", onto_uri) self.bel_graph = nx.Graph() self.bel_graph.add_nodes_from(list(self.onto.classes())) print("Belief graph created from: ", list(self.onto.classes())) print("Node: ", self.bel_graph.nodes()) self.avail_mutex = aioLock()
def loadOntology(self, reasoner=Reasoner.NONE, memory_java="10240"): # self.world = World() # Method from owlready self.onto = get_ontology(self.urionto).load() # self.onto = self.world.get_ontology(self.urionto).load() # self.onto.load() # self.classifiedOnto = get_ontology(self.urionto + '_classified') owlready2.reasoning.JAVA_MEMORY = memory_java owlready2.set_log_level(9) if reasoner == Reasoner.PELLET: try: with self.onto: # it does add inferences to ontology # Is this wrt data assertions? Check if necessary # infer_property_values = True, infer_data_property_values = True logging.info("Classifying ontology with Pellet...") sync_reasoner_pellet( ) # it does add inferences to ontology unsat = len(list(self.onto.inconsistent_classes())) logging.info("Ontology successfully classified.") if unsat > 0: logging.warning( f"There are {str(unsat)} unsatisfiable classes: {list(self.onto.inconsistent_classes())}" ) except Exception: logging.info("Classifying with Pellet failed.") elif reasoner == Reasoner.HERMIT: try: with self.onto: # it does add inferences to ontology logging.info("Classifying ontology with HermiT...") sync_reasoner() # HermiT doe snot work very well.... unsat = len(list(self.onto.inconsistent_classes())) logging.info("Ontology successfully classified.") if unsat > 0: logging.warning( f"There are {str(unsat)} unsatisfiable classes: {list(self.onto.inconsistent_classes())}" ) return f"{str(unsat)} unsatisfiable classes: {list(self.onto.inconsistent_classes())}" except Exception: logging.info("Classifying with HermiT failed.") # End Classification # report problem with unsat (Nothing not declared....) # print(list(self.onto.inconsistent_classes())) self.graph = default_world.as_rdflib_graph() logging.info("There are {} triples in the ontology".format( len(self.graph)))
def test_templateDriver(self): """Function to test the TemplateDriver functionality of the templating engine. Validates that the 'cv' template can be rendered. """ # Importing CV template cv_template = precis.templating.PrecisTemplate( template_folder=TestConfig.template_cv ) # Loading user ontology user_ont = get_ontology(TestConfig.sample_rdf_data).load() # Casting to RDFLib graph (for template driver) user_graph = default_world.as_rdflib_graph() # Loading user preferences (for the template) user_prefs = open(TestConfig.template_prefs, 'r') # Instantiating template driver driver = precis.templating.TemplateDriver( template=cv_template, user_ont=user_ont, user_graph=user_graph, user_prefs=user_prefs ) with open(TestConfig.template_cv_out, 'w') as f: f.write(driver.buildTemplate())
def init_onto(): import owlready2 as ow import pandas as pd onto = ow.get_ontology(main_onto_name) vivoNS = onto.get_namespace("http://vivoweb.org/ontology/core") onto.load() return onto, vivoNS
def updateConcepts(docId, ontoId, concepts): log("Call to updateConcepts()") import coruja_database ontopath = coruja_database.getOntology(str(ontoId)) import owlready2 owlready2.default_world.ontologies.clear() onto = owlready2.get_ontology("file://" + ontopath) log("updateConcepts(): Onto world debug after load: " + str(onto.world.ontologies)) try: onto.load() log("updateConcepts(): Load ontology " + ontopath) except: log("updateConcepts(): Error loading ontology " + ontopath) return 0 log("updateConcepts(): Onto world debug: " + str(onto.world.ontologies)) log("updateConcepts(): Searching for " + onto.base_iri + str(docId)) status = 1 result = onto.search(iri=onto.base_iri + str(docId)) if (len(result) > 0): document = result[0] ontoConcepts = document.documentHasConcept keepConcepts = [] if len(ontoConcepts) > 0: for concept in ontoConcepts: if concept.name in concepts: keepConcepts.append(concept) else: log("updateConcepts(): Deleting concept: " + concept.name) document.documentHasConcept = keepConcepts else: log("updateConcepts(): No concepts found") status = 0 else: status = 0 log("updateConcepts(): Document not found id=" + str(docId)) if status == 1: try: onto_file = open(ontopath, 'wb+') #onto.save(file=ontopath, format="rdfxml") onto.save(file=onto_file, format="rdfxml") onto_file.flush() onto_file.close() del onto_file log("updateConcepts(): Saved ontology to " + ontopath) except: log("updateConcepts(): Error saving ontology " + ontopath) status = 0 else: log("updateConcepts(): Empty ontology loaded " + ontopath) try: log("updateConcepts(): Destroying ontology " + onto.base_iri) onto.destroy() del onto del owlready2 except: log("updateConcepts(): Error destroying ontology:" + onto.base_iri) gc.collect() return status
def get_all_child_cells(): """ Args: cell_cls (dict): dict of cell type name : ontology thing Returns a dict of cell type : list of child cell types. """ from owlready2 import get_ontology, default_world cl_db_dir = os.path.join(PATH, 'data', 'cl.db') default_world.set_backend(filename=cl_db_dir) conn = sqlite3.connect(DB_DIR) C = conn.cursor() C.execute('SELECT * FROM cell_cl') results = C.fetchall() cell_cl = {r[0]: r[1] for r in results} conn.close() # open cell ontology onto = get_ontology('cl.owl').load() # http://owlready.8326.n8.nabble.com/Accessing-class-by-its-name-in-owlready2-td457.html namespace = onto.get_namespace("http://purl.obolibrary.org/obo/") cell_cls = dict() for cell, cl in cell_cl.items(): cell_cls[cell] = namespace[cl] cl_cells = {cl.get_name(cl) : cell for cell, cl in cell_cls.items()} cells_children = dict() for cell_name, cl in cell_cls.items(): children = list(cl.descendants()) cells_children[cell_name] = [] for child in children: child_name = child.get_name(child) if child_name in cl_cells: cell_type = cl_cells[child.get_name(child)] cells_children[cell_name].append(cell_type) return cells_children
def addDocumentConceptsToOntology(docid, path, concepts): import owlready2 onto = owlready2.get_ontology("file://" + path) onto.load() class Concept(owlready2.Thing): namespace = onto class Document(owlready2.Thing): namespace = onto currentDocument = Document(docid) class documentHasConcept(owlready2.ObjectProperty): namespace = onto domain = [Document] range = [Concept] for concept in concepts: currentConcept = Concept(concept) currentDocument.documentHasConcept.append(currentConcept) onto_file = open(path, 'wb+') try: onto.save(file=onto_file, format="rdfxml") onto.destroy() del onto return True except: onto.destroy() del onto return False
def load_ontologies(ontology_arguments): """Loads the ontologies provided as a list of OntologyArgument. Also loads all indirectly imported ontologies. Each ontology is prefixed with the specified prefix (OntologyArgument.prefix) or with a generated prefix (generate_prefix). The manually specified prefixes take precedence. Args: ontology_arguments: A list of OntologyArguments. Returns: A tuple, the first value is a list of loaded ontologies (owlready2 objects), the second value is the map of ontology names to the prefix. """ ontology_prefix_map = {'owl': 'owl'} ontologies = [] for ontology in ontology_arguments: onto = owlready2.get_ontology(ontology.uri).load(reload=True) ontologies.append(onto) ontology_prefix_map[onto.ontology.name] = ontology.prefix for ontology in ontologies: for imported_ontology in ontology.indirectly_imported_ontologies(): onto_name = imported_ontology.ontology.name if onto_name not in ontology_prefix_map: ontologies.append(imported_ontology) ontology_prefix_map[onto_name] = generate_prefix(onto_name) return ontologies, ontology_prefix_map
def processOntodict(ontodict, ontopath, mtype): log("Call to processOntodict() with ontopath: " + ontopath) import owlready2 onto = owlready2.get_ontology("file://" + ontopath) onto.load() #class Concept(Thing): # namespace = onto #class Document(Thing): # namespace = onto clases = ontodict['clases'] concepts = ontodict['concepts'] if mtype == 1: log("Generating clases...") for classkey, classelem in clases.items(): ontoclass = classkey.title() with onto: NewClass = owlready2.types.new_class(ontoclass, (onto.Concept, ), kwds={}) for elem in classelem: NewClass(elem.lower()) for concept in concepts: docid = concept[1] conceptname = concept[0] with onto: currentDocumentSearch = onto.search(iri=onto.base_iri + str(docid)) if len(currentDocumentSearch) > 0: currentDocument = currentDocumentSearch[0] else: currentDocument = onto.Document(docid) currentConceptSearch = onto.search(iri=onto.base_iri + conceptname.lower()) if len(currentConceptSearch): currentConcept = currentConceptSearch[0] else: currentConcept = onto.Concept(conceptname.lower()) currentDocument.documentHasConcept.append(currentConcept) currentConcept.conceptInDocument.append(currentDocument) onto_file = open(ontopath, 'wb+') try: onto.save(file=onto_file, format="rdfxml") log("Saved file to path " + ontopath) onto_file.close() log("Call to destroy ontolgy: " + ontopath) onto.destroy() del onto del owlready2 return True except: log("Error saving ontology, destroying object: " + ontopath) onto.destroy() del onto del owlready2 return False
def insert_relations(specific_relations): """insert connected_to relations into onto""" onto = get_ontology(IRI).load() with onto: for i in specific_relations: onto[str(i[0]).split('.')[-1]].specifically_connected_to.\ append(onto[str(i[1]).split('.')[-1]]) onto.save(file=ONTOFILE)
def populate_from_uberon(self): from owlready2 import get_ontology o = get_ontology("file:///Users/andrew/Data/uberon.owl").load() RegionalPartOfBrain = o.search( iri="http://purl.obolibrary.org/obo/UBERON_0002616")[0] parts_of_brain = o.search(subclass_of=RegionalPartOfBrain) for cls in parts_of_brain: print(cls.label[0], cls.iri)
def init_onto(onto_path): """Helper: read ontology file & run default reasoner. """ onto_path = 'file://' + onto_path onto = owl.get_ontology(onto_path).load() print('Loaded owl file at:', onto_path) owl.sync_reasoner() return onto
def get_scansion_graph(scansion): """Transform a scansion dictionary into a compliant LOD graph. :param scansion: Dictionary with a Rantanplan-like scansion analysis :return: RDFLib Graph with the individuals from scansion """ structural_onto = get_ontology(ONTOLOGIES["structural"]).load() onto = add_structural_individuals(scansion, structural_onto) return onto_to_graph(onto)
def dynamically_create_instances(iri, output, input_list): """create instances from list""" onto = get_ontology(iri).load() for i in input_list[1:]: my_instance = getattr(onto, i[1])(i[0]) if i[2]: my_instance.comment.append(i[2]) onto.save(file=output)
def __init__(self): owl.onto_path.append("data/external_data") self.ontology = owl.get_ontology("ontology.owl").load() self.ontology_classes = set(self.ontology.classes()) self.lexicon = {} for ontology_class in self.ontology_classes: self.lexicon[ontology_class] = ontology_class.lex
def dynamically_create_classes(iri, output, input_list): """create classes from list""" onto = get_ontology(iri).load() with onto: for i in input_list[1:]: my_class = types.new_class(i[0], (getattr(onto, i[1]), )) if i[2]: my_class.comment.append(i[2]) onto.save(file=output)
def handle(self, *args, **options): ontology = get_ontology(options['path_to_owl_file']).load() self.process_option(options['import_categories'], ontology) self.process_option(options['import_audiences'], ontology) if not any([options['import_categories'], options['import_audiences'] ]): self.stderr.write( 'Specify --categories and/or --audiences to import onotologies.' )
def getConcepts(documentId, ontoId): import coruja_database import time log("Call to getConcepts(): docid = " + str(documentId) + " - ontid = " + str(ontoId)) result = [] ontopath = coruja_database.getOntology(str(ontoId)) #Read temp file tmpFilename = config.OntologyDir + str(int(time.time())) + "_tmp.owl" copyfile(ontopath, tmpFilename) log("getConcepts(): Copied ontology from " + ontopath + " to " + tmpFilename) import owlready2 owlready2.default_world.ontologies.clear() getConceptsOnto = owlready2.get_ontology("file://" + tmpFilename) log("getConcepts(): Onto world debug before load: " + str(getConceptsOnto.world.ontologies)) #getConceptsOnto = get_ontology("file://" + ontopath) try: getConceptsOnto.load() log("getConcepts(): Load ontology :" + tmpFilename) #log("getConcepts(): Load ontology :" + ontopath) except: log("getConcepts(): Error loading ontology " + tmpFilename) #log("getConcepts(): Error loading ontology " + ontopath) return result documents = getConceptsOnto.search(iri=getConceptsOnto.base_iri + str(documentId)) log("getConcepts(): Onto world debug: " + str(getConceptsOnto.world.ontologies)) if len(documents) > 0: document = documents[0] log("getConcepts(): Document found " + document.iri) concepts = document.documentHasConcept for concept in concepts: if concept not in result: result.append(concept.name) if len(concepts) > 0: log("getConcepts(): Concepts found: " + str(len(concepts))) else: log("getConcepts(): No concepts found.") else: log("No document found. docid = " + str(documentId)) os.remove(tmpFilename) log("getConcepts(): Deleting temp file " + tmpFilename) log("getConcepts(): Trying to destroy " + getConceptsOnto.base_iri) try: getConceptsOnto.destroy() del getConceptsOnto del owlready2 log("getConcepts(): Ontology destroyed") except: log("getConcepts(): Can not destroy ontology loaded") gc.collect() return result
def load_ontology(): print('Ontology loading...') onto_path.append('ontology/') onto_path.append('ontology/judo-master') onto_path.append('ontology/lkif-core-master/') onto = get_ontology( 'http://www.semanticweb.org/marko/ontologies/2020/3/lcr_onto.owl' ).load() return onto
def __init__(self, onto_filename): """ Load ontology from file. onto_filename: str, """ import owlready2 as owl self._onto = owl.get_ontology(onto_filename).load()
def get_hpo_synonyms(): ont = owlready2.get_ontology(config.hpo_file) ont.load() g = owlready2.default_world.as_rdflib_graph() hpo_ontology_syns = g.query(config.hpo_syns_statement, initNs=HPO.hp_namespaces) g.close() results = [[id, synonym.toPython().lower()] for (id, synonym) in hpo_ontology_syns] return results
def read_ontology(path): onto = get_ontology(path) onto.load() # Read classes classes = [] for cl in onto.classes(): classes.append(str(cl).split('.')[1].lower()) return classes
def populate_ontology_argparse(args): if args.source is None or not os.path.exists(args.source): print('Enter a valid path to a directory containing java files...') sys.exit(0) elif not (os.path.exists(ONTO_PATH) and os.path.isfile(ONTO_PATH)): print('Ontology "%s" does not exist ...' % os.path.basename(ONTO_PATH)) sys.exit(0) onto = owlready2.get_ontology(ONTO_PATH).load() populate_ontology(onto=onto, source=args.source)
def __init__(self, *args, **kwargs): # Running superclass initialization super(TestOntQuery, self).__init__(*args, **kwargs) # Loading ontology self.ont = get_ontology(TestConfig.sample_rdf_data).load() # Casting to graph self.graph = default_world.as_rdflib_graph() # Instantiating OntQuery for tests self.query = precis.OntQuery(ont=self.ont, graph=self.graph)