def _annotate_triples(self, ops: List[SyncOperation], source_content: str, target_content: str): source_model = ontospy.Ontospy(data=source_content, rdf_format='ttl') target_model = ontospy.Ontospy(data=target_content, rdf_format='ttl') all_urielements = _extract_uris_from(ops) _annotate_uris_etype(all_urielements, source_model, target_model) _annotate_datatype_props(all_urielements, source_model, target_model) _annotate_object_props(all_urielements, source_model, target_model)
def get_subclass_relation(ontology_filename, subclass_relation_filename): """ get subclass relation pair :param ontology_filename: :param subclass_relation_filename: :return: """ onto = ontospy.Ontospy(ontology_filename, 'r') classes = onto.classes result = [] for c in classes: c_parents = c.parents() if c_parents is not None: for p in c_parents: result.append((c, p)) subclass_relation_file = open(subclass_relation_filename, 'w') for ele in result: # ontospy has its own class format. Here we extract class child = str(ele[0]) parent = str(ele[1]) child_start = child.index('*') child_end = child.rindex('*') parent_start = parent.index('*') parent_end = parent.rindex('*') child = '<' + child[child_start + 1:child_end] + '>' parent = '<' + parent[parent_start + 1:parent_end] + '>' subclass_relation_file.write(child + '\t' + parent + '\n') subclass_relation_file.close()
def get_entity_definitions_from_ontology(uri_or_path): model = ontospy.Ontospy(uri_or_path) entity_defns = dict() for PROPERTY in model.properties: property_name, property_qname = PROPERTY.bestLabel(), PROPERTY.qname property_desc = PROPERTY.bestDescription() for domain in PROPERTY.domains: domain_name, domain_qname = domain.bestLabel(), domain.qname domain_desc = domain.bestDescription() if domain_name not in entity_defns: entity_defns[domain_name] = dict(entity_name=domain_name, qname=domain_qname, desc=domain_desc, attributes=[]) for RANGE in PROPERTY.ranges: range_name, range_qname = RANGE.bestLabel(), RANGE.qname RANGE.bestDescription() attribute = dict(name=property_name, qname=property_qname, desc=property_desc, type=range_name) entity_defns[domain_name]['attributes'].append(attribute) return [val for (key, val) in entity_defns.items()]
def __init__(self, rdf_path, output_path, onto_title, onto_text): RDFpath = rdf_path outputPath = output_path # load current ontology from EthOn github g = ontospy.Ontospy(RDFpath) #if g.properties.__len__() == 0: # exit(1) # invoke EthOn multi-HTML page visualizer #v = KompleteViz(g, onto_title, "paper", onto_text) v = KompleteViz(g, onto_title, "paper") # build HTML v.build(outputPath) # serialize ontology if '/' in outputPath: destination_prefix = outputPath + '/EthOn_' + outputPath.split( '/')[-1] else: destination_prefix = outputPath + '/EthOn' g.rdflib_graph.serialize(destination=destination_prefix + '.ttl', format='turtle') g.rdflib_graph.serialize(destination=destination_prefix + '.xml', format='xml') g.rdflib_graph.serialize(destination=destination_prefix + '.nt', format='nt')
def generate_class_tree_file(ontology_path = 'ontologies/dbpedia_2016-10.nt', prune=False): print('loading ontology: ', ontology_path) ont = ontospy.Ontospy(ontology_path) all_classes = set() print('building class relationships') relationships = {} for cl in ont.classes: relationships[to_class_name(cl)] = { 'parents': [to_class_name(p) for p in cl.parents()], 'children': [to_class_name(c) for c in cl.children()], } parents = {to_class_name(p) for p in cl.parents()} children = {to_class_name(c) for c in cl.children()} all_classes = all_classes.union(parents, children, set([to_class_name(cl)])) print('pre prune relationships length:', len(relationships.keys())) if prune: # remove all isolated classes (dont have children or parents) relationships = {name: rels for (name, rels) in relationships.items() if has_relations(rels)} print('number of ontology classes:', len(ont.classes)) print('number of all classes (including children & parents):', len(all_classes)) print('number of relationships keys:', len(relationships.keys())) print('classes minus rel keys:', all_classes.difference(set(relationships.keys()))) print('writing class relationships to file') ontology_name = path_to_name(ontology_path) file_name = 'ontologies/class-tree_{0}{1}.json'.format(ontology_name, '_pruned' if prune else '') with open(file_name, 'w') as rels_file: json.dump(relationships, rels_file, indent=4)
def owl_to_dictionary(owl_path): """ Reads owl file and builds classes dictionary with ontospy """ classes = {} onto = ontospy.Ontospy(owl_path) for c in onto.all_classes: ont_class = ontospy_to_dict(c) classes[ont_class['uri']] = ont_class return classes
def parse_ontology(self, file): """ Preprocess ontology into library-specific format :param file: :return: """ self.ontology_name = file ont = ontospy.Ontospy(file) self.o = ont self.objectProperties = self.o.all_properties # cache this self.obtain_class_hierarchy_and_signatures()
def getClasses(owl): model = ontospy.Ontospy(owl) classList = model.classes if classList != []: output = ("%s :: Classes loaded from model at %s \n" % (getTime(), owl)) else: output = ( "%s :: Error - Classes not loaded from %s. Invalid owl file \n" % (getTime(), owl)) logfile.write(output) return classList
def get_related_articles(self): article_concepts = Recurso.objects.filter(pk__in=Tripla.objects.filter( artigo=Artigo.objects.get(pk=self.kwargs['pk'])).values('objeto')) #******************************************************************************************************************** #Primeira opção ''' published_related = Artigo.objects.filter(pk__in=Tripla.objects.filter(objeto__in=article_concepts)\ .values('artigo')).filter(pk__in=Publicado.objects.all().values('artigo')).exclude(pk=self.kwargs['pk'])\ .annotate(qt_related=Count('tripla__pk',filter=Q(tripla__objeto__in=article_concepts))).order_by('-qt_related') return(published_related)''' #******************************************************************************************************************** #segunda opção a = Annotator() onto = ontospy.Ontospy(os.path.join(PROJECT_ROOT, 'namespace.owl')) # Não se pode usar uma função python em uma agregação (como no codigo comentado a seguir) e não consegui criar minha própria # função de agragação para uma função que não tenha correspondência no sql do banco e portanto resolvo o problema com dois loops # como segue(nada eficiente) '''published_related = Artigo.objects.filter(pk__in=Tripla.objects.filter(objeto__in=article_concepts)\ .values('artigo')).filter(pk__in=Publicado.objects.all().values('artigo')).exclude(pk=self.kwargs['pk'])\ .annotate(qt_bro=self.get_brothers_aggregation(F('pk'),self.kwargs['pk'])).order_by('qt_bro')''' annotated_published = Artigo.objects.filter( pk__in=Tripla.objects.all().values('artigo')).filter( pk__in=Publicado.objects.all().values('artigo')).exclude( pk=self.kwargs['pk']) ordered_related_list = list() set_a = article_concepts.values_list('uri', flat=True) for i in annotated_published: set_b = Recurso.objects.filter(pk__in=Tripla.objects.filter( artigo=i).values('objeto')).values_list('uri', flat=True) ordered_related_list.append( (i, a.get_number_of_brothers(set_a, set_b, onto))) ordered_related_list = sorted(ordered_related_list, key=lambda x: x[1], reverse=True) pk_list = [x[0].id for x in ordered_related_list] preserved = Case(*[ When(pk=pk, then=pos) for pos, pk in enumerate(pk_list) ]) # F*****g elegant! published_related = Artigo.objects.filter( pk__in=pk_list).order_by(preserved) return (published_related)
def __init__(self, namespace, prefix, ontology_file, template_folder, spec_template_file, glossary_template_file, spec_target_file, glossary_target_file): ETHON = Namespace(namespace) ontospy.BOOTSTRAP_ONTOLOGIES.append(namespace) VOCAB = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') onto = ontospy.Ontospy(ontology_file) onto.ontologyURI = onto.ontologies[0].uri onto.namespaces.append((prefix, URIRef(namespace))) for c in onto.classes: c.RDFScomment = " \n\n".join(sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.comment)])) c.RDFSlabel = ", ".join(sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.label)])) c.ETHONsuggestedStringRepresentation = ", ".join( sorted([x for x in c.rdfgraph.objects(c.uri, ETHON.suggestedStringRepresentation)])) c.VOCABterm_status = ", ".join(sorted([x for x in c.rdfgraph.objects(c.uri, VOCAB.term_status)])) c.RDFSseeAlso = sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.seeAlso)]) c.RDFSisDefinedBy = sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.isDefinedBy)]) for p in onto.properties: p.RDFScomment = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.comment)])) p.RDFSlabel = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.label)])) p.ETHONsuggestedStringRepresentation = ", ".join( sorted([x for x in p.rdfgraph.objects(p.uri, ETHON.suggestedStringRepresentation)])) p.VOCABterm_status = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, VOCAB.term_status)])) p.RDFSseeAlso = sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.seeAlso)]) p.RDFSisDefinedBy = sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.isDefinedBy)]) env = Environment(loader=FileSystemLoader(template_folder)) # Render specification website spec_template = env.get_template(spec_template_file) spec = spec_template.render( meta=self.bootstrapDesc(onto), classes_tree=onto.toplayer, properties_tree=onto.toplayerProperties, classes=onto.classes, properties=onto.properties, a_properties=onto.annotationProperties, d_properties=onto.datatypeProperties, o_properties=onto.objectProperties ) with open(spec_target_file, "wb") as fh: fh.write(spec.encode('utf-8')) # Render glossary glossary_template = env.get_template(glossary_template_file) glossary = glossary_template.render(glossary=self.makeGlossary(onto)) with open(glossary_target_file, "wb") as fh: fh.write(glossary.encode('utf-8'))
def main(): ETHON = Namespace('http://ethon.consensys.net/') VOCAB = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') ontospy.BOOTSTRAP_ONTOLOGIES.append('http://ethon.consensys.net/') onto = ontospy.Ontospy("EthOn.rdf") onto.ontologyURI = onto.ontologies[0].uri onto.namespaces.append(("ethon", URIRef("http://ethon.consensys.net/"))) for c in onto.classes: c.RDFScomment = " \n\n".join(sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.comment)])) c.RDFSlabel = ", ".join(sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.label)])) c.ETHONsuggestedStringRepresentation = ", ".join( sorted([x for x in c.rdfgraph.objects(c.uri, ETHON.suggestedStringRepresentation)])) c.VOCABterm_status = ", ".join(sorted([x for x in c.rdfgraph.objects(c.uri, VOCAB.term_status)])) c.RDFSseeAlso = sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.seeAlso)]) c.RDFSisDefinedBy = sorted([x for x in c.rdfgraph.objects(c.uri, RDFS.isDefinedBy)]) for p in onto.properties: p.RDFScomment = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.comment)])) p.RDFSlabel = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.label)])) p.ETHONsuggestedStringRepresentation = ", ".join( sorted([x for x in p.rdfgraph.objects(p.uri, ETHON.suggestedStringRepresentation)])) p.VOCABterm_status = ", ".join(sorted([x for x in p.rdfgraph.objects(p.uri, VOCAB.term_status)])) p.RDFSseeAlso = sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.seeAlso)]) p.RDFSisDefinedBy = sorted([x for x in p.rdfgraph.objects(p.uri, RDFS.isDefinedBy)]) env = Environment(loader=FileSystemLoader('doc_resources/templates')) # Render specification website spec_template = env.get_template('EthOn_spec_template.html') spec = spec_template.render( meta=bootstrapDesc(onto), classes_tree=onto.toplayer, properties_tree=onto.toplayerProperties, classes=onto.classes, properties=onto.properties, a_properties=onto.annotationProperties, d_properties=onto.datatypeProperties, o_properties=onto.objectProperties ) with open("EthOn_spec.html", "wb") as fh: fh.write(spec.encode('utf-8')) # Render glossary glossary_template = env.get_template('EthOn_glossary_template.md') glossary = glossary_template.render(glossary=makeGlossary(onto)) with open("EthOn_glossary.md", "wb") as fh: fh.write(glossary.encode('utf-8'))
def forwards_func(apps, schema_editor): Namespace = apps.get_model("cms", "Namespace") Recurso = apps.get_model("cms", "Recurso") db_alias = schema_editor.connection.alias ontoZika = ontospy.Ontospy(os.path.join(PROJECT_ROOT, 'root-ontology.owl')) ontoAO = ontospy.Ontospy(os.path.join(PROJECT_ROOT, 'annotation-core.owl')) nsZika = Namespace(ns_ref=str(ontoZika.namespaces[0][1]).partition(')')[0],rdf=open(os.path.join(PROJECT_ROOT, 'root-ontology.owl'),'r').read()) nsAO = Namespace(ns_ref=str(ontoAO.namespaces[0][1]).partition(')')[0],rdf=open(os.path.join(PROJECT_ROOT, 'annotation-core.owl'),'r').read()) nsZika.save() nsAO.save() for i in ontoZika.classes: Recurso.objects.using(db_alias).bulk_create([ Recurso(namespace=nsZika,uri=i,valor=str(i).partition('#')[-1].partition('*')[0].replace('_',' ')), ]) for i in ontoAO.properties: Recurso.objects.using(db_alias).bulk_create([ Recurso(namespace=nsAO,uri=i,valor=str(i).split('/')[-1].partition('*')[0]), ])
def annotate(self, *args, **kwargs): super(Artigo, self).save(*args, **kwargs) f = open('../newsroomFramework/newsroomFramework/namespace.owl', 'w') ns = File(f) ns.write(Namespace.objects.get(pk=1).rdf) ns.close() onto = ontospy.Ontospy(os.path.join(PROJECT_ROOT, 'namespace.owl')) ns.close() web_concepts = self.a.get_reifications(onto) concepts_dict = self.a.uri_to_text(self.a.zika_ontology_uri_to_text,web_concepts) reifications_to_annotate = [concepts_dict[' '.join(i)] for i in self.a.get_article_concepts(concepts_dict.keys(),self.text)] self.concepts_to_annotate.clear() self.a.add_related_concepts(reifications_to_annotate,self.concepts_to_annotate) self.update_annotations_in_db(Recurso.objects.filter(uri__in=list(self.concepts_to_annotate)).values_list('pk',flat=True))
def visualize(): if request.method == 'POST': f = request.files['file'] f.save(f.filename) g = ontospy.Ontospy(os.path.abspath(f.filename)) v = Dataviz(g) v.build(output_path=os.path.dirname(os.path.abspath(f.filename)) + "\\templates\graph") #v.preview() os.remove(f.filename) return render_template("/graph/index.html") return render_template('seerdf.html')
def initialise(): """ Return an OrderedDict comprising the list of fields in the CSV rows. :return: OrderedDict of fields """ all_fields = OrderedDict([('dcterms:identifier', None), ('dcterms:type', None), ('dcterms:hasPart', None), ('dcterms:title', None), ('rdfs:label', None), ('dcterms:description', None), ('dcterms:conformsTo', None), ('rdfs:range', None)], ) crowds = ontospy.Ontospy( "https://raw.githubusercontent.com/digirati-co-uk/annotation-vocab/master/crowds.rdf" ) for p in crowds.all_properties: all_fields[p.qname] = None return all_fields
def analysis_ontology(ontology_filename, outpath): """ get general information about ontology file :param ontolofy_filename: :param outpath: :return: """ onto = ontospy.Ontospy(ontology_filename) stas = onto.stats() onto_info = open(outpath + 'info', 'w') for ele in stas: for item in ele: onto_info.write(str(item) + ' ') onto_info.write('\n') onto_info.close() classes = onto.classes classes_file = open(outpath + 'classes', 'w') for ele in classes: ele = str(ele) ele_start = ele.index('*') ele_end = ele.rindex('*') ele = '<' + ele[ele_start + 1:ele_end] + '>' classes_file.write(ele + '\n') classes_file.close() data_property = onto.datatypeProperties data_property_file = open(outpath + 'data_property', 'w') for ele in data_property: data_property_file.write(str(ele) + '\n') data_property_file.close() object_property = onto.objectProperties object_property_file = open(outpath + 'object_property', 'w') for ele in object_property: object_property_file.write(str(ele) + '\n') object_property_file.close()
def csv_gen_vocab(csv_file, delimiter='|'): """ Generate an empty CSV file for creating capture model using the Crowds RDF source. Will parse and append all of the vocab URIs it finds in the :param csv_file: filename to write to :param delimiter: delimiter for CSV, defaults to pipe '|'. """ all_fields = OrderedDict([('dcterms:identifier', None), ('dcterms:type', None), ('dcterms:hasPart', None), ('dcterms:title', None), ('rdfs:label', None), ('dcterms:description', None), ('dcterms:conformsTo', None), ('rdfs:range', None)], ) crowds = ontospy.Ontospy( "https://raw.githubusercontent.com/digirati-co-uk/annotation-vocab/master/crowds.rdf" ) for p in crowds.all_properties: all_fields[p.qname] = None with open(csv_file, 'w') as csv_out: dw = csv.DictWriter(csv_out, delimiter=delimiter, fieldnames=all_fields) dw.writeheader()
def rm_main(): # Define Ontology Analyser o = ontospy.Ontospy() #inputFile = "%{inputFile}" #, people.owl, Animal.owl, schema_2020-03-10.n3 o.load_rdf(inputFile) # Create the directory in which store the new vocabulary #outputDirectory = "%{outputDirectory}" if not os.path.isdir(outputDirectory): os.makedirs(outputDirectory) moduleName = ((str(inputFile).split("/")[-1]).split("."))[-2] + "Generator" fileName = outputDirectory + moduleName + ".als" o.build_all() print(o.stats()) #print(o.all_classes) #print(o.all_properties) #print(o.all_shapes) #print(o.all_ontologies) #print(o.all_skos_concepts) #print(o.rdflib_graph) AlloyModel = "" for class_ in o.all_classes + ["http://www.w3.org/2002/07/owl#Thing"]: #print("Class: " + str(class_.uri)) if ("owl#Thing" in str(class_)): className = "Thing" AlloyClass = "sig Thing in Individual { // Individual can be removed if not defined\n " else: className = nameOf(class_.uri) AlloyClass = "sig " + className for subClassOf in class_.parents(): subClassOfName = nameOf(subClassOf.uri) if (" in " not in AlloyClass): AlloyClass = AlloyClass + " in " + subClassOfName else: AlloyClass = AlloyClass + " + " + subClassOfName AlloyClass = AlloyClass + " { \n\t" for property_ in o.all_properties: #print("Property: " + str(property_.uri)) domains_ = domains(property_) property_Name = nameOf(property_.uri) for domain_ in domains_: if (nameOf(domain_) == str(className)): print("Domain: " + str(domain_)) ranges_ = ranges(property_) for range_ in ranges_: print("Range: " + str(range_)) AlloyClass = AlloyClass + property_Name + ": " + nameOf( range_) + ",\n\t" AlloyClass = AlloyClass[0:-3] + "} \n" AlloyModel = AlloyModel + AlloyClass #print() with open(fileName, "w+") as Alloy: Alloy.write("module " + moduleName + "\n\n") Alloy.write(AlloyModel) AlloyModel = "" notAlloyModel = "" notAlloyPred = set() for subject, predicate, object_ in o.rdflib_graph: predicateName = nameOf(predicate.encode('utf-8').strip()) if (predicateName != "type"): #print(subject, predicate, object_) #print() subj = o.get_any_entity(uri=subject.encode('utf-8').strip()) pred = o.get_any_entity(uri=predicate.encode('utf-8').strip()) obj = o.get_any_entity(uri=object_.encode('utf-8').strip()) if (subj and obj): if predicateName == "subPropertyOf": subj_range = "" if ("Property" == str(subj)[1:9] and subj.ranges): #print(len(subj.ranges)) subj_range = subj.ranges[0].uri elif ("Class" == str(subj)[1:6] and subj.range_of): #print(len(subj.range_of)) subj_range = subj.range_of[0].uri AlloyModel = AlloyModel + "// subPropertyOf as Figure4\n" if (nameOf(subj_range) and nameOf(subj.uri) and nameOf(obj.uri)): AlloyModel = AlloyModel + "pred subPropertyOf{all a:" + nameOf( subj_range) + " | a." + nameOf( subj.uri) + " in a." + nameOf( obj.uri) + "}" + "\n" obj_range = "" if ("Property" == str(obj)[1:9] and obj.ranges): #print(len(obj.ranges)) obj_range = obj.ranges[0].uri elif ("Class" == str(obj)[1:6] and obj.range_of): #print(len(obj.range_of)) obj_range = obj.range_of[0].uri if (nameOf(subj_range) and nameOf(obj_range)): AlloyModel = AlloyModel + "// subPropertyOf as TABLE I\n" AlloyModel = AlloyModel + "pred subPropertyOf{all r:" + nameOf( subj_range) + " | r in " + nameOf( obj_range) + "}" + "\n" elif predicateName == "inverseOf": AlloyModel = AlloyModel + "pred inverseOf{" + nameOf( subj.uri) + " = ~" + nameOf(obj.uri) + "}" + "\n" elif predicateName == "disjointWith": if (subj.parents() and obj.parents() and subj.parents()[0] != obj.parents()[0]): AlloyModel = AlloyModel + "pred { no c1:" + nameOf( subj.uri) + ", c2:" + nameOf( obj.uri) + "| c1 = c2}" + "\n" elif predicateName == "complementOf": C = "{" for class_ in o.all_classes: if (nameOf(obj.uri) != nameOf(class_.uri)): C = C + nameOf(class_.uri) C = C + "}" AlloyModel = AlloyModel + "pred { " + nameOf( subj.uri) + " = " + str(C) + "}" + "\n" elif predicateName == "equivalentClass": AlloyModel = AlloyModel + "pred equivalentClass{ " + nameOf( subj.uri) + " = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "equivalentProperty": AlloyModel = AlloyModel + "pred equivalentProperty{ " + nameOf( subj.uri) + " = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "TransitiveProperty": AlloyModel = AlloyModel + "pred TransitiveProperty{ a,b,c ∈ " + nameOf( subj.uri) + " / a.(" + nameOf( predicate) + ") = b && b.(" + nameOf( predicate) + ") = c ⇒ a.(" + nameOf( predicate) + ") = c }" + "\n" elif predicateName == "hasValue": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred hasValue{ #( " + pred.ranges[ 0] + " ) = 1}" + "\n" elif predicateName == "cardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred cardinality{ #( " + pred.ranges[ 0] + " ) = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "maxCardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred maxCardinality{ #( " + pred.ranges[ 0] + " ) <= " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "minCardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred minCardinality{ #( " + pred.ranges[ 0] + " ) >= " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "SymmetricProperty": if ((("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)) and (("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of))): AlloyModel = AlloyModel + "pred SymmetricProperty{ a ∈ " + pred.domains[ 0] + " && b ∈ " + pred.ranges[ 0] + " / a.(" + nameOf( predicate) + ") = b ⇒ b.(" + nameOf( predicate) + ") }" + "\n" elif predicateName == "FunctionalProperty": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred FunctionalProperty{ #(" + pred.ranges[ 0] + ") = 1}" + "\n" elif predicateName == "InverseFunctionalProperty": if (("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of)): AlloyModel = AlloyModel + "pred InverseFunctionalProperty{ #(" + pred.domains[ 0] + ") = 1}" + "\n" elif predicateName == "allValuesFrom": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred allValuesFrom{ " + nameOf( pred.ranges[0]) + " in " + nameOf( obj.uri) + "}" + "\n" elif predicateName == "someValuesFrom": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred allValuesFrom{ some r: " + nameOf( pred.ranges[0]) + " | r in " + nameOf( obj.uri) + "}" + "\n" else: notAlloyModel = notAlloyModel + str( subject.encode('utf-8').strip()) + ",\t" + str( predicate.encode('utf-8').strip()) + ",\t" + str( object_.encode('utf-8').strip()) + "\n" notAlloyPred.add(str(predicate)) else: notAlloyModel = notAlloyModel + str( subject.encode('utf-8').strip()) + ",\t" + str( predicate.encode('utf-8').strip()) + ",\t" + str( object_.encode('utf-8').strip()) + "\n" #notAlloyPred.add(str(predicate)) with open(fileName, "a+") as Alloy: Alloy.write("\n") Alloy.write(AlloyModel) AlloyUtils = "" #AlloyUtilsFile = "%{AlloyUtilsFile}" with open(AlloyUtilsFile, "r") as AlloyUtilsFileRead: AlloyUtils = AlloyUtilsFileRead.read() with open(fileName, "a+") as Alloy: Alloy.write("\n") Alloy.write(AlloyUtils) with open(fileName + "_notAlloy.csv", "w+") as notAlloy: notAlloy.write( "List of all the triples not used for Alloy conversion\n") notAlloy.write(notAlloyModel) with open(fileName + "_notAlloyPredicates.csv", "w+") as notAlloyPredicates: notAlloyPredicates.write( "List of predicates in valid triples(i.e. those without BlankNodes) not used for Alloy conversion\n" ) for pred in notAlloyPred: notAlloyPredicates.write(pred + "\n")
def rm_main(dataDL): # Create the directory in which store the new vocabulary #outputDirectory = "%{outputDirectory}" if not os.path.isdir(outputDirectory): os.makedirs(outputDirectory) # Define Ontology Analyser o = ontospy.Ontospy() # Load Ontology #inputFile = "%{inputFile}" #, people.owl, Animal.owl, schema_2020-03-10.n3 o.load_rdf(inputFile) o.build_all() moduleName = ((str(inputFile).split("/")[-1]).split("."))[-2] + "DL" fileName = outputDirectory + moduleName + ".als" AlloyModel = "module " + moduleName + "\n\n" usedProperties = set() AlloySignatures = "\n// Signatures\n" # Add Classes & Properties to Alloy for class_ in o.all_classes: #print("Class: " + str(class_.uri)) className = nameOf(class_.uri) AlloyClass = "sig " + className + " in TOP " """ for subClassOf in class_.parents(): subClassOfName = nameOf(subClassOf.uri) AlloyClass = AlloyClass + " extends " + subClassOfName """ AlloyClass = AlloyClass + " { \n\t" for property_ in o.all_properties: #print("Property: " + str(property_.uri)) domains_ = domains(property_) property_Name = nameOf(property_.uri) for domain_ in domains_: if (domain_ == str(class_.uri)): #print("Domain: " + str(domain_)) ranges_ = ranges(property_) for range_ in ranges_: #print("Range: " + str(range_)) AlloyClass = AlloyClass + property_Name + ": " + nameOf( range_) + ",\n\t" usedProperties.add(property_Name) AlloyClass = AlloyClass[0:-3] + "} \n" AlloySignatures = AlloySignatures + AlloyClass #print() AlloyModel = AlloyModel + "abstract sig TOP { \n" for property_ in o.all_properties: property_Name = nameOf(property_.uri) if (property_Name not in usedProperties): #print(property_Name) AlloyModel = AlloyModel + property_Name + " : set TOP,\n" AlloyModel = AlloyModel[0:-2] + "}\n" AlloyModel = AlloyModel + "sig BOTTOM in TOP {} fact { #BOTTOM = 0 } \n\n" AlloyAxioms = "\n// Axioms\n" # Iterate for every DL Axioms for index, row in dataDL.iterrows(): if (row["DLAxioms"]): axiom = row["DLAxioms"].encode('utf-8').strip() AlloyAxiom = DLAxiomtoAlloy( str(axiom).replace("⊤", "TOP").replace(",", ""), 0) if (AlloyAxiom[0] == "{"): AlloyAxiom = "fact " + AlloyAxiom #print(AlloyAxiom) if ("fact {" in AlloyAxiom[0:6]): AlloyAxioms = AlloyAxioms + AlloyAxiom + "\n" #print("") AlloyPredicates = "\n// Predicates\n" for subject, predicate, object_ in o.rdflib_graph: predicateName = nameOf(predicate.encode('utf-8').strip()) if (predicateName != "type"): #print(subject, predicate, object_) #print() subj = o.get_any_entity(uri=subject.encode('utf-8').strip()) pred = o.get_any_entity(uri=predicate.encode('utf-8').strip()) obj = o.get_any_entity(uri=object_.encode('utf-8').strip()) if (subj and obj): if predicateName == "subPropertyOf": subj_range = "" if ("Property" == str(subj)[1:9] and subj.ranges): #print(len(subj.ranges)) subj_range = subj.ranges[0].uri elif ("Class" == str(subj)[1:6] and subj.range_of): #print(len(subj.range_of)) subj_range = subj.range_of[0].uri AlloyModel = AlloyModel + "// subPropertyOf as Figure4\n" if (nameOf(subj_range) and nameOf(subj.uri) and nameOf(obj.uri)): AlloyModel = AlloyModel + "pred subPropertyOf{all a:" + nameOf( subj_range) + " | a." + nameOf( subj.uri) + " in a." + nameOf( obj.uri) + "}" + "\n" obj_range = "" if ("Property" == str(obj)[1:9] and obj.ranges): #print(len(obj.ranges)) obj_range = obj.ranges[0].uri elif ("Class" == str(obj)[1:6] and obj.range_of): #print(len(obj.range_of)) obj_range = obj.range_of[0].uri if (nameOf(subj_range) and nameOf(obj_range)): AlloyModel = AlloyModel + "// subPropertyOf as TABLE I\n" AlloyModel = AlloyModel + "pred subPropertyOf{all r:" + nameOf( subj_range) + " | r in " + nameOf( obj_range) + "}" + "\n" elif predicateName == "inverseOf": AlloyModel = AlloyModel + "pred inverseOf{" + nameOf( subj.uri) + " = ~" + nameOf(obj.uri) + "}" + "\n" elif predicateName == "disjointWith": if (subj.parents() and obj.parents() and subj.parents()[0] != obj.parents()[0]): AlloyModel = AlloyModel + "pred { no c1:" + nameOf( subj.uri) + ", c2:" + nameOf( obj.uri) + "| c1 = c2}" + "\n" elif predicateName == "complementOf": C = "{" for class_ in o.all_classes: if (nameOf(obj.uri) != nameOf(class_.uri)): C = C + nameOf(class_.uri) C = C + "}" AlloyModel = AlloyModel + "pred { " + nameOf( subj.uri) + " = " + str(C) + "}" + "\n" elif predicateName == "equivalentClass": AlloyModel = AlloyModel + "pred equivalentClass{ " + nameOf( subj.uri) + " = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "equivalentProperty": AlloyModel = AlloyModel + "pred equivalentProperty{ " + nameOf( subj.uri) + " = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "TransitiveProperty": AlloyModel = AlloyModel + "pred TransitiveProperty{ a,b,c ∈ " + nameOf( subj.uri) + " / a.(" + nameOf( predicate) + ") = b && b.(" + nameOf( predicate) + ") = c ⇒ a.(" + nameOf( predicate) + ") = c }" + "\n" elif predicateName == "hasValue": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred hasValue{ #( " + pred.ranges[ 0] + " ) = 1}" + "\n" elif predicateName == "cardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred cardinality{ #( " + pred.ranges[ 0] + " ) = " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "maxCardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred maxCardinality{ #( " + pred.ranges[ 0] + " ) <= " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "minCardinality": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred minCardinality{ #( " + pred.ranges[ 0] + " ) >= " + nameOf(obj.uri) + "}" + "\n" elif predicateName == "SymmetricProperty": if ((("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)) and (("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of))): AlloyModel = AlloyModel + "pred SymmetricProperty{ a ∈ " + pred.domains[ 0] + " && b ∈ " + pred.ranges[ 0] + " / a.(" + nameOf( predicate) + ") = b ⇒ b.(" + nameOf( predicate) + ") }" + "\n" elif predicateName == "FunctionalProperty": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred FunctionalProperty{ #(" + pred.ranges[ 0] + ") = 1}" + "\n" elif predicateName == "InverseFunctionalProperty": if (("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of)): AlloyModel = AlloyModel + "pred InverseFunctionalProperty{ #(" + pred.domains[ 0] + ") = 1}" + "\n" elif predicateName == "allValuesFrom": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred allValuesFrom{ " + nameOf( pred.ranges[0]) + " in " + nameOf( obj.uri) + "}" + "\n" elif predicateName == "someValuesFrom": if (("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): AlloyModel = AlloyModel + "pred allValuesFrom{ some r: " + nameOf( pred.ranges[0]) + " | r in " + nameOf( obj.uri) + "}" + "\n" with open(fileName, "w+") as Alloy: Alloy.write(AlloyModel) Alloy.write(AlloySignatures) Alloy.write(AlloyAxioms) Alloy.write(AlloyPredicates) AlloyUtils = "" #AlloyUtilsFile = "%{AlloyUtilsFile}" with open(AlloyUtilsFile, "r") as AlloyUtilsFileRead: AlloyUtils = AlloyUtilsFileRead.read() with open(fileName, "a+") as Alloy: Alloy.write("\n") Alloy.write(AlloyUtils)
def rm_main(dataDL): # Create the directory in which store the new vocabulary #outputDirectory = "%{outputDirectory}" if not os.path.isdir(outputDirectory): os.makedirs(outputDirectory) # Define Ontology Analyser o = ontospy.Ontospy() # Load Ontology #inputFile = "%{inputFile}" #, people.owl, Animal.owl, schema_2020-03-10.n3 o.load_rdf(inputFile) o.build_all() moduleName = ((str(inputFile).split("/")[-1]).split("."))[-2] + "DL" fileName = outputDirectory + moduleName + ".als" AlloyModel = "module " + moduleName + "\n\n" usedProperties = set() usedDataTypes = set() AlloySignatures = "// Specific Signatures\n" # Add Classes & Properties to Alloy for class_ in o.all_classes: #print("Class: " + str(class_.uri)) className = nameOf(class_.uri) AlloyClass = "sig " + className + " in TOP " AlloyClass = AlloyClass + " { \n\t" for property_ in o.all_properties: #print("Property: " + str(property_.uri)) domains_ = domains(property_) if(len(domains_) == 1): property_Name = nameOf(property_.uri) for domain_ in domains_: if(domain_ == str(class_.uri)): #print("Domain: " + str(domain_)) ranges_ = ranges(property_) if(len(ranges_) == 1): #print("Range: " + str(range_)) rangeName = nameOf(ranges_[0]) AlloyClass = AlloyClass + property_Name + ": set " + rangeName + ",\n\t" usedProperties.add(property_) usedDataTypes.add(rangeName) else: AlloyClass = AlloyClass + property_Name + ": set TOP,\n\t" usedProperties.add(property_) #print() #print() AlloyClass = AlloyClass[0:-3] + "} \n" AlloySignatures = AlloySignatures + AlloyClass #print() # Define TOP with remaining properties AlloyModel = AlloyModel + "// General Signatures\n" AlloyModel = AlloyModel + "abstract sig TOP { \n" for property_ in o.all_properties: property_Name = nameOf(property_.uri) if(property_ not in usedProperties): # Don't take into account AnnotationProperties of OWL if (property_.uri, RDF.type, OWL.AnnotationProperty) not in o.rdflib_graph: ranges_ = ranges(property_) if(len(ranges_) == 1): rangeName = nameOf(ranges_[0]) if(rangeName == "Thing"): rangeName = "TOP" AlloyModel = AlloyModel + "\t" + property_Name + ": set " + rangeName + ",\n" usedDataTypes.add(rangeName) else: AlloyModel = AlloyModel + "\t" + property_Name + ": set TOP,\n" AlloyModel = AlloyModel[0:-2] + "}\n" AlloyModel = AlloyModel + "sig BOTTOM in TOP {} fact { #BOTTOM = 0 } \n\n" unUsedProperties = set(o.all_properties) - usedProperties unUsedLabels = set() for uUP in unUsedProperties: unUsedLabels.add(nameOf(uUP.uri)) # To add if we want to keep also class relations for validClass in o.all_classes: unUsedLabels.add(nameOf(validClass.uri)) print(unUsedLabels) AlloyAxioms = "\n// Axioms\n" AlloyAxiomsComment = "\n// Non Relevant Axioms\n" # Iterate for every DL Axioms for index, row in dataDL.iterrows(): if (row["DLAxioms"]): axioms = row["DLAxioms"]#.encode('utf-8').strip() # Split across multiple axioms on same row for axiom in str(axioms).split(','): #print(axiom) AlloyAxiom = axiom # Get the Range Replacement rangeReplacement = "TOP" if("⊤" in axiom): checkAxiomRange = axiom.split(".⊤")[0].split(" ")[-1] rangeReplacement = "TOP" for property_ in o.all_properties: property_Name = nameOf(property_.uri) if(property_Name == checkAxiomRange): ranges_ = ranges(property_) if(len(ranges_) == 1): rangeReplacement = nameOf(ranges_[0]) if(rangeReplacement == "Thing"): rangeReplacement = "TOP" # Generate the Axiom AlloyAxiom = DLAxiomtoAlloy(axiom.replace("⊤", rangeReplacement).replace(",", ""), 0) if (AlloyAxiom[0] == "{"): #print(AlloyAxiom) AlloyAxiom = "fact " + AlloyAxiom #print(AlloyAxiom) if("fact {" in AlloyAxiom[0:6]): comment = "// " for label in unUsedLabels: # [TODO] CHECK if( label in AlloyAxiom): comment = "" if(comment): AlloyAxiomsComment = AlloyAxiomsComment + comment + AlloyAxiom + "\n" else: AlloyAxioms = AlloyAxioms + comment + AlloyAxiom + "\n" #print("") AlloyProperties = "\n// Properties\n" for subject, predicate, object_ in o.rdflib_graph: #print(subject, predicate, object_) #print() predicateName = nameOf(predicate.encode('utf-8').strip()) subj = o.get_any_entity(uri=subject.encode('utf-8').strip()) pred = o.get_any_entity(uri=predicate.encode('utf-8').strip()) obj = o.get_any_entity(uri=object_.encode('utf-8').strip()) # PREDICATE MAPPING FROM OWL TO ALLOY if(subj and obj and predicateName != "type"): if predicateName == "subPropertyOf": subj_range = "" if("Property" == str(subj)[1:9] and subj.ranges): #print(len(subj.ranges)) subj_range = subj.ranges[0].uri elif("Class" == str(subj)[1:6] and subj.range_of): #print(len(subj.range_of)) subj_range = subj.range_of[0].uri if(nameOf(subj_range) and nameOf(subj.uri) and nameOf(obj.uri)): AlloyProperties = AlloyProperties + "fact {all a:" + nameOf(subj_range) + " | a." + nameOf(subj.uri) + " in a." + nameOf(obj.uri) + "} // subPropertyOf as Figure4\n" obj_range = "" if("Property" == str(obj)[1:9] and obj.ranges): #print(len(obj.ranges)) obj_range = obj.ranges[0].uri elif("Class" == str(obj)[1:6] and obj.range_of): #print(len(obj.range_of)) obj_range = obj.range_of[0].uri if(nameOf(subj_range) and nameOf(obj_range)): obj_range = nameOf(obj_range) if(obj_range == "Thing"): obj_range = "TOP" AlloyProperties = AlloyProperties + "fact {all r:" + nameOf(subj_range) + " | r in " + obj_range + "} // subPropertyOf as TABLE I\n" elif predicateName == "inverseOf": AlloyProperties = AlloyProperties + "fact {" + nameOf(subj.uri) + " = ~" + nameOf(obj.uri) + "} // inverseOf\n" elif predicateName == "disjointWith": """ if(subj.parents() and obj.parents() and subj.parents()[0] != obj.parents()[0]): AlloyProperties = AlloyProperties + "fact { no c1:" + nameOf(subj.uri) + ", c2:" + nameOf(obj.uri) + "| c1 = c2} // disjointWith\n" """ AlloyProperties = AlloyProperties + "fact { no c1:" + nameOf(subj.uri) + ", c2:" + nameOf(obj.uri) + "| c1 = c2} // disjointWith\n" elif predicateName == "complementOf": C = "{" for class_ in o.all_classes: if(nameOf(obj.uri) != nameOf(class_.uri)): C = C + nameOf(class_.uri) C = C + "}" AlloyProperties = AlloyProperties + "fact { " + nameOf(subj.uri) + " = " + str(C) + "} // complementOf\n" elif predicateName == "equivalentClass": AlloyProperties = AlloyProperties + "fact { " + nameOf(subj.uri) + " = " + nameOf(obj.uri) + "} // equivalentClass\n" elif predicateName == "equivalentProperty": AlloyProperties = AlloyProperties + "fact { " + nameOf(subj.uri) + " = " + nameOf(obj.uri) + "} // equivalentProperty\n" elif predicateName == "TransitiveProperty": AlloyProperties = AlloyProperties + "fact { a,b,c ∈ " + nameOf(subj.uri) + " / a.(" + nameOf(predicate) + ") = b && b.(" + nameOf(predicate) + ") = c ⇒ a.(" + nameOf(predicate) + ") = c } // TransitiveProperty\n" elif predicateName == "hasValue": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { #( " + pred_range + " ) = 1} // hasValue\n" elif predicateName == "cardinality": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { #( " + pred_range + " ) = " + nameOf(obj.uri) + "} // cardinality\n" elif predicateName == "maxCardinality": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { #( " + pred_range + " ) <= " + nameOf(obj.uri) + "} // maxCardinality\n" elif predicateName == "minCardinality": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { #( " + pred_range + " ) >= " + nameOf(obj.uri) + "} // minCardinality\n" elif predicateName == "SymmetricProperty": if((("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)) and (("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of))): AlloyProperties = AlloyProperties + "fact { a ∈ " + pred.domains[0] + " && b ∈ " + pred.ranges[0] + " / a.(" + nameOf(predicate) + ") = b ⇒ b.(" + nameOf(predicate) + ") } // SymmetricProperty\n" elif predicateName == "FunctionalProperty": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { #(" + pred_range + ") = 1} //FunctionalProperty \n" elif predicateName == "InverseFunctionalProperty": if(("Property" == str(pred)[1:9] and pred.domains) or ("Class" == str(pred)[1:6] and pred.domain_of)): AlloyProperties = AlloyProperties + "fact { #(" + pred.domains[0] + ") = 1} // InverseFunctionalProperty\n" elif predicateName == "allValuesFrom": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { " + pred_range + " in " + nameOf(obj.uri) + "} // allValuesFrom\n" elif predicateName == "someValuesFrom": if(("Property" == str(pred)[1:9] and pred.ranges) or ("Class" == str(pred)[1:6] and pred.range_of)): pred_range = nameOf(pred.ranges[0]) if(pred_range == "Thing"): pred_range = "TOP" AlloyProperties = AlloyProperties + "fact { some r: " + pred_range + " | r in " + nameOf(obj.uri) + "} // someValuesFrom\n" # META-PROPERTY OF OWL TO ALLOY elif(predicateName == "type"): if(nameOf(object_) == "FunctionalObjectProperty"): if("Property" == str(subj)[1:9] and subj.ranges): #print(len(subj.ranges)) subj_range = subj.ranges[0].uri if(subj_range == "Thing"): subj_range = "TOP" AlloyProperties = AlloyProperties + "fact { all c: " + subj_range + "| lone " + nameOf(subject)+ ".c } // FunctionalObjectProperty \n" elif(nameOf(object_) == "InverseFunctionalProperty"): if("Property" == str(subj)[1:9] and subj.domains): #print(len(subj.domains)) subj_domain = subj.domains[0].uri AlloyProperties = AlloyProperties + "fact { all c: " + subj_domain + "| lone c." + nameOf(subject)+ " } // InverseFunctionalProperty \n" elif(nameOf(object_) == "TransitiveProperty"): AlloyProperties = AlloyProperties + "fact { " + nameOf(subj.uri) + "." + nameOf(subj.uri) + " in " + nameOf(subj.uri) + " } // TransitiveProperty \n" elif(nameOf(object_) == "SymmetricProperty"): AlloyProperties = AlloyProperties + "fact { ~" + nameOf(subj.uri) + " in " + nameOf(subj.uri) + " } // SymmetricProperty \n" elif(nameOf(object_) == "AsymmetricProperty"): AlloyProperties = AlloyProperties + "fact {~" + nameOf(subj.uri) + " & " + nameOf(subj.uri) + " in iden} // AsymmetricProperty \n" elif(nameOf(object_) == "ReflexiveProperty"): if("Property" == str(subj)[1:9] and subj.domains): #print(len(subj.domains)) subj_domain = subj.domains[0].uri AlloyProperties = AlloyProperties + "fact {" + subj_domain + "<:iden in " + nameOf(subj.uri) + "} // ReflexiveProperty \n" elif(nameOf(object_) == "IrreflexiveProperty"): AlloyProperties = AlloyProperties + "fact {no iden & " + nameOf(subj.uri) + "} // IrreflexiveProperty \n" with open(fileName, "w+") as Alloy: Alloy.write(AlloyModel) Alloy.write(AlloySignatures) Alloy.write(AlloyProperties) Alloy.write(AlloyAxioms) Alloy.write(AlloyAxiomsComment) # Comment unUsed DataTypes AlloyUtils = "" #AlloyUtilsFile = "%{AlloyUtilsFile}" with open(AlloyUtilsFile, "r") as AlloyUtilsFileRead: if("TOP" in usedDataTypes): usedDataTypes.remove("TOP") for line in AlloyUtilsFileRead.readlines(): if(len(line) > 1 and line[0:2] != "//"): comment = "// " for datatype in usedDataTypes: if(datatype in line): comment = "" AlloyUtils = AlloyUtils + comment + line.strip() + "\n" else: AlloyUtils = AlloyUtils + line.strip() + "\n" with open(fileName, "a+") as Alloy: Alloy.write("\n") Alloy.write(AlloyUtils)
import ontospy model = ontospy.Ontospy("../NIL_ontoEmotion/emotions_v11.owl") print model.stats()
import ontospy from ontospy.ontodocs.viz.viz_html_single import * g = ontospy.Ontospy("http://cohere.open.ac.uk/ontology/cohere.owl#") v = HTMLVisualizer(g) # => instantiate the visualization object v.build( ) # => render visualization. You can pass an 'output_path' parameter too v.preview() # => open in browser
def load_model(self): self.onto_model = ontospy.Ontospy(self.file_name) self.get_properties() self.get_classes()
import ontospy import pickle LOCAL_ONTOLOGY_FILE = '../resources/lung_ontology.owl' PICKLED_ONTOLOGY = '../resources/lung_ontology.pkl' try: # load pickled ontospy object f = open(PICKLED_ONTOLOGY, 'rb') onto = pickle.load(f) f.close() except FileNotFoundError: onto = ontospy.Ontospy(uri_or_path=LOCAL_ONTOLOGY_FILE, rdf_format='xml') # pickle the ontology f = open(PICKLED_ONTOLOGY, 'wb') pickle.dump(onto, f) f.close() def get_onto_protein_uri(ontology, protein_label): sparql_proteins_query = """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX : <http://www.semanticweb.org/am175/ontologies/2017/1/untitled-ontology-79#> SELECT ?p ?p_label WHERE { ?p rdfs:subClassOf :Protein . ?p :has_synonym ?p_label . VALUES ?p_label { "%s" } } """ % protein_label
def build_ont_graph(dataset: str) -> OntGraph: ont = Ontology.from_dataset(dataset) ont_graph: OntGraph = OntGraph(dataset) predicates: Dict[str, Predicate] = {} for ont_name, ont_conf in config.datasets[dataset].ontology.items(): fpaths = [] if 'fpath' in ont_conf: fpaths = [ont_conf.fpath] elif 'fpaths' in ont_conf: fpaths = [ont_conf.fpaths] for fpath in fpaths: g = ontospy.Ontospy(str(fpath.as_path())) is_rdf_type_reliable = False for cls in g.classes: add_node(ont, ont_graph, cls) for prop in g.properties: for rg in prop.ranges: add_node(ont, ont_graph, rg) for domain in prop.domains: add_node(ont, ont_graph, domain) try: predicate = Predicate(str(prop.uri), [str(x.uri) for x in prop.domains], [str(x.uri) for x in prop.ranges], ont.simplify_uri(str(prop.rdftype)), False, {ont_name}) if str(prop.uri) in predicates: predicates[str(prop.uri)].merge(predicate) else: predicates[str(prop.uri)] = predicate if predicate.rdf_type in { PredicateType.OWL_DATA_PROP, PredicateType.OWL_OBJECT_PROP }: is_rdf_type_reliable = True except Exception: print(ont_name, prop) print(prop.__dict__) raise for uri, predicate in predicates.items(): if ont_name in predicate.defined_in_onts: predicate.is_rdf_type_reliable = is_rdf_type_reliable ont_graph.set_predicates(list(predicates.values())) # update parent & children between nodes for node in ont_graph.iter_nodes(): for node_uri in node.parents_uris.union(node.children_uris): if not ont_graph.has_node_with_uri(node_uri): # node is referred by subClassOf but never been defined before ont_graph.add_new_node( GraphNodeType.CLASS_NODE, ont.simplify_uri(node_uri).encode('utf-8'), node_uri, set(), set()) for node in ont_graph.iter_nodes(): for parent_uri in node.parents_uris: ont_graph.get_node_by_uri(parent_uri).children_uris.add(node.uri) for child_uri in node.children_uris: ont_graph.get_node_by_uri(child_uri).parents_uris.add(node.uri) return ont_graph
#!/usr/bin/env python # -*- coding: utf-8 -*- # Based on: # https://www.researchgate.net/publication/220535396_Reasoning_support_for_Semantic_Web_ontology_family_languages_using_Alloy import ontospy from rdflib import RDFS, OWL def nameOf(text): return (str(text).split("/"))[-1].split("#")[-1] o = ontospy.Ontospy() fileName = "people" #, people.owl, Animal.owl, schema_2020-03-10.n3 moduleName = fileName o.load_rdf("/home/marco/Desktop/Alloy/" + fileName + ".owl") fileName = "/home/marco/Desktop/Alloy/" + fileName + ".als" o.build_all() print(o.stats()) AlloyModel = "" for class_ in o.all_classes: #print("Class: " + str(class_.uri)) className = nameOf(class_.uri)
import ontospy from jinja2 import Template val = input("Enter URL file: ") val_output = input("Enter URL output file: ") id_service = input("Enter id_service: ") if id_service == "": id_service = "example-sparql" if val_output == "": val_output = "example.graphql" if val == "": val = "esquema2.owl" model = ontospy.Ontospy(val, verbose=True) class OntClass: def __init__(self, uri, id, name, parents): self.uri = uri self.id = id self.name = name self.properties = [] self.parents = parents self.hijos = [] def get_formated_name(self): return self.name.replace("-", "_") def add_property(self, property):
def init_ontology(input_file_ontology): global g g = ontospy.Ontospy(input_file_ontology)
import sys import ontospy model = ontospy.Ontospy(sys.argv[1]) model.printClassTree()
import ontospy import rdflib from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import inflect from database_schema import Normalization #names = set() # download from https://bioportal.bioontology.org/ontologies/CL model = ontospy.Ontospy("./data/cl.owl") cells = model.getClass("http://purl.obolibrary.org/obo/CL_0000000") remappings = ["OVA", "monocyte", "Treg"] synonyms = {} for e in cells.descendants(): synonyms[e.bestLabel()] = e.bestLabel() for syn in e.rdfgraph.objects(subject=e.uri, predicate=rdflib.term.URIRef('http://www.geneontology.org/formats/oboInOwl#hasExactSynonym')): #print(e.bestLabel(), "exact", str(syn)) if str(syn) not in remappings: synonyms[str(syn)] = e.bestLabel() # has_related_synonym for syn in e.rdfgraph.objects(subject=e.uri, predicate=rdflib.term.URIRef('http://www.geneontology.org/formats/oboInOwl#hasRelatedSynonym')): #print(e.bestLabel(), "related", str(syn)) if str(syn) not in remappings: synonyms[str(syn)] = e.bestLabel()