def values(self, property, namespace=None, language=None, localName=False): from rdflib import URIRef if not isinstance(property, URIRef): if namespace: n = Namespace(namespace) predicate = n.term(property) else: predicate = URIRef(property) else: predicate = property if language: result = [o for s,p,o in self.__triples if p == predicate and o.language == language] else: result = [o for s,p,o in self.__triples if p == predicate] if localName: from rdflib import Literal aux = [] for x in result: if isinstance(x, Literal): aux.append(x.value) else: aux.append(split_uri(x)[1]) result = aux return result
def setProperty(self, namespace, property, value): if isinstance(namespace, Namespace): predicate = namespace.term(property) else: n = Namespace(namespace) predicate = n.term(property) from itertools import chain chain(self.__triples, [(self.uri, predicate, value)])
together the LC `marc2bibframe` XSL and `bib2lod`. """ import argparse import io import logging import os.path import pymarc import pymarc.marcxml import rdflib from rdflib.namespace import Namespace, NamespaceManager, RDF import subprocess import sys BF = Namespace('http://id.loc.gov/ontologies/bibframe/') BIB = Namespace('http://bibliotek-o.org/ontology/') DCT = Namespace('http://purl.org/dc/terms/') MADSRDF = Namespace('http://www.loc.gov/mads/rdf/v1#') VIVO = Namespace('http://vivoweb.org/ontology/core#') def bind_namespace(g, prefix, namespace): """Bind prefix to namespace in ns_mgr.""" ns = Namespace(namespace) g.namespace_manager.bind(prefix, ns, override=False) return ns def tree_remove(g, s, p, o): """Modify g to remove (s, p, o) and all children.
from __future__ import unicode_literals import json from rdflib.namespace import Namespace from ckanext.dcat.harvesters import DCATRDFHarvester from ckanext.dcat.profiles import EuropeanDCATAPProfile from ckanext.lacounts.harvest import helpers import logging log = logging.getLogger(__name__) VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") DCAT = Namespace("http://www.w3.org/ns/dcat#") class LacountsESRIGeoportalHarvester(DCATRDFHarvester): ''' A CKAN Harvester for ESRI Geoportals. ''' def modify_package_dict(self, package_dict, dcat_dict, harvest_object): existing_package = self._get_existing_dataset(harvest_object.guid) helpers.process_package(package_dict, existing_package, harvest_object) return package_dict def info(self): return { 'name': 'esri_geoportal', 'title': 'ESRI Geoportal', 'description': 'Harvest from an ESRI Geoportal'
"type_url": type_url, "user": user_value, "url": url ''' def get_devilFruitG(graph): for dfruit in DEVIL_FRUITS: dfruit_object = get_devil_fruit(dfruit) dfruit_url = URIRef(dfruit_object['url']) print(dfruit_object['type_url']) print(dfruit) graph.add((dfruit_url, RDF.type, OPW.Devil_Fruit)) for key in dfruit_object.keys(): if key != 'url': if key == 'type': graph.add((dfruit_url, RDF.type, URIRef(dfruit_object['type_url']))) if key not in ['type', 'type_url', 'user']: graph.add((dfruit_url, properties[key], Literal(dfruit_object[key]))) return graph ns1 = Namespace("/") devilFGraph = Graph() devilFGraph = get_devilFruitG(devilFGraph) devilFGraph.bind("opw", ns1) print(devilFGraph.serialize(format="xml").decode("utf-8"))
from datetime import datetime import time import re from ckanext.dcat.profiles import RDFProfile from ckanext.dcat.utils import resource_uri from ckan.lib.munge import munge_tag from ckanext.switzerland.helpers import get_langs, uri_to_iri import logging log = logging.getLogger(__name__) DCT = Namespace("http://purl.org/dc/terms/") DCAT = Namespace("http://www.w3.org/ns/dcat#") VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") SCHEMA = Namespace('http://schema.org/') ADMS = Namespace("http://www.w3.org/ns/adms#") FOAF = Namespace("http://xmlns.com/foaf/0.1/") TIME = Namespace('http://www.w3.org/2006/time') LOCN = Namespace('http://www.w3.org/ns/locn#') GSP = Namespace('http://www.opengis.net/ont/geosparql#') OWL = Namespace('http://www.w3.org/2002/07/owl#') SPDX = Namespace('http://spdx.org/rdf/terms#') XML = Namespace('http://www.w3.org/2001/XMLSchema') GEOJSON_IMT = 'https://www.iana.org/assignments/media-types/application/vnd.geo+json' # noqa namespaces = {
from rdflib.namespace import Namespace, NamespaceManager from rdflib import Graph #Our data namespace D = Namespace('http://vivo.mydomain.edu/individual/') #The VIVO namespace VIVO = Namespace('http://vivoweb.org/ontology/core#') #The VCARD namespace VCARD = Namespace('http://www.w3.org/2006/vcard/ns#') #The OBO namespace OBO = Namespace('http://purl.obolibrary.org/obo/') #The BIBO namespace BIBO = Namespace('http://purl.org/ontology/bibo/') #The FOAF namespace FOAF = Namespace('http://xmlns.com/foaf/0.1/') #The SKOS namespace SKOS = Namespace('http://www.w3.org/2004/02/skos/core#') ns_manager = NamespaceManager(Graph()) ns_manager.bind('d', D) ns_manager.bind('vivo', VIVO) ns_manager.bind('vcard', VCARD) ns_manager.bind('obo', OBO) ns_manager.bind('bibo', BIBO) ns_manager.bind("foaf", FOAF) ns_manager.bind("skos", SKOS)
from pylons import config import rdflib from rdflib import URIRef, BNode, Literal from rdflib.namespace import Namespace, RDF, XSD, SKOS, RDFS from geomet import wkt, InvalidGeoJSONException from ckan.model.license import LicenseRegister from ckan.model.group import Group from ckan.plugins import toolkit from ckanext.iaest.utils import resource_uri, publisher_uri_from_dataset_dict, catalog_uri DCT = Namespace("http://purl.org/dc/terms/") DCAT = Namespace("http://www.w3.org/ns/dcat#") ADMS = Namespace("http://www.w3.org/ns/adms#") VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") FOAF = Namespace("http://xmlns.com/foaf/0.1/") SCHEMA = Namespace('http://schema.org/') TIME = Namespace('http://www.w3.org/2006/time') LOCN = Namespace('http://www.w3.org/ns/locn#') GSP = Namespace('http://www.opengis.net/ont/geosparql#') OWL = Namespace('http://www.w3.org/2002/07/owl#') SPDX = Namespace('http://spdx.org/rdf/terms#') GEOJSON_IMT = 'https://www.iana.org/assignments/media-types/application/vnd.geo+json' RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
# -*- 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')
# named tsv but it's csv import sys import os import csv import re import rdflib from rdflib import URIRef, Literal, BNode from rdflib.namespace import RDF, SKOS, Namespace, NamespaceManager, XSD, RDF, RDFS import glob BDR = Namespace("http://purl.bdrc.io/resource/") BDO = Namespace("http://purl.bdrc.io/ontology/core/") BDG = Namespace("http://purl.bdrc.io/graph/") BDA = Namespace("http://purl.bdrc.io/admindata/") ADM = Namespace("http://purl.bdrc.io/ontology/admin/") BF = Namespace("http://id.loc.gov/ontologies/bibframe/") NSM = NamespaceManager(rdflib.Graph()) NSM.bind("bdr", BDR) NSM.bind("", BDO) NSM.bind("bdg", BDG) NSM.bind("bda", BDA) NSM.bind("adm", ADM) NSM.bind("skos", SKOS) NSM.bind("rdf", RDF) NSM.bind("rdfs", RDFS) NSM.bind("bf", BF) NSM.bind("xsd", XSD) RIDSUBST = {}
class ORG(DefinedNamespace): """ Core organization ontology Vocabulary for describing organizational structures, specializable to a broad variety of types of organization. Generated from: http://www.w3.org/ns/org# Date: 2020-05-26 14:20:02.908408 """ _fail = True # http://www.w3.org/1999/02/22-rdf-syntax-ns#Property basedAt: URIRef # Indicates the site at which a person is based. We do not restrict the possibility that a person is based at multiple sites. changedBy: URIRef # Indicates a change event which resulted in a change to this organization. Depending on the event the organization may or may not have continued to exist after the event. Inverse of `org:originalOrganization`. classification: URIRef # Indicates a classification for this Organization within some classification scheme. Extension vocabularies may wish to specialize this property to have a range corresponding to a specific `skos:ConceptScheme`. This property is under discussion and may be revised or removed - in many cases organizations are best categorized by defining a sub-class hierarchy in an extension vocabulary. hasMember: URIRef # Indicates a person who is a member of the subject Organization. Inverse of `org:memberOf`, see that property for further clarification. Provided for compatibility with `foaf:member`. hasMembership: URIRef # Indicates a membership relationship that the Agent plays. Inverse of `org:member`. hasPost: URIRef # Indicates a Post which exists within the Organization. hasPrimarySite: URIRef # Indicates a primary site for the Organization, this is the default means by which an Organization can be contacted and is not necessarily the formal headquarters. hasRegisteredSite: URIRef # Indicates the legally registered site for the organization, in many legal jurisdictions there is a requirement that FormalOrganizations such as Companies or Charities have such a primary designed site. hasSite: URIRef # Indicates a site at which the Organization has some presence even if only indirect (e.g. virtual office or a professional service which is acting as the registered address for a company). Inverse of `org:siteOf`. hasSubOrganization: URIRef # Represents hierarchical containment of Organizations or Organizational Units; indicates an organization which is a sub-part or child of this organization. Inverse of `org:subOrganizationOf`. hasUnit: URIRef # Indicates a unit which is part of this Organization, e.g. a Department within a larger FormalOrganization. Inverse of `org:unitOf`. headOf: URIRef # Indicates that a person is the leader or formal head of the Organization. This will normally mean that they are the root of the `org:reportsTo` (acyclic) graph, though an organization may have more than one head. heldBy: URIRef # Indicates an Agent which holds a Post. holds: URIRef # Indicates a Post held by some Agent. identifier: URIRef # Gives an identifier, such as a company registration number, that can be used to used to uniquely identify the organization. Many different national and international identier schemes are available. The org ontology is neutral to which schemes are used. The particular identifier scheme should be indicated by the datatype of the identifier value. Using datatypes to distinguish the notation scheme used is consistent with recommended best practice for `skos:notation` of which this property is a specialization. linkedTo: URIRef # Indicates an arbitrary relationship between two organizations. Specializations of this can be used to, for example, denote funding or supply chain relationships. location: URIRef # Gives a location description for a person within the organization, for example a _Mail Stop_ for internal posting purposes. member: URIRef # Indicates the Person (or other Agent including Organization) involved in the Membership relationship. Inverse of `org:hasMembership` memberDuring: URIRef # Optional property to indicate the interval for which the membership is/was valid. memberOf: URIRef # Indicates that a person is a member of the Organization with no indication of the nature of that membership or the role played. Note that the choice of property name is not meant to limit the property to only formal membership arrangements, it is also intended to cover related concepts such as affilliation or other involvement in the organization. Extensions can specialize this relationship to indicate particular roles within the organization or more nuanced relationships to the organization. Has an optional inverse, `org:hasmember`. organization: URIRef # Indicates Organization in which the Agent is a member. originalOrganization: URIRef # Indicates one or more organizations that existed before the change event. Depending on the event they may or may not have continued to exist after the event. Inverse of `org:changedBy`. postIn: URIRef # Indicates the Organization in which the Post exists. purpose: URIRef # Indicates the purpose of this Organization. There can be many purposes at different levels of abstraction but the nature of an organization is to have a reason for existence and this property is a means to document that reason. An Organization may have multiple purposes. It is recommended that the purpose be denoted by a controlled term or code list, ideally a `skos:Concept`. However, the range is left open to allow for other types of descriptive schemes. It is expected that specializations or application profiles of this vocabulary will constrain the range of the purpose. Alternative names: _remit_ _responsibility_ (esp. if applied to OrganizationalUnits such as Government Departments). remuneration: URIRef # Indicates a salary or other reward associated with the role. Typically this will be denoted using an existing representation scheme such as `gr:PriceSpecification` but the range is left open to allow applications to specialize it (e.g. to remunerationInGBP). reportsTo: URIRef # Indicates a reporting relationship as might be depicted on an organizational chart. The precise semantics of the reporting relationship will vary by organization but is intended to encompass both direct supervisory relationships (e.g. carrying objective and salary setting authority) and more general reporting or accountability relationships (e.g. so called _dotted line_ reporting). resultedFrom: URIRef # Indicates an event which resulted in this organization. Inverse of `org:resultingOrganization`. resultingOrganization: URIRef # Indicates an organization which was created or changed as a result of the event. Inverse of `org:resultedFrom`. role: URIRef # Indicates the Role that the Agent plays in a Membership relationship with an Organization. roleProperty: URIRef # This is a metalevel property which is used to annotate an `org:Role` instance with a sub-property of `org:memberOf` that can be used to directly indicate the role for easy of query. The intended semantics is a Membership relation involving the Role implies the existence of a direct property relationship through an inference rule of the form: `{ [] org:member ?p; org:organization ?o; org:role [org:roleProperty ?r] } -> {?p ?r ?o}`. siteAddress: URIRef # Indicates an address for the site in a suitable encoding. Use of vCard (using the http://www.w3.org/TR/vcard-rdf/ vocabulary) is encouraged but the range is left open to allow other encodings to be used. The address may include email, telephone, and geo-location information and is not restricted to a physical address. siteOf: URIRef # Indicates an Organization which has some presence at the given site. This is the inverse of `org:hasSite`. subOrganizationOf: URIRef # Represents hierarchical containment of Organizations or OrganizationalUnits; indicates an Organization which contains this Organization. Inverse of `org:hasSubOrganization`. transitiveSubOrganizationOf: URIRef # The transitive closure of subOrganizationOf, giving a representation of all organizations that contain this one. Note that technically this is a super property of the transitive closure so it could contain additional assertions but such usage is discouraged. unitOf: URIRef # Indicates an Organization of which this Unit is a part, e.g. a Department within a larger FormalOrganization. This is the inverse of `org:hasUnit`. # http://www.w3.org/2000/01/rdf-schema#Class ChangeEvent: URIRef # Represents an event which resulted in a major change to an organization such as a merger or complete restructuring. It is intended for situations where the resulting organization is sufficient distinct from the original organizations that it has a distinct identity and distinct URI. Extension vocabularies should define sub-classes of this to denote particular categories of event. The instant or interval at which the event occurred should be given by `prov:startAtTime` and `prov:endedAtTime`, a description should be given by `dct:description`. FormalOrganization: URIRef # An Organization which is recognized in the world at large, in particular in legal jurisdictions, with associated rights and responsibilities. Examples include a Corporation, Charity, Government or Church. Note that this is a super class of `gr:BusinessEntity` and it is recommended to use the GoodRelations vocabulary to denote Business classifications such as DUNS or NAICS. Membership: URIRef # Indicates the nature of an Agent's membership of an organization. Represents an n-ary relation between an Agent, an Organization and a Role. It is possible to directly indicate membership, independent of the specific Role, through use of the `org:memberOf` property. Organization: URIRef # Represents a collection of people organized together into a community or other social, commercial or political structure. The group has some common purpose or reason for existence which goes beyond the set of people belonging to it and can act as an Agent. Organizations are often decomposable into hierarchical structures. It is recommended that SKOS lexical labels should be used to label the Organization. In particular `skos:prefLabel` for the primary (possibly legally recognized name), `skos:altLabel` for alternative names (trading names, colloquial names) and `skos:notation` to denote a code from a code list. Alternative names: _Collective_ _Body_ _Org_ _Group_ OrganizationalCollaboration: URIRef # A collaboration between two or more Organizations such as a project. It meets the criteria for being an Organization in that it has an identity and defining purpose independent of its particular members but is neither a formally recognized legal entity nor a sub-unit within some larger organization. Might typically have a shorter lifetime than the Organizations within it, but not necessarily. All members are `org:Organization`s rather than individuals and those Organizations can play particular roles within the venture. Alternative names: _Project_ _Venture_ _Endeavour_ _Consortium_ _Endeavour_ OrganizationalUnit: URIRef # An Organization such as a University Support Unit which is part of some larger FormalOrganization and only has full recognition within the context of that FormalOrganization, it is not a Legal Entity in its own right. Units can be large and complex containing other Units and even FormalOrganizations. Alternative names: _OU_ _Unit_ _Department_ Post: URIRef # A Post represents some position within an organization that exists independently of the person or persons filling it. Posts may be used to represent situations where a person is a member of an organization ex officio (for example the Secretary of State for Scotland is part of UK Cabinet by virtue of being Secretary of State for Scotland, not as an individual person). A post can be held by multiple people and hence can be treated as a organization in its own right. Role: URIRef # Denotes a role that a Person or other Agent can take in an organization. Instances of this class describe the abstract role; to denote a specific instance of a person playing that role in a specific organization use an instance of `org:Membership`. It is common for roles to be arranged in some taxonomic structure and we use SKOS to represent that. The normal SKOS lexical properties should be used when labelling the Role. Additional descriptive properties for the Role, such as a Salary band, may be added by extension vocabularies. Site: URIRef # An office or other premise at which the organization is located. Many organizations are spread across multiple sites and many sites will host multiple locations. In most cases a Site will be a physical location. However, we don't exclude the possibility of non-physical sites such as a virtual office with an associated post box and phone reception service. Extensions may provide subclasses to denote particular types of site. # http://www.w3.org/ns/org#Role Head: URIRef # head _NS = Namespace("http://www.w3.org/ns/org#")
import certifi import json from rdflib.namespace import Namespace from rdflib import Graph, BNode, RDF, RDFS, URIRef, Literal, XSD import pygeoj from geojson import Feature, Point import coloredlogs, logging geoj = pygeoj.new() NAMESPACES = { 'schema': Namespace('http://schema.org/'), 'dcterms': Namespace('http://purl.org/dc/terms/') } g = Graph() g.parse("./data/poit.rdf") qres = g.query(""" PREFIX sdo: <http://schema.org/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX dc: <http://purl.org/dc/terms/> SELECT DISTINCT ?newsitemlabel ?label ?lon ?lat ?newsitemdate ?url WHERE { ?item rdfs:label ?label . ?item sdo:geo ?geo . ?geo sdo:latitude ?lat . ?geo sdo:longitude ?lon . ?newsitem sdo:about ?item .
import pandas import urllib import re from rdflib import Graph, URIRef, Literal from rdflib.namespace import FOAF, RDF, SKOS, OWL, RDFS, XSD from rdflib.namespace import Namespace from collections import OrderedDict, defaultdict from countrycode.countrycode import countrycode import random import locale PROV = Namespace('http://www.w3.org/ns/prov#') import os, binascii def random_string(): return binascii.b2a_hex(os.urandom(8)).decode('ascii') class TagLifter: """A class for convering HXL-style tagged data into RDF linked data guided by an OWL ontology. Builds an rdflib graph when build_graph method is called. Arguments: ontology - the path to the ontology to use during conversion [Required] source - the path to the data file to use during conversion (type determined by file extension) [Required] Values that can be set: .limit_rows - useful during debug to limit the number of rows of the data file processed by build_graph()
"wd": WD, "viaf": VIAF, "dila": DILA, "rkts": RKTS, "tmp": TMP } PATHS = [ "../adm/**/*.ttl", "../core/*.ttl", #"../ext/**/*.ttl" ] NSM = NamespaceManager(rdflib.Graph()) for p, ns in PREFIXES.items(): NSM.bind(p, Namespace(ns)) def add_static(ctx): for p, ns in PREFIXES.items(): if p == "bdo": continue ctx[p] = ns ctx["type"] = "@type" ctx["id"] = "@id" ctx["@vocab"] = BDO ctx["adm:hasAdmin"] = { "@reverse": "http://purl.bdrc.io/ontology/admin/adminAbout" } ctx["owl:sameAs"] = {"@type": "@id"} ctx["skos:closeMatch"] = {"@type": "@id"}
from pkg_resources import iter_entry_points from ckantoolkit import config import rdflib import rdflib.parser from rdflib import URIRef, BNode, Literal from rdflib.namespace import Namespace, RDF import ckan.plugins as p from ckanext.dcat.utils import catalog_uri, dataset_uri, url_to_rdflib_format, DCAT_EXPOSE_SUBCATALOGS, url_quote from ckanext.dcat.profiles import DCAT, DCT, FOAF from ckanext.dcat.exceptions import RDFProfileException, RDFParserException HYDRA = Namespace('http://www.w3.org/ns/hydra/core#') DCAT = Namespace("http://www.w3.org/ns/dcat#") # noqa RDF_PROFILES_ENTRY_POINT_GROUP = 'ckan.rdf.profiles' RDF_PROFILES_CONFIG_OPTION = 'ckanext.dcat.rdf.profiles' COMPAT_MODE_CONFIG_OPTION = 'ckanext.dcat.compatibility_mode' DEFAULT_RDF_PROFILES = ['euro_dcat_ap'] class RDFProcessor(object): def __init__(self, profiles=None, compatibility_mode=False): ''' Creates a parser or serializer instance You can optionally pass a list of profiles to be used.
"""Step 5 preparing Jabberwocky manifest.""" from rdflib import Graph, BNode, Literal from rdflib.namespace import Namespace, RDF, RDFS, DC, XSD from rdflib_pyld_compat import pyld_json_from_rdflib_graph from pyld import jsonld import context_cache.for_pyld import json import sys sc = Namespace("http://iiif.io/api/presentation/2#") oa = Namespace("http://www.w3.org/ns/oa#") exif = Namespace("http://www.w3.org/2003/12/exif/ns#") dctypes = Namespace("http://purl.org/dc/dcmitype/") foaf = Namespace("http://xmlns.com/foaf/0.1/") jw = Namespace("http://localhost:8000/jabberwocky/") def StrLiteral(s): """String literal convenience method.""" return Literal(s, datatype=XSD.string) def ListStart(g, s, p, f=None): """Add first element of RDF:List, return list and first.""" l = BNode() if (f is None): f = BNode() g.add((s, p, l)) g.add((l, RDF.type, RDF.List)) g.add((l, RDF.first, f)) g.add((l, RDF.rest, RDF.nil))
from modules.filesystem import read_file, write_file __author__ = "Sascha KAUFMANN" __copyright__ = "Copyright 2018, NIE-INE" __credits__ = [] __license__ = "3-Clause BSD License" __version__ = "0.0.2" __maintainer__ = "Sascha KAUFMANN" __email__ = "*****@*****.**" __status__ = "Production" header_information = None _KNORA_NS = Namespace("http://www.knora.org/ontology/") _DIRSEP = os.sep _TIMESTAMP = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def split_ns(ns_name): """ :param ns_name: :return: """ try: components = ns_name.split('#') if len(components) == 2: return components[0].strip(), components[1].strip()
import requests import rdflib.parser import timeout_decorator from functools import wraps import re import xml.etree.ElementTree as ET from geomet import wkt from rdflib import URIRef, BNode, Literal from rdflib.namespace import Namespace, RDF, SKOS, RDFS from idgo_admin.exceptions import DcatBaseError from idgo_admin import logger DCT = Namespace("http://purl.org/dc/terms/") DCAT = Namespace("http://www.w3.org/ns/dcat#") ADMS = Namespace("http://www.w3.org/ns/adms#") VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") FOAF = Namespace("http://xmlns.com/foaf/0.1/") LOCN = Namespace('http://www.w3.org/ns/locn#') GSP = Namespace('http://www.opengis.net/ont/geosparql#') OWL = Namespace('http://www.w3.org/2002/07/owl#') namespaces = { 'dct': DCT, 'dcat': DCAT, 'adms': ADMS, 'vcard': VCARD, 'foaf': FOAF, 'skos': SKOS,
"""This module demonstrates the use of functions defined in ABoxGeneration for representing instances, links between them and their data""" from rdflib import Graph, FOAF, URIRef, BNode, Literal from rdflib.namespace import RDF, RDFS, Namespace import ABoxGeneration as aboxgen if __name__ == '__main__': """Creates an instance of Graph""" g = Graph() """Assigns the IRI of the OntoLandUse ontology""" land_use_code_ontology_iri = "http://www.theworldavatar.com/ontology/ontolanduse/OntoLandUse.owl#" """Binds the IRI with the landusecode literal in the graph""" g.bind("landusecode", land_use_code_ontology_iri) """Creates the namespace of lucode AC01""" instance_iri_lucode_namespace = Namespace("http://www.theworldavatar.com/kb/ontolanduse/AC01.owl#") """Assigns the IRI of lucode AC01""" instance_iri_lucode = instance_iri_lucode_namespace.LandUseCode_AC01 """Assigns the name of lucode""" instance_name_lucode = "AC01" """Creates the namespace of the OntoLandUse ontology""" namespace_onto_land_use = Namespace("http://www.theworldavatar.com/ontology/ontolanduse/OntoLandUse.owl#") """Creates an instance of lucode""" g = aboxgen.create_instance(g, namespace_onto_land_use.LandUseCode, instance_iri_lucode, instance_name_lucode) """Assigns the IRI of England""" instance_iri_admindiv = "http://www.theworldavatar.com/kb/ontolanduse/England.owl#AdministrativeDivision_England" """Creates the namespace of administrative division""" instance_iri_admindiv_namespace = Namespace("http://www.theworldavatar.com/kb/ontolanduse/England.owl#") """Assigns the name of administrative division""" instance_name_admin_div = "England" """Creates an instance of administrative division"""
if object.datatype: attributes += ' rdf:datatype="%s"' % object.datatype write("%s<%s%s>%s</%s>\n" % (indent, qname, attributes, escape(object), qname)) else: if isinstance(object, BNode): write('%s<%s rdf:nodeID="%s"/>\n' % (indent, qname, object)) else: write("%s<%s rdf:resource=%s/>\n" % (indent, qname, quoteattr(self.relativize(object)))) XMLLANG = "http://www.w3.org/XML/1998/namespacelang" XMLBASE = "http://www.w3.org/XML/1998/namespacebase" OWL_NS = Namespace('http://www.w3.org/2002/07/owl#') # TODO: def fix(val): "strip off _: from nodeIDs... as they are not valid NCNames" if val.startswith("_:"): return val[2:] else: return val class PrettyXMLSerializer(Serializer): def __init__(self, store, max_depth=3): super(PrettyXMLSerializer, self).__init__(store) self.forceRDFAbout = set()
import uuid import json import datetime from dateutil.parser import parse as parse_date from six.moves.urllib.parse import quote from rdflib.namespace import XSD, Namespace from rdflib import Literal, URIRef from ckantoolkit import config import ckan.model as model log = logging.getLogger(__name__) PREFIX_MAILTO = u"mailto:" ADMS = Namespace("http://www.w3.org/ns/adms#") DCAT = Namespace("http://www.w3.org/ns/dcat#") DCT = Namespace("http://purl.org/dc/terms/") FOAF = Namespace("http://xmlns.com/foaf/0.1/") GEOJSON_IMT = ( "https://www.iana.org/assignments/media-types/application/vnd.geo+json") GSP = Namespace("http://www.opengis.net/ont/geosparql#") LOCN = Namespace("http://www.w3.org/ns/locn#") OWL = Namespace("http://www.w3.org/2002/07/owl#") SCHEMA = Namespace("http://schema.org/") SPDX = Namespace("http://spdx.org/rdf/terms#") VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") VCARD = Namespace("http://www.w3.org/2006/vcard/ns#") EML = Namespace("eml://ecoinformatics.org/eml-2.1.1") XS = Namespace("http://www.w3.org/2001/XMLSchema#")
class ODRL2(DefinedNamespace): """ ODRL Version 2.2 The ODRL Vocabulary and Expression defines a set of concepts and terms (the vocabulary) and encoding mechanism (the expression) for permissions and obligations statements describing digital content usage based on the ODRL Information Model. Generated from: https://www.w3.org/ns/odrl/2/ODRL22.ttl Date: 2020-05-26 14:20:02.352356 """ _fail = True # http://www.w3.org/1999/02/22-rdf-syntax-ns#Property action: URIRef # The operation relating to the Asset for which the Rule is being subjected. andSequence: URIRef # The relation is satisfied when each of the Constraints are satisfied in the order specified. assignee: URIRef # The Party is the recipient of the Rule. assigneeOf: URIRef # Identifies an ODRL Policy for which the identified Party undertakes the assignee functional role. assigner: URIRef # The Party is the issuer of the Rule. assignerOf: URIRef # Identifies an ODRL Policy for which the identified Party undertakes the assigner functional role. attributedParty: URIRef # The Party to be attributed. attributingParty: URIRef # The Party who undertakes the attribution. compensatedParty: URIRef # The Party is the recipient of the compensation. compensatingParty: URIRef # The Party that is the provider of the compensation. conflict: URIRef # The conflict-resolution strategy for a Policy. consentedParty: URIRef # The Party who obtains the consent. consentingParty: URIRef # The Party to obtain consent from. consequence: URIRef # Relates a Duty to another Duty, the latter being a consequence of not fulfilling the former. constraint: URIRef # Constraint applied to a Rule contractedParty: URIRef # The Party who is being contracted. contractingParty: URIRef # The Party who is offering the contract. dataType: URIRef # The datatype of the value of the rightOperand or rightOperandReference of a Constraint. duty: URIRef # Relates an individual Duty to a Permission. failure: URIRef # Failure is an abstract property that defines the violation (or unmet) relationship between Rules. function: URIRef # Function is an abstract property whose sub-properties define the functional roles which may be fulfilled by a party in relation to a Rule. hasPolicy: URIRef # Identifies an ODRL Policy for which the identified Asset is the target Asset to all the Rules. implies: URIRef # An Action asserts that another Action is not prohibited to enable its operational semantics. includedIn: URIRef # An Action transitively asserts that another Action that encompasses its operational semantics. informedParty: URIRef # The Party to be informed of all uses. informingParty: URIRef # The Party who provides the inform use data. inheritAllowed: URIRef # Indicates if the Policy entity can be inherited. inheritFrom: URIRef # Relates a (child) policy to another (parent) policy from which terms are inherited. inheritRelation: URIRef # Identifies the type of inheritance. leftOperand: URIRef # The left operand in a constraint expression. obligation: URIRef # Relates an individual Duty to a Policy. operand: URIRef # Operand is an abstract property for a logical relationship. operator: URIRef # The operator function applied to operands of a Constraint output: URIRef # The output property specifies the Asset which is created from the output of the Action. partOf: URIRef # Identifies an Asset/PartyCollection that the Asset/Party is a member of. payeeParty: URIRef # The Party is the recipient of the payment. permission: URIRef # Relates an individual Permission to a Policy. profile: URIRef # The identifier(s) of an ODRL Profile that the Policy conforms to. prohibition: URIRef # Relates an individual Prohibition to a Policy. proximity: URIRef # An value indicating the closeness or nearness. refinement: URIRef # Constraint used to refine the semantics of an Action, or Party/Asset Collection relation: URIRef # Relation is an abstract property which creates an explicit link between an Action and an Asset. remedy: URIRef # Relates an individual remedy Duty to a Prohibition. rightOperand: URIRef # The value of the right operand in a constraint expression. rightOperandReference: URIRef # A reference to a web resource providing the value for the right operand of a Constraint. scope: URIRef # The identifier of a scope that provides context to the extent of the entity. source: URIRef # Reference to a Asset/PartyCollection status: URIRef # the value generated from the leftOperand action or a value related to the leftOperand set as the reference for the comparison. target: URIRef # The target property indicates the Asset that is the primary subject to which the Rule action directly applies. timedCount: URIRef # The number of seconds after which timed metering use of the asset begins. trackedParty: URIRef # The Party whose usage is being tracked. trackingParty: URIRef # The Party who is tracking usage. uid: URIRef # An unambiguous identifier undefined: URIRef # Relates the strategy used for handling undefined actions to a Policy. unit: URIRef # The unit of measurement of the value of the rightOperand or rightOperandReference of a Constraint. xone: URIRef # The relation is satisfied when only one, and not more, of the Constraints is satisfied # http://www.w3.org/2002/07/owl#NamedIndividual All: URIRef # Specifies that the scope of the relationship is all of the collective individuals within a context. All2ndConnections: URIRef # Specifies that the scope of the relationship is all of the second-level connections to the Party. AllConnections: URIRef # Specifies that the scope of the relationship is all of the first-level connections of the Party. AllGroups: URIRef # Specifies that the scope of the relationship is all of the group connections of the Party. Group: URIRef # Specifies that the scope of the relationship is the defined group with multiple individual members. Individual: URIRef # Specifies that the scope of the relationship is the single Party individual. absolutePosition: URIRef # A point in space or time defined with absolute coordinates for the positioning of the target Asset. absoluteSize: URIRef # Measure(s) of one or two axes for 2D-objects or measure(s) of one to tree axes for 3D-objects of the target Asset. absoluteSpatialPosition: URIRef # The absolute spatial positions of four corners of a rectangle on a 2D-canvas or the eight corners of a cuboid in a 3D-space for the target Asset to fit. absoluteTemporalPosition: URIRef # The absolute temporal positions in a media stream the target Asset has to fit. count: URIRef # Numeric count of executions of the action of the Rule. dateTime: URIRef # The date (and optional time and timezone) of exercising the action of the Rule. Right operand value MUST be an xsd:date or xsd:dateTime as defined by [[xmlschema11-2]]. delayPeriod: URIRef # A time delay period prior to exercising the action of the Rule. The point in time triggering this period MAY be defined by another temporal Constraint combined by a Logical Constraint (utilising the odrl:andSequence operand). Right operand value MUST be an xsd:duration as defined by [[xmlschema11-2]]. deliveryChannel: URIRef # The delivery channel used for exercising the action of the Rule. device: URIRef # An identified device used for exercising the action of the Rule. elapsedTime: URIRef # A continuous elapsed time period which may be used for exercising of the action of the Rule. Right operand value MUST be an xsd:duration as defined by [[xmlschema11-2]]. eq: URIRef # Indicating that a given value equals the right operand of the Constraint. event: URIRef # An identified event setting a context for exercising the action of the Rule. fileFormat: URIRef # A transformed file format of the target Asset. gt: URIRef # Indicating that a given value is greater than the right operand of the Constraint. gteq: URIRef # Indicating that a given value is greater than or equal to the right operand of the Constraint. hasPart: URIRef # A set-based operator indicating that a given value contains the right operand of the Constraint. ignore: URIRef # The Action is to be ignored and is not part of the policy – and the policy remains valid. industry: URIRef # A defined industry sector setting a context for exercising the action of the Rule. invalid: URIRef # The policy is void. isA: URIRef # A set-based operator indicating that a given value is an instance of the right operand of the Constraint. isAllOf: URIRef # A set-based operator indicating that a given value is all of the right operand of the Constraint. isAnyOf: URIRef # A set-based operator indicating that a given value is any of the right operand of the Constraint. isNoneOf: URIRef # A set-based operator indicating that a given value is none of the right operand of the Constraint. isPartOf: URIRef # A set-based operator indicating that a given value is contained by the right operand of the Constraint. language: URIRef # A natural language used by the target Asset. lt: URIRef # Indicating that a given value is less than the right operand of the Constraint. lteq: URIRef # Indicating that a given value is less than or equal to the right operand of the Constraint. media: URIRef # Category of a media asset setting a context for exercising the action of the Rule. meteredTime: URIRef # An accumulated amount of one to many metered time periods which were used for exercising the action of the Rule. Right operand value MUST be an xsd:duration as defined by [[xmlschema11-2]]. neq: URIRef # Indicating that a given value is not equal to the right operand of the Constraint. payAmount: URIRef # The amount of a financial payment. Right operand value MUST be an xsd:decimal. percentage: URIRef # A percentage amount of the target Asset relevant for exercising the action of the Rule. Right operand value MUST be an xsd:decimal from 0 to 100. perm: URIRef # Permissions take preference over prohibitions. policyUsage: URIRef # Indicates the actual datetime the action of the Rule was exercised. product: URIRef # Category of product or service setting a context for exercising the action of the Rule. prohibit: URIRef # Prohibitions take preference over permissions. purpose: URIRef # A defined purpose for exercising the action of the Rule. recipient: URIRef # The party receiving the result/outcome of exercising the action of the Rule. relativePosition: URIRef # A point in space or time defined with coordinates relative to full measures the positioning of the target Asset. relativeSize: URIRef # Measure(s) of one or two axes for 2D-objects or measure(s) of one to tree axes for 3D-objects - expressed as percentages of full values - of the target Asset. relativeSpatialPosition: URIRef # The relative spatial positions - expressed as percentages of full values - of four corners of a rectangle on a 2D-canvas or the eight corners of a cuboid in a 3D-space of the target Asset. relativeTemporalPosition: URIRef # A point in space or time defined with coordinates relative to full measures the positioning of the target Asset. resolution: URIRef # Resolution of the rendition of the target Asset. spatial: URIRef # A named and identified geospatial area with defined borders which is used for exercising the action of the Rule. An IRI MUST be used to represent this value. spatialCoordinates: URIRef # A set of coordinates setting the borders of a geospatial area used for exercising the action of the Rule. The coordinates MUST include longitude and latitude, they MAY include altitude and the geodetic datum. support: URIRef # The Action is to be supported as part of the policy – and the policy remains valid. system: URIRef # An identified computing system used for exercising the action of the Rule. systemDevice: URIRef # An identified computing system or computing device used for exercising the action of the Rule. timeInterval: URIRef # A recurring period of time before the next execution of the action of the Rule. Right operand value MUST be an xsd:duration as defined by [[xmlschema11-2]]. unitOfCount: URIRef # The unit of measure used for counting the executions of the action of the Rule. version: URIRef # The version of the target Asset. virtualLocation: URIRef # An identified location of the IT communication space which is relevant for exercising the action of the Rule. # http://www.w3.org/2004/02/skos/core#Collection # http://www.w3.org/2004/02/skos/core#Concept Action: URIRef # An operation on an Asset. Agreement: URIRef # A Policy that grants the assignee a Rule over an Asset from an assigner. Assertion: URIRef # A Policy that asserts a Rule over an Asset from parties. Asset: URIRef # A resource or a collection of resources that are the subject of a Rule. AssetCollection: URIRef # An Asset that is collection of individual resources AssetScope: URIRef # Scopes for Asset Scope expressions. ConflictTerm: URIRef # Used to establish strategies to resolve conflicts that arise from the merging of Policies or conflicts between Permissions and Prohibitions in the same Policy. Constraint: URIRef # A boolean expression that refines the semantics of an Action and Party/Asset Collection or declare the conditions applicable to a Rule. Duty: URIRef # The obligation to perform an Action LeftOperand: URIRef # Left operand for a constraint expression. LogicalConstraint: URIRef # A logical expression that refines the semantics of an Action and Party/Asset Collection or declare the conditions applicable to a Rule. Offer: URIRef # A Policy that proposes a Rule over an Asset from an assigner. Operator: URIRef # Operator for constraint expression. Party: URIRef # An entity or a collection of entities that undertake Roles in a Rule. PartyCollection: URIRef # A Party that is a group of individual entities PartyScope: URIRef # Scopes for Party Scope expressions. Permission: URIRef # The ability to perform an Action over an Asset. Policy: URIRef # A non-empty group of Permissions and/or Prohibitions. Privacy: URIRef # A Policy that expresses a Rule over an Asset containing personal information. Prohibition: URIRef # The inability to perform an Action over an Asset. Request: URIRef # A Policy that proposes a Rule over an Asset from an assignee. RightOperand: URIRef # Right operand for constraint expression. Rule: URIRef # An abstract concept that represents the common characteristics of Permissions, Prohibitions, and Duties. Set: URIRef # A Policy that expresses a Rule over an Asset. Ticket: URIRef # A Policy that grants the holder a Rule over an Asset from an assigner. UndefinedTerm: URIRef # Is used to indicate how to support Actions that are not part of any vocabulary or profile in the policy expression system. acceptTracking: URIRef # To accept that the use of the Asset may be tracked. adHocShare: URIRef # The act of sharing the asset to parties in close proximity to the owner. aggregate: URIRef # To use the Asset or parts of it as part of a composite collection. annotate: URIRef # To add explanatory notations/commentaries to the Asset without modifying the Asset in any other way. anonymize: URIRef # To anonymize all or parts of the Asset. append: URIRef # The act of adding to the end of an asset. appendTo: URIRef # The act of appending data to the Asset without modifying the Asset in any other way. archive: URIRef # To store the Asset (in a non-transient form). attachPolicy: URIRef # The act of keeping the policy notice with the asset. attachSource: URIRef # The act of attaching the source of the asset and its derivatives. attribute: URIRef # To attribute the use of the Asset. commercialize: URIRef # The act of using the asset in a business environment. compensate: URIRef # To compensate by transfer of some amount of value, if defined, for using or selling the Asset. concurrentUse: URIRef # To create multiple copies of the Asset that are being concurrently used. copy: URIRef # The act of making an exact reproduction of the asset. core: URIRef # Identifier for the ODRL Core Profile delete: URIRef # To permanently remove all copies of the Asset after it has been used. derive: URIRef # To create a new derivative Asset from this Asset and to edit or modify the derivative. digitize: URIRef # To produce a digital copy of (or otherwise digitize) the Asset from its analogue form. display: URIRef # To create a static and transient rendition of an Asset. distribute: URIRef # To supply the Asset to third-parties. ensureExclusivity: URIRef # To ensure that the Rule on the Asset is exclusive. execute: URIRef # To run the computer program Asset. export: URIRef # The act of transforming the asset into a new form. extract: URIRef # To extract parts of the Asset and to use it as a new Asset. extractChar: URIRef # The act of extracting (replicating) unchanged characters from the asset. extractPage: URIRef # The act of extracting (replicating) unchanged pages from the asset. extractWord: URIRef # The act of extracting (replicating) unchanged words from the asset. give: URIRef # To transfer the ownership of the Asset to a third party without compensation and while deleting the original asset. grantUse: URIRef # To grant the use of the Asset to third parties. include: URIRef # To include other related assets in the Asset. index: URIRef # To record the Asset in an index. inform: URIRef # To inform that an action has been performed on or in relation to the Asset. install: URIRef # To load the computer program Asset onto a storage device which allows operating or running the Asset. lease: URIRef # The act of making available the asset to a third-party for a fixed period of time with exchange of value. lend: URIRef # The act of making available the asset to a third-party for a fixed period of time without exchange of value. license: URIRef # The act of granting the right to use the asset to a third-party. modify: URIRef # To change existing content of the Asset. A new asset is not created by this action. move: URIRef # To move the Asset from one digital location to another including deleting the original copy. nextPolicy: URIRef # To grant the specified Policy to a third party for their use of the Asset. obtainConsent: URIRef # To obtain verifiable consent to perform the requested action in relation to the Asset. pay: URIRef # The act of paying a financial amount to a party for use of the asset. play: URIRef # To create a sequential and transient rendition of an Asset. present: URIRef # To publicly perform the Asset. preview: URIRef # The act of providing a short preview of the asset. print: URIRef # To create a tangible and permanent rendition of an Asset. read: URIRef # To obtain data from the Asset. reproduce: URIRef # To make duplicate copies the Asset in any material form. reviewPolicy: URIRef # To review the Policy applicable to the Asset. secondaryUse: URIRef # The act of using the asset for a purpose other than the purpose it was intended for. sell: URIRef # To transfer the ownership of the Asset to a third party with compensation and while deleting the original asset. share: URIRef # The act of the non-commercial reproduction and distribution of the asset to third-parties. shareAlike: URIRef # The act of distributing any derivative asset under the same terms as the original asset. stream: URIRef # To deliver the Asset in real-time. synchronize: URIRef # To use the Asset in timed relations with media (audio/visual) elements of another Asset. textToSpeech: URIRef # To have a text Asset read out loud. transfer: URIRef # To transfer the ownership of the Asset in perpetuity. transform: URIRef # To convert the Asset into a different format. translate: URIRef # To translate the original natural language of an Asset into another natural language. uninstall: URIRef # To unload and delete the computer program Asset from a storage device and disable its readiness for operation. use: URIRef # To use the Asset watermark: URIRef # To apply a watermark to the Asset. write: URIRef # The act of writing to the Asset. writeTo: URIRef # The act of adding data to the Asset. # Valid non-python identifiers _extras = [ "and", "or", "#actionConcepts", "#actions", "#actionsCommon", "#assetConcepts", "#assetParty", "#assetRelations", "#assetRelationsCommon", "#conflictConcepts", "#constraintLeftOperandCommon", "#constraintLogicalOperands", "#constraintRelationalOperators", "#constraintRightOpCommon", "#constraints", "#deprecatedTerms", "#duties", "#logicalConstraints", "#partyConcepts", "#partyRoles", "#partyRolesCommon", "#permissions", "#policyConcepts", "#policySubClasses", "#policySubClassesCommon", "#prohibitions", "#ruleConcepts", ] _NS = Namespace("http://www.w3.org/ns/odrl/2/")
""" Notation 3 (N3) RDF graph serializer for RDFLib. """ from rdflib.graph import Graph from rdflib.namespace import Namespace, OWL from rdflib.plugins.serializers.turtle import (TurtleSerializer, SUBJECT, OBJECT) __all__ = ['N3Serializer'] SWAP_LOG = Namespace("http://www.w3.org/2000/10/swap/log#") class N3Serializer(TurtleSerializer): short_name = "n3" def __init__(self, store, parent=None): super(N3Serializer, self).__init__(store) self.keywords.update({OWL.sameAs: '=', SWAP_LOG.implies: '=>'}) self.parent = parent def reset(self): super(N3Serializer, self).reset() self._stores = {} def subjectDone(self, subject): super(N3Serializer, self).subjectDone(subject) if self.parent: self.parent.subjectDone(subject)
import os import rdflib import yaml from rdflib.namespace import Namespace from lxml import etree import logging log = logging.getLogger(__name__) DCT = Namespace("http://purl.org/dc/terms/") SKOS = Namespace("http://www.w3.org/2004/02/skos/core#") TERMS_OF_USE_OPEN = 'NonCommercialAllowed-CommercialAllowed-ReferenceNotRequired' # noqa TERMS_OF_USE_BY = 'NonCommercialAllowed-CommercialAllowed-ReferenceRequired' # noqa TERMS_OF_USE_ASK = 'NonCommercialAllowed-CommercialWithPermission-ReferenceNotRequired' # noqa TERMS_OF_USE_BY_ASK = 'NonCommercialAllowed-CommercialWithPermission-ReferenceRequired' # noqa VALID_TERMS_OF_USE = [ TERMS_OF_USE_BY, TERMS_OF_USE_ASK, TERMS_OF_USE_BY_ASK, TERMS_OF_USE_OPEN ] DEFAULT_TERMS_OF_USE = TERMS_OF_USE_BY namespaces = { "skos": SKOS, "dc11": "http://purl.org/dc/elements/1.1/", "foaf": "http://xmlns.com/foaf/0.1/", "dc": DCT } __location__ = \
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function ''' This module centralize udata-wide RDF helpers and configuration ''' from flask import request, url_for from rdflib import Graph, Literal, URIRef from rdflib.resource import Resource as RdfResource from rdflib.namespace import (Namespace, NamespaceManager, DCTERMS, SKOS, FOAF, XSD, RDFS) from rdflib.util import SUFFIX_FORMAT_MAP, guess_format as raw_guess_format from rdflib_jsonld.context import Context # Extra Namespaces ADMS = Namespace('http://www.w3.org/ns/adms#') DCAT = Namespace('http://www.w3.org/ns/dcat#') HYDRA = Namespace('http://www.w3.org/ns/hydra/core#') SCHEMA = Namespace('http://schema.org/') SCV = Namespace('http://purl.org/NET/scovo#') SPDX = Namespace('http://spdx.org/rdf/terms#') VCARD = Namespace('http://www.w3.org/2006/vcard/ns#') FREQ = Namespace('http://purl.org/cld/freq/') DCT = DCTERMS # More common usage namespace_manager = NamespaceManager(Graph()) namespace_manager.bind('dcat', DCAT) namespace_manager.bind('dct', DCT) namespace_manager.bind('foaf', FOAF) namespace_manager.bind('foaf', FOAF) namespace_manager.bind('hydra', HYDRA)
from rdflib.serializer import Serializer from rdflib.plugins.serializers.xmlwriter import XMLWriter from rdflib.term import URIRef, Literal, BNode from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph from six import text_type, b __all__ = ['TriXSerializer'] # TODO: Move this somewhere central TRIXNS = Namespace("http://www.w3.org/2004/03/trix/trix-1/") XMLNS = Namespace("http://www.w3.org/XML/1998/namespace") class TriXSerializer(Serializer): def __init__(self, store): super(TriXSerializer, self).__init__(store) if not store.context_aware: raise Exception( "TriX serialization only makes sense for context-aware stores") def serialize(self, stream, base=None, encoding=None, **args): nm = self.store.namespace_manager self.writer = XMLWriter(stream, nm, encoding, extra_ns={"": TRIXNS}) self.writer.push(TRIXNS[u"TriX"])
from rdflib.term import Literal, BNode, URIRef from rdflib.graph import ConjunctiveGraph from rdflib.namespace import Namespace DC = Namespace(u"http://purl.org/dc/elements/1.1/") FOAF = Namespace(u"http://xmlns.com/foaf/0.1/") graph = ConjunctiveGraph() s = BNode() graph.add((s, FOAF['givenName'], Literal('Alice'))) b = BNode() graph.add((b, FOAF['givenName'], Literal('Bob'))) graph.add((b, DC['date'], Literal("2005-04-04T04:04:04Z"))) def test_bound(): res = list( graph.query("""PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> SELECT ?name WHERE { ?x foaf:givenName ?name . OPTIONAL { ?x dc:date ?date } . FILTER ( bound(?date) ) }""")) expected = [(Literal('Bob', lang=None, datatype=None), )] assert res == expected, "Expected %s but got %s" % (expected, res) if __name__ == '__main__': test_bound()
def __init__(self, node, graph, inherited_state=None, base="", options=None): """ @param node: the current DOM Node @param graph: the RDFLib Graph @keyword inherited_state: the state as inherited from upper layers. This inherited_state is mixed with the state information retrieved from the current node. @type inherited_state: L{State.ExecutionContext} @keyword base: string denoting the base URI for the specific node. This overrides the possible base inherited from the upper layers. The current XHTML+RDFa syntax does not allow the usage of C{@xml:base}, but SVG1.2 does, so this is necessary for SVG (and other possible XML dialects that accept C{@xml:base}) @keyword options: invocation option @type options: L{Options<pyRdfa.Options>} """ #----------------------------------------------------------------- # settling the base # note that, strictly speaking, it is not necessary to add the base to the # context, because there is only one place to set it (<base> element of the <header>). # It is done because it is prepared for a possible future change in direction of # accepting xml:base on each element. # At the moment, it is invoked with a 'None' at the top level of parsing, that is # when the <base> element is looked for. if inherited_state: self.base = inherited_state.base self.options = inherited_state.options # for generic XML versions the xml:base attribute should be handled if self.options.host_language == GENERIC_XML and node.hasAttribute( "xml:base"): self.base = node.getAttribute("xml:base") else: # this is the branch called from the very top self.base = "" for bases in node.getElementsByTagName("base"): if bases.hasAttribute("href"): self.base = bases.getAttribute("href") continue if self.base == "": self.base = base # this is just to play safe. I believe this branch should actually not happen... if options == None: from pyRdfa import Options self.options = Options() else: self.options = options # xml:base is not part of XHTML+RDFa, but it is a valid setting for, say, SVG1.2 if self.options.host_language == GENERIC_XML and node.hasAttribute( "xml:base"): self.base = node.getAttribute("xml:base") self.options.comment_graph.set_base_URI( URIRef(_quote(base, self.options))) # check the the presense of the @profile and or @version attribute for the RDFa profile... # This whole branch is, however, irrelevant if the host language is a generic XML one (eg, SVG) if self.options.host_language != GENERIC_XML: doctype = None try: # I am not 100% sure the HTML5 minidom implementation has this, so let us just be # cautious here... doctype = node.ownerDocument.doctype except: pass if doctype == None or not (doctype.publicId == RDFa_PublicID and doctype.systemId == RDFa_SystemID): # next level: check the version html = node.ownerDocument.documentElement if not (html.hasAttribute("version") and RDFa_VERSION == html.getAttribute("version")): # see if least the profile has been set # Find the <head> element head = None for index in range(0, html.childNodes.length - 1): if html.childNodes.item(index).nodeName == "head": head = html.childNodes.item(index) break if not (head != None and head.hasAttribute("profile") and RDFa_PROFILE in head.getAttribute( "profile").strip().split()): if self.options.host_language == HTML5_RDFA: self.options.comment_graph.add_info( "RDFa profile or RFDa version has not been set (for a correct identification of RDFa). This is not a requirement for RDFa, but it is advised to use one of those nevertheless. Note that in the case of HTML5, the DOCTYPE setting may not work..." ) else: self.options.comment_graph.add_info( "None of the RDFa DOCTYPE, RDFa profile, or RFDa version has been set (for a correct identification of RDFa). This is not a requirement for RDFa, but it is advised to use one of those nevertheless." ) #----------------------------------------------------------------- # Settling the language tags # check first the lang or xml:lang attribute # RDFa does not allow the lang attribute. HTML5 relies :-( on @lang; # I just want to be prepared here... if options != None and options.host_language == HTML5_RDFA and node.hasAttribute( "lang"): self.lang = node.getAttribute("lang") if len(self.lang) == 0: self.lang = None elif node.hasAttribute("xml:lang"): self.lang = node.getAttribute("xml:lang") if len(self.lang) == 0: self.lang = None elif inherited_state: self.lang = inherited_state.lang else: self.lang = None #----------------------------------------------------------------- # Handling namespaces # First get the local xmlns declarations/namespaces stuff. dict = {} for i in range(0, node.attributes.length): attr = node.attributes.item(i) if attr.name.find('xmlns:') == 0: # yep, there is a namespace setting key = attr.localName if key != "": # exclude the top level xmlns setting... if key == "_": if warning: self.options.comment_graph.add_error( "The '_' local CURIE prefix is reserved for blank nodes, and cannot be changed" ) elif key.find(':') != -1: if warning: self.options.comment_graph.add_error( "The character ':' is not valid in a CURIE Prefix" ) else: # quote the URI, ie, convert special characters into %.. This is # true, for example, for spaces uri = _quote(attr.value, self.options) # 1. create a new Namespace entry ns = Namespace(uri) # 2. 'bind' it in the current graph to # get a nicer output graph.bind(key, uri) # 3. Add an entry to the dictionary dict[key] = ns # See if anything has been collected at all. # If not, the namespaces of the incoming state is # taken over self.ns = {} if len(dict) == 0 and inherited_state: self.ns = inherited_state.ns else: if inherited_state: for k in inherited_state.ns: self.ns[k] = inherited_state.ns[k] # copying the newly found namespace, possibly overwriting # incoming values for k in dict: self.ns[k] = dict[k] else: self.ns = dict # see if the xhtml core vocabulary has been set self.xhtml_prefix = None for key in self.ns.keys(): if XHTML_URI == str(self.ns[key]): self.xhtml_prefix = key break if self.xhtml_prefix == None: if XHTML_PREFIX not in self.ns: self.ns[XHTML_PREFIX] = Namespace(XHTML_URI) self.xhtml_prefix = XHTML_PREFIX else: # the most disagreeable thing, the user has used # the prefix for something else... self.xhtml_prefix = XHTML_PREFIX + '_' + ( "%d" % random.randint(1, 1000)) self.ns[self.xhtml_prefix] = Namespace(XHTML_URI) graph.bind(self.xhtml_prefix, XHTML_URI) # extra tricks for unusual usages... # if the 'rdf' prefix is not used, it is artificially added... if "rdf" not in self.ns: self.ns["rdf"] = RDF if "rdfs" not in self.ns: self.ns["rdfs"] = RDFS # Final touch: setting the default namespace... if node.hasAttribute("xmlns"): self.defaultNS = node.getAttribute("xmlns") elif inherited_state and inherited_state.defaultNS != None: self.defaultNS = inherited_state.defaultNS else: self.defaultNS = None
class FOAF(DefinedNamespace): """ Friend of a Friend (FOAF) vocabulary The Friend of a Friend (FOAF) RDF vocabulary, described using W3C RDF Schema and the Web Ontology Language. Generated from: http://xmlns.com/foaf/spec/index.rdf Date: 2020-05-26 14:20:01.597998 """ _fail = True # http://www.w3.org/1999/02/22-rdf-syntax-ns#Property account: URIRef # Indicates an account held by this agent. accountName: URIRef # Indicates the name (identifier) associated with this online account. accountServiceHomepage: URIRef # Indicates a homepage of the service provide for this online account. age: URIRef # The age in years of some agent. based_near: URIRef # A location that something is based near, for some broadly human notion of near. birthday: URIRef # The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. currentProject: URIRef # A current project this person works on. depiction: URIRef # A depiction of some thing. depicts: URIRef # A thing depicted in this representation. dnaChecksum: URIRef # A checksum for the DNA of some thing. Joke. familyName: URIRef # The family name of some person. family_name: URIRef # The family name of some person. firstName: URIRef # The first name of a person. focus: URIRef # The underlying or 'focal' entity associated with some SKOS-described concept. fundedBy: URIRef # An organization funding a project or person. geekcode: URIRef # A textual geekcode for this person, see http://www.geekcode.com/geek.html gender: URIRef # The gender of this Agent (typically but not necessarily 'male' or 'female'). givenName: URIRef # The given name of some person. givenname: URIRef # The given name of some person. holdsAccount: URIRef # Indicates an account held by this agent. img: URIRef # An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). interest: URIRef # A page about a topic of interest to this person. knows: URIRef # A person known by this person (indicating some level of reciprocated interaction between the parties). lastName: URIRef # The last name of a person. made: URIRef # Something that was made by this agent. maker: URIRef # An agent that made this thing. member: URIRef # Indicates a member of a Group membershipClass: URIRef # Indicates the class of individuals that are a member of a Group myersBriggs: URIRef # A Myers Briggs (MBTI) personality classification. name: URIRef # A name for some thing. nick: URIRef # A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). page: URIRef # A page or document about this thing. pastProject: URIRef # A project this person has previously worked on. phone: URIRef # A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). plan: URIRef # A .plan comment, in the tradition of finger and '.plan' files. primaryTopic: URIRef # The primary topic of some page or document. publications: URIRef # A link to the publications of this person. schoolHomepage: URIRef # A homepage of a school attended by the person. sha1: URIRef # A sha1sum hash, in hex. skypeID: URIRef # A Skype ID status: URIRef # A string expressing what the user is happy for the general public (normally) to know about their current activity. surname: URIRef # The surname of some person. theme: URIRef # A theme. thumbnail: URIRef # A derived thumbnail image. tipjar: URIRef # A tipjar document for this agent, describing means for payment and reward. title: URIRef # Title (Mr, Mrs, Ms, Dr. etc) topic: URIRef # A topic of some page or document. topic_interest: URIRef # A thing of interest to this person. workInfoHomepage: URIRef # A work info homepage of some person; a page about their work for some organization. workplaceHomepage: URIRef # A workplace homepage of some person; the homepage of an organization they work for. # http://www.w3.org/2000/01/rdf-schema#Class Agent: URIRef # An agent (eg. person, group, software or physical artifact). Document: URIRef # A document. Group: URIRef # A class of Agents. Image: URIRef # An image. LabelProperty: URIRef # A foaf:LabelProperty is any RDF property with textual values that serve as labels. OnlineAccount: URIRef # An online account. OnlineChatAccount: URIRef # An online chat account. OnlineEcommerceAccount: URIRef # An online e-commerce account. OnlineGamingAccount: URIRef # An online gaming account. Organization: URIRef # An organization. Person: URIRef # A person. PersonalProfileDocument: URIRef # A personal profile RDF document. Project: URIRef # A project (a collective endeavour of some kind). # http://www.w3.org/2002/07/owl#InverseFunctionalProperty aimChatID: URIRef # An AIM chat ID homepage: URIRef # A homepage for some thing. icqChatID: URIRef # An ICQ chat ID isPrimaryTopicOf: URIRef # A document that this thing is the primary topic of. jabberID: URIRef # A jabber ID for something. logo: URIRef # A logo representing some thing. mbox: URIRef # A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. mbox_sha1sum: URIRef # The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. msnChatID: URIRef # An MSN chat ID openid: URIRef # An OpenID for an Agent. weblog: URIRef # A weblog of some thing (whether person, group, company etc.). yahooChatID: URIRef # A Yahoo chat ID _NS = Namespace("http://xmlns.com/foaf/0.1/")
def bind_namespace(g, prefix, namespace): """Bind prefix to namespace in ns_mgr.""" ns = Namespace(namespace) g.namespace_manager.bind(prefix, ns, override=False) return ns
import os.path as path import logging from gocamgen.triple_pattern_finder import TriplePattern, TriplePatternFinder from gocamgen.subgraphs import AnnotationSubgraph from gocamgen.collapsed_assoc import CollapsedAssociationSet, CollapsedAssociation from gocamgen.utils import sort_terms_by_ontology_specificity, ShexHelper, ShexException # logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel("INFO") ro = OboRO() evt = Evidence() upt = UpperLevel() LEGO = Namespace("http://geneontology.org/lego/") LAYOUT = Namespace("http://geneontology.org/lego/hint/layout/") PAV = Namespace('http://purl.org/pav/') DC = Namespace("http://purl.org/dc/elements/1.1/") RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#") GOREL = Namespace("http://purl.obolibrary.org/obo/GOREL_") # Stealing a lot of code for this from ontobio.rdfgen: # https://github.com/biolink/ontobio def expand_uri_wrapper(id): c = prefix_context c['GOREL'] = "http://purl.obolibrary.org/obo/GOREL_" uri = expand_uri(id, cmaps=[c]) return uri
# -*- coding: utf-8 -*- # import psycopg2 as pg import rdflib from rdflib.namespace import Namespace, RDF, RDFS, XSD GEO = Namespace("http://www.opengis.net/ont/geosparql#") GEOX = Namespace("http://linked.data.gov.au/def/geox#") DBP = Namespace("http://dbpedia.org/property/") QUDT = Namespace("http://qudt.org/schema/qudt#") PROV = Namespace("http://www.w3.org/ns/prov#") Feature = GEO['Feature'] sfContains = GEO['sfContains'] sfWithin = GEO['sfWithin'] transitiveSfOverlap = GEOX['transitiveSfOverlap'] area = DBP['area'] unit = QUDT['unit'] numericValue = QUDT['numericValue'] sqm = QUDT['SquareMeter'] a = RDF['type'] decimalType = XSD['decimal'] doubleType = XSD['double'] r_subject = RDF['subject'] r_predicate = RDF['predicate'] r_object = RDF['object'] method = rdflib.URIRef( "http://linked.data.gov.au/def/loci/hadGenerationMethod") cc_pre = Namespace("http://linked.data.gov.au/dataset/geofabric/catchment/") mb_pre = Namespace("http://linked.data.gov.au/dataset/asgs2016/meshblock/")
def triplify(db, rdf_format, config): """Generate RDF triples from RDB using Direct Mapping approach.""" fmt2fext = dict(xml = '.rdf', nt = '.nt', turtle = '.ttl', n3 = '.n3') if rdf_format not in fmt2fext: raise IOError("Unsupported RDF serialization '{0}'.".format(rdf_format)) base_uri = config['URIs']['rdf_base'] creator_uri = config['URIs']['rdf_creator'] download_url = config['URIs']['gff_source'] species_name = config['Dataset']['species_name'] taxon_id = config['Dataset']['ncbi_taxon_id'] # define additional namespace prefixes # TODO: add namespaces to a config file OBO = Namespace('http://purl.obolibrary.org/obo/') FALDO = Namespace('http://biohackathon.org/resource/faldo#') DCMITYPE = Namespace('http://purl.org/dc/dcmitype/') SO = Namespace('http://purl.obolibrary.org/obo/so#') g = Graph() g.bind('obo', OBO) g.bind('faldo', FALDO) g.bind('dcterms', DCTERMS) g.bind('dcmitype', DCMITYPE) g.bind('so', SO) # map GFF feature types and DNA strandedness to ontology classes # Note: The 'mRNA' feature key is often used (incorrectly) in place of 'prim_transcript' # in genome annotations. The former feature MUST NOT contain introns while the latter # MAY contain introns [2]. # Feature type to SO mappings: # prim_transcript -> SO_0000120 refers to a protein-coding primary (unprocessed) transcript # mRNA -> SO_0000234 refers to a mature transcript # feature_onto_class = file_to_dict('../config/feature2class.ini') strand_onto_class = { '+' : FALDO.ForwardStrandPosition, '-' : FALDO.ReverseStrandPosition, '?' : FALDO.StrandedPosition, '.' : FALDO.Position } # add genome info to graph genome_uri = URIRef(os.path.join(base_uri, 'genome', species_name.replace(' ', '_'))) taxon_uri = OBO.term('NCBITaxon_%d' % taxon_id) g.add( (genome_uri, RDF.type, OBO.term(feature_onto_class['genome'])) ) g.add( (genome_uri, RDF.type, DCMITYPE.Dataset) ) g.add( (genome_uri, RDFS.label, Literal('genome of {0}'.format(species_name), datatype=XSD.string)) ) g.add( (genome_uri, DCTERMS.created, Literal(datetime.now().strftime("%Y-%m-%d"), datatype=XSD.date )) ) g.add( (genome_uri, DCTERMS.creator, URIRef(creator_uri)) ) g.add( (genome_uri, DCTERMS.title, Literal('genome of {0}'.format(species_name), datatype=XSD.string)) ) g.add( (genome_uri, DCTERMS.source, URIRef(download_url)) ) g.add( (genome_uri, SO.genome_of, taxon_uri) ) # N.B.: predicate has no domain/range defined g.add( (genome_uri, OBO.RO_0002162, taxon_uri) ) # use 'in taxon' alternatively g.add( (taxon_uri, RDFS.label, Literal('NCBI Taxonomy ID: {0}'.format(taxon_id), datatype=XSD.string)) ) g.add( (taxon_uri, DCTERMS.identifier, Literal(taxon_id, datatype=XSD.positiveInteger)) ) for feature in db.all_features(): if feature.strand not in strand_onto_class: raise KeyError("Incorrect strand information for feature ID '{0}'.".format(feature.id)) try: # skip GFF feature types not in feature_onto_class dict chrom = str(feature.seqid) strand_uri = strand_onto_class[feature.strand] feature_id = normalize_feature_id(feature.id) feature_type = amend_feature_type(feature.featuretype) feature_type_uri = OBO.term(feature_onto_class[feature_type]) feature_uri = URIRef(os.path.join(genome_uri, feature_type, feature_id)) seqid_uri = URIRef(os.path.join(genome_uri, 'chromosome', chrom)) region_uri = URIRef('{0}#{1}-{2}'.format(seqid_uri, feature.start, feature.end)) start_uri = URIRef('{0}#{1}'.format(seqid_uri, feature.start)) end_uri = URIRef('{0}#{1}'.format(seqid_uri, feature.end)) # add genome and chromosome info to graph # Note: the assumption is that the seqid field refers to chromosome g.add( (seqid_uri, RDF.type, OBO.term(feature_onto_class['chromosome'])) ) g.add( (seqid_uri, RDFS.label, Literal('chromosome {0}'.format(chrom), datatype=XSD.string)) ) g.add( (seqid_uri, SO.part_of, genome_uri) ) # add feature types and IDs to graph g.add( (feature_uri, RDF.type, feature_type_uri) ) g.add( (feature_uri, RDFS.label, Literal('{0} {1}'.format(feature_type, feature_id), datatype=XSD.string)) ) g.add( (feature_uri, DCTERMS.identifier, Literal(feature_id, datatype=XSD.string)) ) # add feature descriptions (from the attributes field) to graph des = get_feature_attrs(feature) if des is not None: g.add( (feature_uri, RDFS.comment, Literal(des, datatype=XSD.string)) ) # add feature start/end coordinates and strand info to graph g.add( (feature_uri, FALDO.location, region_uri) ) g.add( (region_uri, RDF.type, FALDO.Region) ) g.add( (region_uri, RDFS.label, Literal('chromosome {0}:{1}-{2}'.format(chrom, feature.start, feature.end))) ) g.add( (region_uri, FALDO.begin, start_uri) ) g.add( (start_uri, RDF.type, FALDO.ExactPosition) ) g.add( (start_uri, RDF.type, strand_uri) ) g.add( (start_uri, RDFS.label, Literal('chromosome {0}:{1}-*'.format(chrom, feature.start))) ) g.add( (start_uri, FALDO.position, Literal(feature.start, datatype=XSD.positiveInteger)) ) g.add( (start_uri, FALDO.reference, seqid_uri) ) g.add( (region_uri, FALDO.end, end_uri) ) g.add( (end_uri, RDF.type, FALDO.ExactPosition) ) g.add( (end_uri, RDF.type, strand_uri) ) g.add( (end_uri, RDFS.label, Literal('chromosome {0}:*-{1}'.format(chrom, feature.end))) ) g.add( (end_uri, FALDO.position, Literal(feature.end, datatype=XSD.positiveInteger)) ) g.add( (end_uri, FALDO.reference, seqid_uri) ) # Note: phase info is mandatory for CDS feature types but can't find a corresponding ontological term # add parent-child relationships between features to graph for child in db.children(feature, level=1): child_feature_id = normalize_feature_id(child.id) child_feature_type = amend_feature_type(child.featuretype) child_feature_uri = URIRef(os.path.join(genome_uri, child_feature_type, child_feature_id)) g.add( (feature_uri, SO.has_part, child_feature_uri) ) # use the inverse of part_of if feature_type == 'gene' and child_feature_type == 'prim_transcript': g.add( (feature_uri, SO.transcribed_to, child_feature_uri) ) except KeyError: pass outfile = os.path.splitext(db.dbfn)[0] + fmt2fext[rdf_format] with open(outfile, 'w') as fout: fout.write(g.serialize(format=rdf_format))