Python rdflib.Namespace() Examples

The following are 25 code examples of rdflib.Namespace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdflib , or try the search function .
Example #1
Source File: test_multiple_tables.py    From pycsvw with Apache License 2.0 6 votes vote down vote up
def verify_rdf(rdf_output):
    ids_ns = Namespace("http://foo.example.org/CSV/People-IDs/")
    ages_ns = Namespace("http://foo.example.org/CSV/People-Ages/")
    g = ConjunctiveGraph()
    g.parse(data=rdf_output, format="turtle")

    all_subjects = {x for x in g.subjects()}
    assert len(all_subjects) == 2

    bob_subj = ids_ns['1']
    joe_subj = ids_ns['2']
    assert bob_subj in all_subjects
    assert joe_subj in all_subjects

    # Bob's details
    assert len([g.triples((bob_subj, ids_ns.id, Literal(1)))]) == 1
    assert len([g.triples((bob_subj, ids_ns.name, Literal("Bob")))]) == 1
    assert len([g.triples((bob_subj, ages_ns.age, Literal(34)))]) == 1

    # Joe's details
    assert len([g.triples((joe_subj, ids_ns.id, Literal(2)))]) == 1
    assert len([g.triples((joe_subj, ids_ns.name, Literal("Joe")))]) == 1
    assert len([g.triples((joe_subj, ages_ns.age, Literal(54)))]) == 1 
Example #2
Source File: lmdb_store.py    From lakesuperior with Apache License 2.0 6 votes vote down vote up
def bind(self, prefix, namespace):
        """
        Bind a prefix to a namespace.

        :param str prefix: Namespace prefix.
        :param rdflib.URIRef namespace: Fully qualified URI of namespace.
        """
        prefix = prefix.encode()
        namespace = namespace.encode()
        if self.is_txn_rw:
            # FIXME DB labels should be constants but there are problems
            # imprting them from the Cython module.
            self.put(prefix, namespace, b'pfx:ns_')
            self.put(namespace, prefix, b'ns:pfx_')
        else:
            #logger.debug('Opening RW transaction.')
            with self.txn_ctx(write=True) as wtxn:
                self.put(prefix, namespace, b'pfx:ns_')
                self.put(namespace, prefix, b'ns:pfx_') 
Example #3
Source File: prov.py    From grlc with MIT License 6 votes vote down vote up
def __init__(self, user, repo):
        """Default constructor.

        Keyword arguments:
        user -- Github user.
        repo -- Github repo.
        """
        self.user = user
        self.repo = repo
        self.prov_g = Graph()
        prov_uri = URIRef("http://www.w3.org/ns/prov#")
        self.prov = Namespace(prov_uri)
        self.prov_g.bind('prov', self.prov)

        self.agent = URIRef("http://{}".format(static.SERVER_NAME))
        self.entity_d = URIRef("http://{}/api/{}/{}/spec".format(static.SERVER_NAME, self.user, self.repo))
        self.activity = URIRef(self.entity_d + "-activity")

        self.init_prov_graph() 
Example #4
Source File: rdf.py    From tools-python with Apache License 2.0 5 votes vote down vote up
def __init__(self, builder, logger):
        self.logger = logger
        self.doap_namespace = Namespace('http://usefulinc.com/ns/doap#')
        self.spdx_namespace = Namespace("http://spdx.org/rdf/terms#")
        self.builder = builder 
Example #5
Source File: config.py    From Skosify with MIT License 5 votes vote down vote up
def parse_config(self, cfgparser):

        # parse namespaces from configuration file
        for prefix, uri in cfgparser.items('namespaces'):
            self.namespaces[prefix] = Namespace(uri)

        # parse types from configuration file
        for key, val in cfgparser.items('types'):
            self.types[expand_curielike(self.namespaces, key)] = \
                expand_mapping_target(self.namespaces, val)

        # parse literals from configuration file
        for key, val in cfgparser.items('literals'):
            self.literals[expand_curielike(self.namespaces, key)] = \
                expand_mapping_target(self.namespaces, val)

        # parse relations from configuration file
        for key, val in cfgparser.items('relations'):
            self.relations[expand_curielike(self.namespaces, key)] = \
                expand_mapping_target(self.namespaces, val)

        # parse options from configuration file
        for opt, val in cfgparser.items('options'):
            if not hasattr(self, opt) or opt in ['types', 'literals', 'relations', 'namespaces']:
                logging.warning('Ignoring unknown configuration option: %s', opt)
                continue
            if getattr(self, opt) in (True, False):  # is a Boolean option
                setattr(self, opt, cfgparser.getboolean('options', opt))
            else:
                setattr(self, opt, val) 
