def make_all_type_rel(rdf_graph: Graph, COMMON_PREFIX: str = config.COMMON_PREFIX): """ 生成subject和object的所有类型关系的SPO三元组 :return: 迭代生成所有三元关系的字符串 Examples -------- >>> for rel in make_all_type_rel(graph) >>> print(rel) """ global_nm = GlobalNamespaceManager.get() rdf_type_rel = RDF.term('type') def extract_type_rel_from_identifier(identifier: Union[BNode, URIRef]): """ 在一个identifier中提取出 rdf:type 的三元组关系,并将其转化成字符串表示 :return: 转化后的字符串 """ typename = global_nm.compute_qname_strict(identifier)[0] return f'{identifier.n3()} {rdf_type_rel.n3()} {URIRef(COMMON_PREFIX + typename).n3()} .' for s, o in rdf_graph.subject_objects(): try: yield extract_type_rel_from_identifier(s) except ValueError: pass try: yield extract_type_rel_from_identifier(o) except ValueError: pass
def citation_enhancer_view_core(enhancer_id = None, enhancer_setup = None, parent_id = None, form_id=None, parent_field=None): content = stanbol_contenthub_retrieve(parent_id, media_type="rdf", subresource="raw") additional_constraints = [{ "type": "reference", "field": str(RDF.term("type")), "value": "http://purl.uniprot.org/core/Journal_Citation" }] formtable = define_table_query_form(form_id,parent_field) formtable.query.default = remove_first_line(content) formtable.type.default = "similarity" formtable.site.default = "uniprot" formtable.field.requires = None formtable.field.default = str(RDFS.term("comment")) formtable.result_limit.default = 500 formtable.additional_constraints.default = json.dumps(additional_constraints) form = SQLFORM(formtable, submit_button='Search') form.element(_id="%s_query"%form_id).attributes["_rows"]="5" form.element(_id="%s_query"%form_id).attributes["_cols"]="120" form_hide_row(form,form_id,"additional_constraints") form_hide_row(form,form_id,"site") form_hide_row(form,form_id,"field") form_hide_row(form,form_id,"type") form_hide_row(form,form_id,"result_limit") form_hide_row(form,form_id,"mode") return form
def uniprot_reference_controller(): response.view = 'tree/provide_enhancements.html' jsonquery={ #"selected" :selectedFields.values(), "limit": 500, "constraints": [{ "value": request.vars.url, "type": "reference", "field": stanbolmod.STANBOL_REFS, "mode" : "any", }] } #imidlog.log("ref search "+str(request.vars.searched_type)) if request.vars.searched_type is not None and request.vars.searched_type != '': jsonquery["constraints"].append({ "value": request.vars.searched_type, "type" : "reference", "field": str(RDF.term("type")), "mode": "any", }) site = "uniprot" enh = get_formated_enhancements_jsonquery(jsonquery,site) return dict(parent_id=request.vars.parent_id, enhancements=enh, format_enhancement_short=format_enhancement_short)
def gene_enhancer_controller(): response.view = 'tree/provide_enhancements.html' genes_names=request.vars.genes_names if isinstance(request.vars.genes_names,list) else [request.vars.genes_names]; genelistUP=tuple(gn.strip().upper() for gn in genes_names if len(gn.strip())>0) genelist_low=tuple(gn.strip().lower() for gn in genes_names if len(gn.strip())>0) #imidlog.log("Gene Enhancer: "+str(genelistUP)) geneids=db.executesql(db(db.hgnc.approved_symbol.belongs(genelistUP))._select(db.hgnc.gene_id)) geneids=geneids+db.executesql(db(db.hgnc.ucsc_id.belongs(genelist_low))._select(db.hgnc.gene_id)) imidlog.log("Gene Enhancer: "+str(geneids)) genevalues=["http://purl.uniprot.org/geneid/%s"%str(gid[0]) for gid in geneids if gid[0]!=''] jsonquery={ #"selected" :selectedFields.values(), "limit": 500, "constraints": [{ "value": genevalues, "type": "reference", "field": stanbolmod.STANBOL_REFS, "mode" : "any", }], } if request.vars.searched_type != '': jsonquery["constraints"].append({ "value": request.vars.searched_type, "type" : "reference", "field": str(RDF.term("type")), "mode": "any", }) imidlog.log("Gene Enhancer: "+str(jsonquery)) site = "uniprot" enh = get_formated_enhancements_jsonquery(jsonquery,site) if len(genevalues)>0 else [] return dict(parent_id=request.vars.parent_id, enhancements=enh, format_enhancement_short=format_enhancement_short)
def stanbol_enhancements_view_core(enhancer_id = None, enhancer_setup = None, parent_id = None, form_id=None, parent_field=None): meta=stanbol.contenthub_retrieve(parent_id, media_type="rdf", subresource="metadata") js=stanbolmod.rdf_to_json(meta) selectedFields = dict( titlep = "http://purl.uniprot.org/core/title", title = "http://purl.org/dc/terms/title", comment = str(RDFS.term("comment")), label = str(RDFS.term("label")), mnemonic = "http://purl.uniprot.org/core/mnemonic", type = str(RDF.term("type")), ) def __getField(r,fieldList,default="id"): for f in fieldList: try: return r[selectedFields[f]][0]["value"] except: pass return r[default] enh = [] try: res = json.loads(qry) for r in res["results"]: enh.append( dict(id =r["id"], title = __getField(r,["title","titlep","label","mnemonic","type"]), description=__getField(r,["comment","type"]) ) ) except Exception as e: enh.append( dict(id=qry, title="There was an error:", description=str(e)) ) #[ # for (k,v) in js.iteritems() if not k.startswith("urn:enhancement")] #fields = [Field("E%d"%i,"string",default=url,writable=False) for (i,url) in enumerate(md)] #def_tab_args=[form_id]+fields+[parent_field] #form = SQLFORM(SQLDB(None).define_table(*def_tab_args), # submit_button='Review&Accept') return form
def get_formated_enhancements_jsonquery(jsonquery,site=None): #Useful information for enhancements selectedFields = dict( titlep = "http://purl.uniprot.org/core/title", title = "http://purl.org/dc/terms/title", comment = str(RDFS.term("comment")), label = str(RDFS.term("label")), mnemonic = "http://purl.uniprot.org/core/mnemonic", type = str(RDF.term("type")), ) jsonquery["selected"]=selectedFields.values() try: qry = stanbol.entityhub_query(jsonquery,site) except Exception as e: qry = str(e) def __getField(r,fieldList,default="id"): for f in fieldList: try: return r[selectedFields[f]][0]["value"] except: pass return r[default] enh = [] try: res = json.loads(qry) for r in res["results"]: enh.append( dict(id =r["id"], title = __getField(r,["title","titlep","label","mnemonic","type"]), description=__getField(r,["comment","type"]) ) ) except Exception as e: enh.append( dict(id=qry, title="There was an error:", description=str(e)) ) return enh
import inspect import os from rdflib import Graph, RDFS, RDF, OWL from itertools import chain owl_class = OWL.term('Class') owl_obj_property = OWL.term('ObjectProperty') owl_data_property = OWL.term('DatatypeProperty') rdf_type = RDF.term('type') rdfs_domain = RDFS.term('domain') rdfs_range = RDFS.term('range') rdfs_subClassOf = RDFS.term('subClassOf') def create_onto_py_URIs(file, form='turtle', add_imports=True): g = Graph() root = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) root += '/OwlFiles/' g.parse(root + file, format=form) file_content = '' if add_imports: file_content = "# Auto generated file #\n" \ "from rdflib import Graph,URIRef\n" \ "import os\n" \ "import inspect\n\n\n" \ file_content += "graph = Graph()\n" \ "root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n" \ "root += '/OwlFiles/'\n" \
from rdflib import Graph from rdflib import Literal from rdflib import OWL from rdflib import RDF from rdflib import RDFS from rdflib import URIRef from rdflib import XSD from utils import write_graph a = RDF.term('type') rdfs_domain = RDFS.term('domain') rdfs_range = RDFS.term('range') rdfs_subClassOf = RDFS.term('subClassOf') xsd_double = XSD.term('double') owl_Class = OWL.term('Class') owl_DatatypeProperty = OWL.term('DatatypeProperty') owl_FunctionalProperty = OWL.term('FunctionalProperty') class Iris2RDFConverter(object): """ Attribute Information: 1. sepal length in cm 2. sepal width in cm 3. petal length in cm 4. petal width in cm 5. class: -- Iris Setosa -- Iris Versicolour
# -*- coding: utf-8 -*- import rdflib from rdflib.namespace import Namespace from rdflib import RDFS, RDF, OWL SH = Namespace('http://www.w3.org/ns/shacl#') # Classes RDF_Property = RDF.term('Property') RDF_List = RDF.term('List') RDFS_Resource = RDFS.term('Resource') RDFS_Class = RDFS.term('Class') OWL_Ontology = OWL.term("Ontology") OWL_Class = OWL.term("Class") OWL_DatatypeProperty = OWL.term("DatatypeProperty") SH_NodeShape = SH.term('NodeShape') SH_PropertyShape = SH.term('PropertyShape') SH_ValidationResult = SH.term('ValidationResult') SH_ValidationReport = SH.term('ValidationReport') SH_Violation = SH.term('Violation') SH_Info = SH.term('Info') SH_Warning = SH.term('Warning') SH_IRI = SH.term('IRI') SH_BlankNode = SH.term('BlankNode') SH_Literal = SH.term('Literal') SH_BlankNodeOrIRI = SH.term('BlankNodeOrIRI') SH_BlankNodeORLiteral = SH.term('BlankNodeOrLiteral') SH_IRIOrLiteral = SH.term('IRIOrLiteral') SH_SPARQLFunction = SH.term('SPARQLFunction') SH_SPARQLRule = SH.term('SPARQLRule')
SH_NodeShape = SH.term('NodeShape') SH_PropertyShape = SH.term('PropertyShape') SH_ValidationResult = SH.term('ValidationResult') SH_ValidationReport = SH.term('ValidationReport') SH_Violation = SH.term('Violation') SH_Info = SH.term('Info') SH_Warning = SH.term('Warning') SH_IRI = SH.term('IRI') SH_BlankNode = SH.term('BlankNode') SH_Literal = SH.term('Literal') SH_BlankNodeOrIRI = SH.term('BlankNodeOrIRI') SH_BlankNodeORLiteral = SH.term('BlankNodeOrLiteral') SH_IRIOrLiteral = SH.term('IRIOrLiteral') # predicates RDF_type = RDF.term('type') RDFS_subClassOf = RDFS.term('subClassOf') SH_path = SH.term('path') SH_deactivated = SH.term('deactivated') SH_message = SH.term('message') SH_name = SH.term('name') SH_description = SH.term('description') SH_property = SH.term('property') SH_node = SH.term('node') SH_targetClass = SH.term('targetClass') SH_targetNode = SH.term('targetNode') SH_targetObjectsOf = SH.term('targetObjectsOf') SH_targetSubjectsOf = SH.term('targetSubjectsOf') SH_focusNode = SH.term('focusNode') SH_resultSeverity = SH.term('resultSeverity') SH_resultPath = SH.term('resultPath')
# -*- coding: utf-8 -*- # """A collection of handy utility RDF functions, will one day be split out into its own installable module.""" from rdflib import RDF, RDFS, Namespace RDFS_Resource = RDFS.term('Resource') RDF_first = RDF.term('first') SH = Namespace('http://www.w3.org/ns/shacl#') from .load import load_from_source, get_rdf_from_web from .stringify import stringify_blank_node, stringify_graph, stringify_literal, stringify_node from .clone import clone_blank_node, clone_literal, clone_graph, clone_node, mix_graphs from .compare import compare_blank_node, order_graph_literal, compare_node, compare_literal
SH_NodeShape = SH.term('NodeShape') SH_PropertyShape = SH.term('PropertyShape') SH_ValidationResult = SH.term('ValidationResult') SH_ValidationReport = SH.term('ValidationReport') SH_Violation = SH.term('Violation') SH_Info = SH.term('Info') SH_Warning = SH.term('Warning') SH_IRI = SH.term('IRI') SH_BlankNode = SH.term('BlankNode') SH_Literal = SH.term('Literal') SH_BlankNodeOrIRI = SH.term('BlankNodeOrIRI') SH_BlankNodeORLiteral = SH.term('BlankNodeOrLiteral') SH_IRIOrLiteral = SH.term('IRIOrLiteral') # predicates RDF_type = RDF.term('type') RDF_first = RDF.term('first') RDF_rest = RDF.term('rest') RDFS_subClassOf = RDFS.term('subClassOf') SH_path = SH.term('path') SH_deactivated = SH.term('deactivated') SH_message = SH.term('message') SH_name = SH.term('name') SH_description = SH.term('description') SH_property = SH.term('property') SH_node = SH.term('node') SH_targetClass = SH.term('targetClass') SH_targetNode = SH.term('targetNode') SH_targetObjectsOf = SH.term('targetObjectsOf') SH_targetSubjectsOf = SH.term('targetSubjectsOf') SH_focusNode = SH.term('focusNode')