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 run(*args): if reasoner == 'Pellet': owlready2.sync_reasoner_pellet(*args) elif reasoner == 'HermiT': owlready2.sync_reasoner(*args) else: raise ValueError('unknown reasoner %r. Supported reasoners' 'are "Pellet" and "HermiT".', reasoner)
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 consistency(self, condition: bool = False): try: with self.onto: if condition: sync_reasoner(self.my_world) classi_incosistenti = list(self.my_world.inconsistent_classes()) if not len(classi_incosistenti) == 0: return classi_incosistenti else: sync_reasoner(self.big_world) return "The ontology is consistent" except OwlReadyInconsistentOntologyError: return "The ontology is inconsistent"
def rereason(G, filename): world = owlready2.World() with open(filename, 'wb') as f: f.write(G.serialize(format='ntriples')) on = world.get_ontology(f"file://./{filename}").load() owlready2.sync_reasoner(world, infer_property_values=True) G = world.as_rdflib_graph() G.bind('rdf', RDF) G.bind('owl', OWL) G.bind('rdfs', RDFS) G.bind('skos', SKOS) G.bind('brick', BRICK) G.bind('tag', TAG) G.bind('bldg', BLDG) return G
def main(path: str = '', output: str = None, stub: Arg(action='store_true') = False, infer: Arg(action='store_true') = False): if stub: path = '--stub' elif not path: log(Log.ERROR, f'Missing filename') exit(1) onto = load_ontology(path) show_classes(onto) show_obj_properties(onto) show_which_implements(onto, NOCLASS) if infer: with onto: owl.sync_reasoner() show_inconsistencies(onto) show_classes(onto) if output: onto.save(file=output, format='owlxml')
def populate_ontology(legal_ontology, data_instances): # imported ontologies ontologies = list(legal_ontology.imported_ontologies) judo = list(ontologies[0].imported_ontologies)[0] lkif_role = ontologies[1] lkif_action = lkif_role.get_namespace( 'http://www.estrellaproject.org/lkif-core/action.owl#') lkif_legal_action = lkif_role.get_namespace( 'http://www.estrellaproject.org/lkif-core/legal-action.owl#') lkif_top = lkif_role.get_namespace( 'http://www.estrellaproject.org/lkif-core/lkif-top.owl#') lkif_legal_role = lkif_role.get_namespace( 'http://www.estrellaproject.org/lkif-core/legal-role.owl#') lkif_process = lkif_role.get_namespace( 'http://www.estrellaproject.org/lkif-core/process.owl#') for instance in data_instances: # Jurisdiction individual court = instance.jurisdiction_court.replace(' ', '_') jurisdiction = judo.Jurisdiction(court, namespace=legal_ontology) # Judgement individual judgement = instance.case_id.replace(' ', '_') judgement = judo.Judgement(judgement, namespace=legal_ontology) judgement.judgement_name.append(instance.case_name) judgement.jurisdiction_city.append(instance.jurisdiction_court_city) judgement.judgement_date.append(instance.judgement_date) judgement.hearing_date.append(instance.hearing_date) # spajanje suda i presude preko considered_by ObjectProperty-a judgement.considered_by.append(jurisdiction) # Registry individual registry_name = instance.judgement_registry.replace(' ', '_') registry = lkif_process.Physical_Object(registry_name, namespace=legal_ontology) registry.stores.append( judgement) # dodavanje dokumenta u odgovarajuci registry # svi ucesnici presude modelovani su kao Legal_Person, jer ne moraju biti iskljucivo jedna osoba, vec mogu biti i kompanije, organizacije, itd. # Judge individual (Legal_Person that %plays% "judge" Legal_Role) # takodje je ucesnik odgovarajuce presude, tj. .participant(...presuda...) judge_name = instance.judge.replace(' ', '_') judge = lkif_legal_action.Legal_Person(judge_name, namespace=legal_ontology) judge_role = lkif_legal_role.Legal_Role('judge', namespace=legal_ontology) judge.plays.append(judge_role) judge.participant.append(judgement) # Side 1 (Appellant/Applicant) Counsel individual for counsel in instance.side1_counsels: a_counsel_name = counsel.replace(' ', '_') side1_counsel = lkif_legal_action.Legal_Person( a_counsel_name, namespace=legal_ontology) side1_counsel_role = lkif_legal_role.Legal_Role( instance.side1_role + '_counsel', namespace=legal_ontology) side1_counsel.plays.append(side1_counsel_role) side1_counsel.participant.append(judgement) # Side 1 Solicitor individual for solicitor in instance.side1_solicitors: a_solicitor_name = solicitor.replace(' ', '_') side1_solicitor = lkif_legal_action.Legal_Person( a_solicitor_name, namespace=legal_ontology) side1_solicitor_role = lkif_legal_role.Legal_Role( instance.side1_role + '_solicitor', namespace=legal_ontology) side1_solicitor.plays.append(side1_solicitor_role) side1_solicitor.participant.append(judgement) # Side 2 Counsel individual for counsel in instance.side2_counsels: r_counsel_name = counsel.replace(' ', '_') side2_counsel = lkif_legal_action.Legal_Person( r_counsel_name, namespace=legal_ontology) side2_counsel_role = lkif_legal_role.Legal_Role( instance.side2_role + '_counsel', namespace=legal_ontology) side2_counsel.plays.append(side2_counsel_role) side2_counsel.participant.append(judgement) # Side 2 Solicitor individual for solicitor in instance.side2_solicitors: r_solicitor_name = solicitor.replace(' ', '_') side2_solicitor = lkif_legal_action.Legal_Person( r_solicitor_name, namespace=legal_ontology) side2_solicitor_role = lkif_legal_role.Legal_Role( instance.side2_role + '_solicitor', namespace=legal_ontology) side2_solicitor.plays.append(side2_solicitor_role) side2_solicitor.participant.append(judgement) # Side 1 individual (left of V in judgement full name) for side1_name in instance.side1: side1_name = side1_name.replace(' ', '_') side1 = lkif_legal_action.Legal_Person(side1_name, namespace=legal_ontology) side1_role = lkif_legal_role.Legal_Role(instance.side1_role, namespace=legal_ontology) side1.plays.append(side1_role) side1.participant.append(judgement) # Side 2 individuals (right of V in judgement full name) # There could be more than 1 respondents! for side2_name in instance.side2: side2_name = side2_name.replace(' ', '_') side2 = lkif_legal_action.Legal_Person(side2_name, namespace=legal_ontology) side2_role = lkif_legal_role.Legal_Role( instance.side2_role, namespace=legal_ontology ) # proveriti da li postoji vise razlicitih uloga! side2.plays.append(side2_role) side2.participant.append(judgement) # Legal rule individuals for rule in instance.legal_rules: rule = rule.replace(' ', '_') legal_rule = judo.Legal_Rule(rule, namespace=legal_ontology) judgement.considers.append(legal_rule) # Referencirane presude for ref_case, ref_name in zip(instance.referenced_cases, instance.ref_names): # pravljenje individuala presude koja se referencira (VIDI STA SE DESAVA AKO TAKAV INDIVIDUAL VEC POSTOJI) ref_case = ref_case.replace(' ', '_') ref_judgement = judo.Judgement(ref_case, namespace=legal_ontology) ref_judgement.judgement_name.append(ref_name) # aktuelna presuda -> considers -> referencirana presuda judgement.considers.append(ref_judgement) # HermiT reasoner -> ako bude pucalo, skines HermiT sa zvanicnog sajta, raspakujes i zamenis to sa onim sto ti je instalirano preko owlready2 # znaci bice negde ili AppData/Python/... ili u okruzenju koje koristis u anakondi # pretrazi onim fensi search everything pa vidi gde je with legal_ontology: sync_reasoner(infer_property_values=True) save_ontology(legal_ontology)
def GetOntology(cls, iri, doReasoner=False, cachePath=None): iri_hash = cls.IRI_HASH.get(iri) if iri_hash is None: cls.IRI_HASH[iri] = iri_hash = hashlib.sha1( iri.encode('utf-8')).hexdigest() onto = cls.ONTO_CACHE.get(iri_hash) if onto is None: worldDB = cls.TermWorlds.get(iri_hash) if worldDB is None: worldDBPath = cls.GetWorldDBPath(iri_hash, cachePath) # Activate this only if you want to save a copy of the ontologies #ontologiesPath = os.path.join(cachePath,'ontologies') #os.makedirs(ontologiesPath,exist_ok=True) #owlready2.onto_path.append(ontologiesPath) worldDB = owlready2.World(filename=worldDBPath, exclusive=False) cls.TermWorlds[iri_hash] = worldDB # Trying to get the metadata useful for an optimal ontology download metadataPath = cls.GetMetadataPath(iri_hash, cachePath) if os.path.exists(metadataPath): try: with open(metadataPath, mode='r', encoding='utf-8') as metadata_fh: metadata = json.load(metadata_fh) except: # A corrupted cache should not disturb metadata = {} else: metadata = {} ontologyPath = cls.GetOntologyPath(iri_hash, cachePath) gotPath, gotMetadata = download_file(iri, ontologyPath, metadata) if gotPath: gotMetadata['orig_url'] = iri # Reading the ontology with open(ontologyPath, mode="rb") as onto_fh: onto = worldDB.get_ontology(iri).load(fileobj=onto_fh, reload=True) # Save the metadata with open(metadataPath, mode="w", encoding="utf-8") as metadata_fh: json.dump(gotMetadata, metadata_fh) # Re-save once the reasoner has run if doReasoner: worldDB.save() owlready2.sync_reasoner(onto) else: onto = worldDB.get_ontology(iri).load() worldDB.save() # And now unlink the ontology (if exists) if os.path.exists(ontologyPath): os.unlink(ontologyPath) cls.ONTO_CACHE[iri_hash] = onto return onto
from owlready2 import get_ontology, onto_path, sync_reasoner #onto = get_ontology("http://www.lesfleursdunormal.fr/static/_downloads/pizza_onto.owl") onto = get_ontology('pizza_onto.owl') onto.load() class NonVegetarianPizza(onto.Pizza): equivalent_to = [ onto.Pizza & (onto.has_topping.some(onto.MeatTopping) | onto.has_topping.some(onto.FishTopping)) ] if __name__ == "__main__": my_pizza = onto.Pizza('my_pizza') my_pizza.has_topping = [ onto.CheeseTopping(), onto.TomatoTopping(), onto.MeatTopping() ] print('Before reasoning: %s' % my_pizza.__class__) sync_reasoner(debug=0) print('After reasoning: %s' % my_pizza.__class__)
def relation_between_word_aspect(self, word_class, category, aspect_class, aspect_dependency, word_sentiment): if aspect_dependency != 'no': aspect_relation = [1, 0] aspect_sentiment = word_sentiment else: aspect_relation = [0, 1] aspect_sentiment = [0, 0, 1] if word_class is None: # aspect_relation, UnknownPolarity return aspect_relation, [0, 0, 1], aspect_sentiment, word_sentiment positive_class = self.ontology.search(iri='*Positive')[0] negative_class = self.ontology.search(iri='*Negative')[0] sub_classes = word_class.ancestors() if self.ontology.PropertyMention in sub_classes: if self.ontology.GenericNegativePropertyMention in sub_classes: # True, Negative if aspect_dependency != 'no': return aspect_relation, [0, 1, 0], [0, 1, 0], [0, 1, 0] else: return aspect_relation, [0, 1, 0], [0, 0, 1], [0, 1, 0] elif self.ontology.GenericPositivePropertyMention in sub_classes: # True, Positive if aspect_dependency != 'no': return aspect_relation, [1, 0, 0], [1, 0, 0], [1, 0, 0] else: return aspect_relation, [1, 0, 0], [0, 0, 1], [1, 0, 0] elif self.ontology.Positive in sub_classes: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True, Positive return [1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0] # aspect_relation, UnknownPolarity if aspect_dependency != 'no': return aspect_relation, [0, 0, 1], [1, 0, 0], [1, 0, 0] else: return aspect_relation, [0, 0, 1], [0, 0, 1], [1, 0, 0] elif self.ontology.Negative in sub_classes: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True, Negative return [1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0] # aspect_relation, UnknownPolarity if aspect_dependency != 'no': return aspect_relation, [0, 0, 1], [0, 1, 0], [0, 1, 0] else: return aspect_relation, [0, 0, 1], [0, 0, 1], [0, 1, 0] else: if aspect_class is not None: word_class = owl.types.new_class(word_class.__name__ + aspect_class.__name__, (word_class, aspect_class)) owl.sync_reasoner() positive = positive_class.__subclasscheck__(word_class) negative = negative_class.__subclasscheck__(word_class) if positive and not negative: # True Positive return [1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0] elif not positive and negative: # True Negative return [1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0] elif positive and negative: # True UnknownPolarity return [1, 0], [0, 0, 1], word_sentiment, word_sentiment else: # aspect_relation, UnknownPolarity return aspect_relation, [0, 0, 1], aspect_sentiment, word_sentiment elif self.ontology.ActionMention in sub_classes: if self.ontology.GenericNegativeAction in sub_classes: # True, Negative if aspect_dependency != 'no': return aspect_relation, [0, 1, 0], [0, 1, 0], [0, 1, 0] else: return aspect_relation, [0, 1, 0], [0, 0, 1], [0, 1, 0] elif self.ontology.GenericPositiveAction in sub_classes: # True, Positive if aspect_dependency != 'no': return aspect_relation, [1, 0, 0], [1, 0, 0], [1, 0, 0] else: return aspect_relation, [1, 0, 0], [0, 0, 1], [1, 0, 0] elif self.ontology.Positive in sub_classes: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True, Positive return [1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0] # aspect_relation, UnknownPolarity if aspect_dependency != 'no': return aspect_relation, [0, 0, 1], [1, 0, 0], [1, 0, 0] else: return aspect_relation, [0, 0, 1], [0, 0, 1], [1, 0, 0] elif self.ontology.Negative in sub_classes: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True Negative return [1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0] # aspect_relation, UnknownPolarity if aspect_dependency != 'no': return aspect_relation, [0, 0, 1], [0, 1, 0], [0, 1, 0] else: return aspect_relation, [0, 0, 1], [0, 0, 1], [0, 1, 0] else: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True UnknownPolarity return [1, 0], [0, 0, 1], word_sentiment, word_sentiment # aspect_relation, UnknownPolarity return aspect_relation, [0, 0, 1], aspect_sentiment, word_sentiment elif self.ontology.EntityMention in sub_classes: if self.ontology.Positive in sub_classes: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True Positive return [1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0] # aspect_relation, UnknownPolarity if aspect_dependency != 'no': return aspect_relation, [0, 0, 1], [1, 0, 0], [1, 0, 0] else: return aspect_relation, [0, 0, 1], [0, 0, 1], [1, 0, 0] elif self.ontology.Negative in sub_classes: return [1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0] else: for c in sub_classes: if c == owl.Thing: continue if category in c.aspect: # True UnknownPolarity return [1, 0], [0, 0, 1], word_sentiment, word_sentiment # aspect_relation, UnknownPolarity return aspect_relation, [0, 0, 1], aspect_sentiment, word_sentiment else: # aspect_relation, UnknownPolarity return aspect_relation, [0, 0, 1], aspect_sentiment, word_sentiment
from django.http import JsonResponse from .ontology import Ontology as Ontology_class from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.shortcuts import render from .models import Ontology, Jogo from rest_framework.decorators import api_view from rest_framework import serializers, viewsets from owlready2 import sync_reasoner sync_reasoner() def index(request): tutorial = Ontology.objects.get(slug='PlayProfile') return render(request, "ontology_app/homepage.html", {'tutorial': tutorial}) def get_all_instances(request, ont_name, by_class): ontology = Ontology.objects.get(slug=ont_name) ontology = Ontology_class(ontology.file.name) instances = ontology.get_instances_of(by_class) return JsonResponse(instances, safe=False) def get_sub_class(request, ont_name, by_class): ontology = Ontology.objects.get(slug=ont_name) ontology = Ontology_class(ontology.file.name) sub_classes = ontology.get_sub_classes_of(by_class) return JsonResponse(sub_classes, safe=False)
def sync_reasoner(self): """Update current ontology by running the HermiT reasoner.""" with self: owlready2.sync_reasoner()
| pizza_onto.TomatoTopping | pizza_onto.MeatTopping)) portlandia = pizza_onto.Pizza("portlandia") portlandia.has_topping = [pizza_onto.TomatoTopping()] portlandia.is_a.append(pizza_onto.has_topping.only(pizza_onto.TomatoTopping)) # close_world(pizza_onto.Pizza) print("---- List Individuals -----") for instance in pizza_onto.Pizza.instances(): print(instance) # try reasoning with pizza_onto: owlready2.sync_reasoner(infer_property_values=True) print("---- What about -----") print("What about a margarita ? {}".format(margarita.is_a)) print("What about a napolitana ? {}".format(napolitana.is_a)) print("What about a portlandia ? {}".format(portlandia.is_a)) print("---- Individual Search -----") print("Individuals of NonVegetarianPizza are {}".format( pizza_onto.search(type=pizza_onto.NonVegetarianPizza))) print("Individuals of VegetarianPizza are {}".format( pizza_onto.search(type=pizza_onto.VegetarianPizza))) print("Individuals of VeganPizza are {}".format( pizza_onto.search(type=pizza_onto.VeganPizza))) print("---- What is it -----")
def __init__(self, data_dir_path): my_world = World() # path to the owl file is given here my_world.get_ontology("file://%s" % data_dir_path).load() sync_reasoner(my_world) # reasoner is started and synchronized here self.graph = my_world.as_rdflib_graph()