Example #6
Source File: rdf_graph_mixin.py    From kgx with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, source_graph: nx.MultiDiGraph = None):
        if source_graph:
            self.graph = source_graph
        else:
            self.graph = nx.MultiDiGraph()

        self.graph_metadata = {}
        self.prefix_manager = PrefixManager()
        self.DEFAULT = Namespace(self.prefix_manager.prefix_map[':'])
        # TODO: use OBO IRI from biolink model context once https://github.com/biolink/biolink-model/issues/211 is resolved
        self.OBO = Namespace('http://purl.obolibrary.org/obo/')
        self.OBAN = Namespace(self.prefix_manager.prefix_map['OBAN'])
        self.PMID = Namespace(self.prefix_manager.prefix_map['PMID'])
        self.BIOLINK = Namespace(self.prefix_manager.prefix_map['biolink']) 
Example #7
Source File: test_rdf.py    From kgx with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_load():
    """
    load TTL and save as CSV
    """
    input_file = os.path.join(resource_dir, 'monarch/biogrid_test.ttl')
    output_file = os.path.join(target_dir, 'test_output.ttl')

    t = ObanRdfTransformer()
    t.parse(input_file, input_format="turtle")
    t.report()
    t.save(output_file, output_format="turtle")

    output_archive_file = os.path.join(target_dir, 'biogrid_test')
    pt = PandasTransformer(t.graph)
    pt.save(output_archive_file)

    # read again the source, test graph
    src_graph = rdflib.Graph()
    src_graph.parse(input_file, format="turtle")

    # read again the dumped target graph
    target_graph = rdflib.Graph()
    target_graph.parse(output_file, format="turtle")

    # compare subgraphs from the source and the target graph.
    OBAN = Namespace('http://purl.org/oban/')
    for a in src_graph.subjects(RDF.type, OBAN.association):
        oban_src_graph = rdflib.Graph()
        oban_src_graph += src_graph.triples((a, None, None))
        oban_tg_graph = rdflib.Graph()
        oban_tg_graph += target_graph.triples((a, None, None))
        # see they are indeed identical (isomorphic)
        if not oban_src_graph.isomorphic(oban_tg_graph):
            print('The subgraphs whose subject is {} are not isomorphic'.format(a))

    # w2 = GraphMLTransformer(t.graph)
    # w2.save(os.path.join(tpath, "x1n.graphml"))
    w3 = JsonTransformer(t.graph)
    w3.save(os.path.join(target_dir, "biogrid_test.json")) 
Example #8
Source File: naiveKGQA.py    From HarvestText with MIT License 5 votes vote down vote up
def build_KG(self, SVOs, ht_SVO):
        namespace0 = Namespace(self.default_namespace)
        g = Graph()
        type_word_dict = {"实体":set(),"谓词":set()}
        for (s,v,o) in SVOs:
            type_word_dict["实体"].add(s)
            type_word_dict["实体"].add(o)
            type_word_dict["谓词"].add(v)
            g.add((namespace0[s], namespace0[v], namespace0[o]))
        ht_SVO.add_typed_words(type_word_dict)
        return g 
Example #9
Source File: void.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def prep_graph(self):
        """ prepares a graph for Pelagios """
        self.g = Graph()
        for prefix, ns_uri in self.NAMESPACES.items():
            ns = Namespace(ns_uri)
            self.g.bind(prefix, ns) 
Example #10
Source File: gazgraph.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def prep_graph(self):
        """ prepares a graph for Pelagios """
        self.g = Graph()
        for prefix, ns_uri in self.NAMESPACES.items():
            ns = Namespace(ns_uri)
            self.g.bind(prefix, ns) 
