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 GetAll(): graphe = default_world.as_rdflib_graph() res = [[ i[0].replace("https://YoucefMadadi.com/Teleconsultation#", ""), str(i[1]) ] for i in graphe.query(Queries.All_Symptoms)] return res
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 post(self): req = request.values["value"] get_files() graph = default_world.as_rdflib_graph() res = list(graph.query(str(req))) graph.close() return jsonify(res)
def SaveOnto(): open(RdfFile, "w+") graphe = default_world.as_rdflib_graph() graphe.serialize(RdfFile, "turtle") default_world.save() ont.save(file=OntologyFile, format="rdfxml") return graphe
def getRDFLibGraph(self) -> TripleLiteRDFlibGraph: """Function to get the rdflib graph representation of the ontology. Returns: TripleLiteRDFlibGraph -- RDFlib compatible graph. """ return default_world.as_rdflib_graph()
def get_query_results(): get_files() graph = default_world.as_rdflib_graph() res = list( graph.query("""select ?conflict ?ACM where { ?conflict <http://www.semanticweb.org/ayoubpc/ontologies/2019/11/untitled-ontology-15#resolved_by> ?ACM. } """)) graph.close() return res
def get(self, child): graph = default_world.as_rdflib_graph() testreq = request.query_string print(testreq) req1 = child.replace("!", "?") req = req1.replace("$", "#") print(req) res = list(graph.query(str(req))) return jsonify(res)
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)
def remove_relations(ontofile, query_body): """remove existing specifically_connected_to relations""" myfile = open(PREFIXES, "r") query = myfile.read() myfile.close() myfile = open(query_body, "r") query += myfile.read() myfile.close() onto = get_ontology(IRI).load() graph = default_world.as_rdflib_graph() graph.update(query) onto.save(file=ontofile)
def get_environement(): get_files() graph = default_world.as_rdflib_graph() res = list(graph.query("""select distinct ?environement where { ?user a <http://www.semanticweb.org/ayoubpc/ontologies/2019/11/untitled-ontology-15#User> ;<http://elite.polito.it/ontologies/dogont.owl#LocatedIn> ?environement . } """)) graph.close() environement = [] for r in res: environement.append(str(r[0]).split('#')[1]) return environement
def find_bad_smells(): print('\n> Running queries for detecting bad smells in "%s"... ' % os.path.basename(P_ONTO_PATH)) if not os.path.exists(QUERIES_PATH): os.makedirs(QUERIES_PATH) graph = default_world.as_rdflib_graph() get_long_methods_and_constructors(g=graph) get_large_classes(g=graph) get_methods_or_constructors_with_switch(g=graph) get_methods_or_constructors_with_long_parameter_list(g=graph) get_data_classes(g=graph)
def GetUnchecked(): graphe = default_world.as_rdflib_graph() result = {} query = [[str(j) for j in i] for i in graphe.query(Queries.Unchecked)] for q in query: a = dict( zip([ "PatientID", "FirstName", "LastName", "Gender", "Age", "District", "Province", "Chronic", "Treatments", "Started", "Symptoms" ], q)) a["PatientID"] = a["PatientID"].replace( "https://YoucefMadadi.com/Teleconsultation#", "") try: result[a["PatientID"]]["Symptoms"].append(a["Symptoms"]) except: result[a["PatientID"]] = a result[a["PatientID"]]["Symptoms"] = [a["Symptoms"]] return result.values()
def query(self, query="", show_print=False): self.load() set_import = """ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX %s: <%s> \n """ % (self.prefix, self.base_iri) graph = default_world.as_rdflib_graph() query_SPARQL = set_import + query if show_print: print(query_SPARQL) rows = list(graph.query(query_SPARQL)) result = [] for row in rows: replaced_row = [] for term in row: replaced_row.append(str(term).replace(self.base_iri, '')) result.append(replaced_row) return result
def buildSampleCV(): # Load resume template cv_template = precis.templating.PrecisTemplate( template_folder=os.path.join(precis.config.templates_folder, "curriculum_vitae/") ) # Load user ontology user_ont = get_ontology(TestConfig.sample_rdf_data).load() # Casting to RDFLib graph user_graph = default_world.as_rdflib_graph() # Loading user preferences (for template) with open(TestConfig.template_prefs) as cv_prefs: driver = precis.templating.TemplateDriver( template=cv_template, user_ont=user_ont, user_graph=user_graph, user_prefs=cv_prefs ) with open(TestConfig.template_cv_out, "w") as f: f.write(driver.buildTemplate())
def get_query_results(): get_files() graph = default_world.as_rdflib_graph() res = list(graph.query("""select distinct ?user ?environement ?activity ?prefreneces where { ?user a <http://www.semanticweb.org/ayoubpc/ontologies/2019/11/untitled-ontology-15#User> ;<http://elite.polito.it/ontologies/dogont.owl#LocatedIn> ?environement ; <http://elite.polito.it/ontologies/dogont.owl#Performs> ?activity. ?activity <http://elite.polito.it/ontologies/dogont.owl#hasPrefrences> ?prefreneces. ?user1 a <http://www.semanticweb.org/ayoubpc/ontologies/2019/11/untitled-ontology-15#User> ;<http://elite.polito.it/ontologies/dogont.owl#LocatedIn> ?environement1; <http://elite.polito.it/ontologies/dogont.owl#Performs> ?activity1. ?activity1 <http://elite.polito.it/ontologies/dogont.owl#hasPrefrences> ?prefreneces1. filter(?user != ?user1 && ?environement = ?environement1 && ?prefreneces != ?prefreneces1) } """)) graph.close() inst_dict = {} for r in res: # print(str(r[0]).split('#')[1], str(r[1]).split('#')[1], str(r[2]).split('#')[1], str(r[3]).split('#')[1]) inst_dict[str(r[0]).split('#')[1]] = {'environment': str(r[1]).split('#')[1], 'activity': str(r[2]).split('#')[1], 'preference': str(r[3]).split('#')[1]} return inst_dict
from owlready2 import get_ontology, default_world onto = get_ontology("owl/littlePony.owl") onto.load() graph = default_world.as_rdflib_graph() entity = onto.Sphinx print(entity)