Example #11
Source File: graph.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def prep_graph(self):
        """ prepares a graph for Pelagios """
        self.g = Graph()
        for prefix, ns_uri in self.NAMESPACES.items():
            ns = Namespace(ns_uri)
            self.g.bind(prefix, ns) 
Example #12
Source File: brick_parser2.py    From plastering with MIT License 5 votes vote down vote up
def get_prefixes(version):
    BRICK = Namespace('https://brickschema.org/schema/{0}/Brick#'.format(version))
    BRICKFRAME = Namespace('https://brickschema.org/schema/{0}/BrickFrame#'.format(version))
    BRICKTAG = Namespace('https://brickschema.org/schema/{0}/BrickTag#'.format(version))
    return {
        'brick': BRICK,
        'bf': BRICKFRAME,
        'tag': BRICKTAG,
        'rdfs': rdflib.RDFS,
        'rdf': rdflib.RDF,
        'owl': rdflib.OWL,
    } 
Example #13
Source File: __init__.py    From plastering with MIT License 5 votes vote down vote up
def __init__(self,
                 empty=False,
                 version='1.0.2',
                 brick_file='brick/Brick_1_0_2.ttl',
                 brickframe_file='brick/BrickFrame_1_0_2.ttl',
                 triplestore_type=RDFLIB
                 ):
        self.triplestore_type = triplestore_type
        self._brick_version = version
        if self.triplestore_type == RDFLIB:
            self.base_package = rdflib_wrapper
        elif self.triplestore_type == VIRTUOSO:
            self.base_package = virtuoso_wrapper
        self.g = self.base_package.init_graph(empty, brick_file,
                                              brickframe_file)
        self.BRICK = Namespace('https://brickschema.org/schema/{0}/Brick#'
                               .format(self._brick_version))
        self.BF = Namespace('https://brickschema.org/schema/{0}/BrickFrame#'
                            .format(self._brick_version))
        self.BASE = Namespace('http://example.com#')
        self.sparql_prefix = """
        prefix brick: <{0}>
        prefix rdf: <{1}>
        prefix rdfs: <{2}>
        prefix base: <{3}>
        prefix bf: <{4}>
        prefix owl: <{5}>
        """.format(str(self.BRICK), RDF, RDFS, self.BASE, str(self.BF), OWL) 
Example #14
Source File: rdf.py    From tools-python with Apache License 2.0 5 votes vote down vote up
def __init__(self, document, out):
        self.document = document
        self.out = out
        self.doap_namespace = Namespace('http://usefulinc.com/ns/doap#')
        self.spdx_namespace = Namespace("http://spdx.org/rdf/terms#")
        self.graph = Graph() 
Example #15
Source File: test_1_0_lmdb_store.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def bindings(self):
        return (
            ('ns1', Namespace('http://test.org/ns#')),
            ('ns2', Namespace('http://my_org.net/ns#')),
            ('ns3', Namespace('urn:test:')),
            ('ns4', Namespace('info:myinst/graph#')),
        ) 
Example #16
Source File: lmdb_store.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def namespaces(self):
        """Get an iterator of all prefix: namespace bindings.

        :rtype: Iterator(tuple(str, rdflib.Namespace))
        """
        for pfx, ns in self.all_namespaces():
            yield (pfx, Namespace(ns)) 
Example #17
Source File: lmdb_store.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def prefix(self, namespace):
        """
        Get the prefix associated with a namespace.

        **Note:** A namespace can be only bound to one prefix in this
        implementation.

        :param rdflib.Namespace namespace: Fully qualified namespace.

        :rtype: str or None
        """
        prefix = self.get_data(str(namespace).encode(), b'ns:pfx_')

        return prefix.decode() if prefix is not None else None 
Example #18
Source File: lmdb_store.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def namespace(self, prefix):
        """
        Get the namespace for a prefix.
        :param str prefix: Namespace prefix.
        """
        ns = self.get_data(prefix.encode(), b'pfx:ns_')

        return Namespace(ns.decode()) if ns is not None else None 
Example #19
Source File: Mapper.py    From table-extractor with GNU General Public License v3.0 5 votes vote down vote up
def define_namespace(self):
        """
        Method used to set standard names (dbr stands for dbpediaresource, dbp for dbpediaproperty,
          dbo for dbpediaontology)

        :return:
        """

        if self.chapter != 'en':
            self.dbr = rdflib.Namespace("http://" + self.chapter + ".dbpedia.org/resource/")
        else:
            self.dbr = rdflib.Namespace("http://dbpedia.org/resource/")

        self.dbo = rdflib.Namespace("http://dbpedia.org/ontology/")
        self.dbp = rdflib.Namespace("http://dbpedia.org/property/") 
Example #20
Source File: RDFGraph.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bind_all_namespaces(self):
        """
            Results in the RDF @prefix directives for every ingest
            being added to this ingest.
        """
        for prefix in self.curie_map.keys():
            iri = self.curie_map[prefix]
            self.bind(prefix, Namespace(iri))
        return

    # serialize() conflicts between rdflib & Graph.serialize abstractmethod
    # GraphUtils expects the former.  (too bad there is no multiple dispatch) 
Example #21
Source File: RDFGraph.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _getnode(self, curie):  # convention is lowercase names
        """
        This is a wrapper for creating a URIRef or Bnode object
        with a given a curie or iri as a string.

        If an id starts with an underscore, it assigns it to a BNode, otherwise
        it creates it with a standard URIRef.
        Alternatively, self.skolemize_blank_node is True,
        it will skolemize the blank node

        :param curie: str identifier formatted as curie or iri
        :return: node: RDFLib URIRef or BNode object
        """
        node = None
        if curie[0] == '_':
            if self.are_bnodes_skized is True:
                node = self.skolemizeBlankNode(curie)
            else:  # delete the leading underscore to make it cleaner
                node = BNode(re.sub(r'^_:|^_', '', curie, 1))

        # Check if curie string is actually an IRI
        elif curie[:4] == 'http' or curie[:3] == 'ftp' or curie[:4] == 'jdbc':
            node = URIRef(curie)
        else:
            iri = RDFGraph.curie_util.get_uri(curie)
            if iri is not None:
                node = URIRef(RDFGraph.curie_util.get_uri(curie))
                # Bind prefix map to graph
                prefix = curie.split(':')[0]
                if prefix not in self.namespace_manager.namespaces():
                    mapped_iri = self.curie_map[prefix]
                    self.bind(prefix, Namespace(mapped_iri))
            else:
                LOG.error("couldn't make URI for %s", curie)
                # get a sense of where the CURIE-ish? thing is comming from
                # magic number here is "steps up the call stack"
                for call in range(3, 0, -1):
                    LOG.warning(
                        '\t%sfrom: %s', '\t' * call, sys._getframe(call).f_code.co_name)
        return node 
Example #22
Source File: RDFGraph.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, are_bnodes_skized=True, identifier=None):
        # print("in RDFGraph  with id: ", identifier)
        super().__init__('IOMemory', identifier)
        self.are_bnodes_skized = are_bnodes_skized

        # Can be removed when this is resolved
        # https://github.com/RDFLib/rdflib/issues/632
        for pfx in ('OBO',):  # , 'ORPHA'):
            self.bind(pfx, Namespace(self.curie_map[pfx]))

        # try adding them all
        # self.bind_all_namespaces()  # too much 
Example #23
Source File: solr_ontology_tagger.py    From solr-ontology-tagger with GNU General Public License v3.0 4 votes vote down vote up
def get_labels(self, subject):

		labels = []
	
		# append RDFS.labels
		for label in self.objects(subject=subject, predicate=rdflib.RDFS.label):

			if self.languages:
				if label.language in self.languages:
					labels.append(label)
			else:
				labels.append(label)

		#
		# append SKOS labels
		#
			
		# append SKOS prefLabel
		skos = rdflib.Namespace('http://www.w3.org/2004/02/skos/core#')
		for label in self.objects(subject=subject, predicate=skos['prefLabel']):

			if self.languages:
				if label.language in self.languages:
					labels.append(label)
			else:
				labels.append(label)

		# append SKOS altLabels
		for label in self.objects(subject=subject, predicate=skos['altLabel']):
			if self.languages:
				if label.language in self.languages:
					labels.append(label)
			else:
				labels.append(label)

		# append SKOS hiddenLabels
		for label in self.objects(subject=subject, predicate=skos['hiddenLabel']):
			if self.languages:
				if label.language in self.languages:
					labels.append(label)
			else:
				labels.append(label)

		return labels



	# best/preferred label as title 
Example #24
Source File: data_store.py    From pyaff4 with Apache License 2.0 4 votes vote down vote up
def _DumpToTurtle(self, volumeurn, verbose=False):
        g = rdflib.Graph()
        g.bind("aff4", rdflib.Namespace(self.lexicon.base))

        # looks like rdflib has some problems with re-constituting subjects using @base
        # comment out for now
        #volumeNamespace = rdflib.Namespace(volumeurn.value + "/")
        #volumeBase = volumeurn.value + "/"

        for urn, items in self.store.items():
            urn = utils.SmartUnicode(urn)
            type = items.get(utils.SmartUnicode(lexicon.AFF4_TYPE))

            # only dump objects and pseudo map entries
            if type is None:
                if not urn.startswith(u"aff4:sha512:"):
                    continue

            for attr, value in list(items.items()):
                attr = utils.SmartUnicode(attr)
                # We suppress certain facts which can be deduced from the file
                # format itself. This ensures that we do not have conflicting
                # data in the data store. The data in the data store is a
                # combination of explicit facts and implied facts.
                if not verbose:
                    if attr.startswith(lexicon.AFF4_VOLATILE_NAMESPACE):
                        continue

                if not isinstance(value, list):
                    value = [value]

                for item in value:
                    if self._should_ignore(urn, attr, item):
                        continue
                    g.add((rdflib.URIRef(urn), rdflib.URIRef(attr), item.GetRaptorTerm()))

        #result = g.serialize(format='turtle', base=volumeNamespace)
        result = g.serialize(format='turtle')
        result = utils.SmartUnicode(result)
        #basestart = "@base <%s> .\r\n" % (volumeBase)
        #result = basestart + result

        return result 
Example #25
Source File: rdffile.py    From arches with GNU Affero General Public License v3.0 4 votes vote down vote up
def write_resources(self, graph_id=None, resourceinstanceids=None, **kwargs):
        super(RdfWriter, self).write_resources(graph_id=graph_id, resourceinstanceids=resourceinstanceids, **kwargs)
        g = self.get_rdf_graph()
        value = g.serialize(format="nquads").decode("utf-8")

        # print(f"Got graph: {value}")
        js = from_rdf(value, {"format": "application/nquads", "useNativeTypes": True})

        assert len(resourceinstanceids) == 1  # currently, this should be limited to a single top resource

        archesproject = Namespace(settings.ARCHES_NAMESPACE_FOR_DATA_EXPORT)
        resource_inst_uri = archesproject[reverse("resources", args=[resourceinstanceids[0]]).lstrip("/")]

        context = self.graph_model.jsonldcontext
        framing = {"@omitDefault": True, "@omitGraph": False, "@id": str(resource_inst_uri)}

        if context:
            framing["@context"] = context

        js = frame(js, framing)

        try:
            context = JSONDeserializer().deserialize(context)
        except ValueError:
            if context == "":
                context = {}
            context = {"@context": context}
        except AttributeError:
            context = {"@context": {}}

        # Currently omitGraph is not processed by pyLd, but data is compacted
        # simulate omitGraph:
        if "@graph" in js and len(js["@graph"]) == 1:
            # merge up
            for (k, v) in list(js["@graph"][0].items()):
                js[k] = v
            del js["@graph"]

        out = json.dumps(js, indent=kwargs.get("indent", None), sort_keys=True)
        dest = StringIO(out)

        full_file_name = os.path.join("{0}.{1}".format(self.file_name, "jsonld"))
        return [{"name": full_file_name, "outputfile": dest}]