Method attempts to add output to Blazegraph RDF Triplestore
187879
def add_to_triplestore(self, output):
        """"""
        if len(output) > 0:
            result = self.ext_conn.load_data(data=output.serialize(),
                                             datatype='rdf')
973433
def _parse_graph(self):

		'''
		
		'''

		# if resource exists, parse self.rdf.data
		if self.exists:
			self.rdf.graph = self.repo.api.parse_rdf_payload(self.rdf.data, self.headers)

		# else, create empty graph
		else:
			self.rdf.graph = rdflib.Graph()

		# bind any additional namespaces from repo instance, but do not override
		self.rdf.namespace_manager = rdflib.namespace.NamespaceManager(self.rdf.graph)
		for ns_prefix, ns_uri in self.rdf.prefixes.__dict__.items():
			self.rdf.namespace_manager.bind(ns_prefix, ns_uri, override=False)

		# conversely, add namespaces from parsed graph to self.rdf.prefixes
		for ns_prefix, ns_uri in self.rdf.graph.namespaces():
			setattr(self.rdf.prefixes, ns_prefix, rdflib.Namespace(ns_uri))
			setattr(self.rdf.uris, rdflib.Namespace(ns_uri), ns_prefix)

		# pin old graph to resource, create copy graph for modifications
		self.rdf._orig_graph = copy.deepcopy(self.rdf.graph)

		# parse triples for object-like access
		self.parse_object_like_triples()
837789
function _graphToRDF(graph, namer) {
  var rval = [];

  var ids = Object.keys(graph).sort();
  for(var i = 0; i < ids.length; ++i) {
    var id = ids[i];
    var node = graph[id];
    var properties = Object.keys(node).sort();
    for(var pi = 0; pi < properties.length; ++pi) {
      var property = properties[pi];
      var items = node[property];
      if(property === '@type') {
        property = RDF_TYPE;
      }
      else if(_isKeyword(property)) {
        continue;
      }

      for(var ii = 0; ii < items.length; ++ii) {
        var item = items[ii];

        // RDF subject
        var subject = {};
        subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
        subject.value = id;

        // RDF predicate
        var predicate = {};
        predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';
        predicate.value = property;

        // convert @list to triples
        if(_isList(item)) {
          _listToRDF(item['@list'], namer, subject, predicate, rval);
        }
        // convert value or node object to triple
        else {
          var object = _objectToRDF(item);
          rval.push({subject: subject, predicate: predicate, object: object});
        }
      }
    }
  }

  return rval;
}
1190558
def serialize(self, format="turtle"):
        
        if self.triples:
            if not self.rdfgraph:
                self._buildGraph()
            return self.rdfgraph.serialize(format=format)
        else:
            return None
1364226
def rdf2dot( g, stream, opts={} ):
    

    accept_lang = set( opts.get('lang',[]) )
    do_literal = opts.get('literal')
    nodes = {}
    links = []

    def node_id(x):
        if x not in nodes:
            nodes[x] = "node%d" % len(nodes)
        return nodes[x]

    def qname(x, g):
        try:
            q = g.compute_qname(x)
            return q[0] + ":" + q[2]
        except:
            return x

    def accept( node ):
        if isinstance( node, (rdflib.URIRef,rdflib.BNode) ):
            return True
        if not do_literal:
            return False
        return (not accept_lang) or (node.language in accept_lang)


    stream.write( u'digraph { \n node [ fontname="DejaVu Sans,Tahoma,Geneva,sans-serif" ] ; \n' )

    # Write all edges. In the process make a list of all nodes
    for s, p, o in g:
        # skip triples for labels
        if p == rdflib.RDFS.label:
            continue

        # Create a link if both objects are graph nodes
        # (or, if literals are also included, if their languages match)
        if not (accept(s) and accept(o)):
            continue

        # add the nodes to the list
        sn = node_id(s)
        on = node_id(o)

        # add the link
        q = qname(p,g)
        if isinstance(p, rdflib.URIRef):
            opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s", href="%s", target="_other" ] ;\n' % (sn,on,q,p)
        else:
            opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s" ] ;\n'%(sn,on,q)
        stream.write( opstr )

    # Write all nodes
    for u, n in nodes.items():
        lbl = escape( label(u,g,accept_lang), True )
        if isinstance(u, rdflib.URIRef):
            opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s", href="%s", target=_other ] \n' % (n, 'blue', lbl, u )
        else:
            opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s" ] \n' % (n, 'black', lbl )
        stream.write( u"# %s %s\n" % (u, n) )
        stream.write( opstr )

    stream.write(u'}\n')
1287263
def _update_triplestore(self, es_result, action_list, **kwargs):
        
        idx_time = XsdDatetime(datetime.datetime.utcnow())
        uri_keys = {}
        bnode_keys = {}
        for item in action_list:
            try:
                uri_keys[item['_id']] = item['_source']["uri"]
            except KeyError:
                bnode_keys[item['_id']] = item['_id']
        error_dict = {}
        error_bnodes = {}
        if es_result[1]:
            for result in es_result[1]:
                err_item = list(result.values())[0]
                try:
                    error_dict[uri_keys.pop(err_item['_id'])] = \
                            XsdString(err_item['error']['reason'])
                except KeyError:
                    error_bnodes[bnode_keys.pop(err_item['_id'])] = \
                            XsdString(err_item['error']['reason'])
        if uri_keys:
            sparql_good = """
                DELETE
                {{
                    ?s kds:esIndexTime ?esTime .
                    ?s kds:esIndexError ?esError .
                }}
                INSERT
                {{
                    GRAPH ?g {{ ?s kds:esIndexTime {idx_time} }}.
                }}
                WHERE
                {{
                    VALUES ?s {{ {subj_list} }} .
                    {{
                        SELECT DISTINCT ?g ?s ?esTime ?esError
                        {{
                            GRAPH ?g {{ ?s ?p ?o }} .
                            OPTIONAL {{
                                ?s kds:esIndexTime ?esTime
                            }}
                            OPTIONAL {{
                                ?s kds:esIndexError ?esError
                            }}
                        }}
                    }}
                }}
                """.format(idx_time=idx_time.sparql,
                           subj_list="<%s>" % ">\n<".join(uri_keys.values()))
            self.tstore_conn.update_query(sparql_good)
        # Process any errors that were found.
        if not error_dict:
            return
        # Delete all indexing triples related to the error subjects
        sparql_error = """
            DELETE
            {{
                ?s kds:esIndexTime ?esTime .
                ?s kds:esIndexError ?esError .
            }}
            WHERE
            {{
                VALUES ?s {{ {subj_list} }} .
                OPTIONAL {{
                    ?s kds:esIndexTime ?esTime
                }}
                OPTIONAL {{
                    ?s kds:esIndexError ?esError
                }}
            }}
            """.format(subj_list="<%s>" % ">\n<".join(error_dict.keys()))
        self.tstore_conn.update_query(sparql_error)
        del sparql_error
        sparql_update = """
            INSERT
            {{
                GRAPH ?g {{
                    ?s kds:esIndexTime {idx_time} .
                    ?s kds:esIndexError ?esError .
                }}
            }}
            WHERE
            {{
                VALUES (?s ?esError) {{ {error_list} }} .
                {{
                    SELECT DISTINCT ?g ?s
                    {{
                        graph ?g {{?s ?p ?o}}
                    }}
                }}
            }}""".format(
                    idx_time=idx_time.sparql,
                    error_list="\n".join(["(<%s> %s)" % (key, val.sparql)
                                          for key, val in error_dict.items()]))

        # Create a turtle data stream of the new errors to upload into the
        # triplestore
        self.tstore_conn.update_query(sparql_update)
        del sparql_update
772610
def nx_to_ontology(graph, source_node, output_path, base_iri):
    
    ontology = owlready.Ontology(base_iri)

    parent_lookup = {
        source_node: types.new_class(source_node, (owlready.Thing,), kwds={"ontology": ontology})
    }

    def recur(pnode):
        for neighbor in graph.neighbors(pnode):
            data = graph.node[neighbor]
            neighbor_class = types.new_class(neighbor, (parent_lookup[pnode],), kwds={"ontology": ontology})
            owlready.ANNOTATIONS[neighbor_class].add_annotation(owlready.rdfs.label, data['label'])
            recur(neighbor)

    recur(source_node)

    ontology.save(filename=output_path)
161726
protected void add(SubjectNode subject,
                       RDFName predicate,
                       ObjectNode object,
                       Set<Triple> set) throws ResourceIndexException {
        set.add(new SimpleTriple(subject, predicate, object));
    }
516753
void graphToRDF(String graphName, Map<String, Object> graph) {
        // 4.2)
        final List<Quad> triples = new ArrayList<Quad>();
        // 4.3)
        final List<String> subjects = new ArrayList<String>(graph.keySet());
        // Collections.sort(subjects);
        for (final String id : subjects) {
            if (JsonLdUtils.isRelativeIri(id)) {
                continue;
            }
            final Map<String, Object> node = (Map<String, Object>) graph.get(id);
            final List<String> properties = new ArrayList<String>(node.keySet());
            Collections.sort(properties);
            for (String property : properties) {
                final List<Object> values;
                // 4.3.2.1)
                if ("@type".equals(property)) {
                    values = (List<Object>) node.get("@type");
                    property = RDF_TYPE;
                }
                // 4.3.2.2)
                else if (isKeyword(property)) {
                    continue;
                }
                // 4.3.2.3)
                else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) {
                    continue;
                }
                // 4.3.2.4)
                else if (JsonLdUtils.isRelativeIri(property)) {
                    continue;
                } else {
                    values = (List<Object>) node.get(property);
                }

                Node subject;
                if (id.indexOf("_:") == 0) {
                    // NOTE: don't rename, just set it as a blank node
                    subject = new BlankNode(id);
                } else {
                    subject = new IRI(id);
                }

                // RDF predicates
                Node predicate;
                if (property.startsWith("_:")) {
                    predicate = new BlankNode(property);
                } else {
                    predicate = new IRI(property);
                }

                for (final Object item : values) {
                    // convert @list to triples
                    if (isList(item)) {
                        final List<Object> list = (List<Object>) ((Map<String, Object>) item)
                                .get("@list");
                        Node last = null;
                        Node firstBNode = nil;
                        if (!list.isEmpty()) {
                            last = objectToRDF(list.get(list.size() - 1));
                            firstBNode = new BlankNode(api.generateBlankNodeIdentifier());
                        }
                        triples.add(new Quad(subject, predicate, firstBNode, graphName));
                        for (int i = 0; i < list.size() - 1; i++) {
                            final Node object = objectToRDF(list.get(i));
                            triples.add(new Quad(firstBNode, first, object, graphName));
                            final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier());
                            triples.add(new Quad(firstBNode, rest, restBNode, graphName));
                            firstBNode = restBNode;
                        }
                        if (last != null) {
                            triples.add(new Quad(firstBNode, first, last, graphName));
                            triples.add(new Quad(firstBNode, rest, nil, graphName));
                        }
                    }
                    // convert value or node object to triple
                    else {
                        final Node object = objectToRDF(item);
                        if (object != null) {
                            triples.add(new Quad(subject, predicate, object, graphName));
                        }
                    }
                }
            }
        }
        put(graphName, triples);
    }
355914
def _parse_rdf(self, file):
        
        store = Graph()
        store.parse(file)

        print len(store)
943494
def fetch(rdf_url, from_remote: nil)
      begin
        graph = fetch_cached_graph(rdf_url)

        if graph.nil? && !from_remote
          raise TriplestoreAdapter::TriplestoreException, "graph not found in cache. Skipping fetch from remote graph"
        elsif graph.nil?
          graph = fetch_and_cache_graph(rdf_url)
        end

        graph
      rescue => e
        raise TriplestoreAdapter::TriplestoreException, e.message
      end
    end
551038
def process(source, target, rdfsonly, base=None, logger=logging):
    '''
    

    '''
    for link in source.match():
        s, p, o = link[:3]
        #SKip docheader statements
        if s == (base or '') + '@docheader': continue
        if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
        if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
        if p == VERSA_BASEIRI + 'refines':
            tlinks = list(source.match(s, TYPE_REL))
            if tlinks:
                if tlinks[0][TARGET] == VERSA_BASEIRI + 'Resource':
                    p = I(RDFS_NAMESPACE + 'subClassOf')
                elif tlinks[0][TARGET] == VERSA_BASEIRI + 'Property':
                    p = I(RDFS_NAMESPACE + 'subPropertyOf')
        if p == VERSA_BASEIRI + 'properties':
            suri = I(iri.absolutize(s, base)) if base else s
            target.add((URIRef(o), URIRef(RDFS_NAMESPACE + 'domain'), URIRef(suri)))
            continue
        if p == VERSA_BASEIRI + 'value':
            if o not in ['Literal', 'IRI']:
                ouri = I(iri.absolutize(o, base)) if base else o
                target.add((URIRef(s), URIRef(RDFS_NAMESPACE + 'range'), URIRef(ouri)))
                continue
        s = URIRef(s)
        #Translate v:type to rdf:type
        p = RDF.type if p == TYPE_REL else URIRef(p)
        o = URIRef(o) if isinstance(o, I) else Literal(o)
        if not rdfsonly or p.startswith(RDF_NAMESPACE) or p.startswith(RDFS_NAMESPACE):
            target.add((s, p, o))
    return
589105
def _buildTemplates(self):
        

        jsontree_classes = build_D3treeStandard(
            0, 99, 1, self.ontospy_graph.toplayer_classes)
        c_total = len(self.ontospy_graph.all_classes)

        JSON_DATA_CLASSES = json.dumps({
            'children': jsontree_classes,
            'name': 'owl:Thing',
        })

        extra_context = {
            "ontograph": self.ontospy_graph,
            "TOTAL_CLASSES": c_total,
            'JSON_DATA_CLASSES': JSON_DATA_CLASSES,
        }

        # Ontology - MAIN PAGE
        contents = self._renderTemplate(
            "d3/d3_rotatingCluster.html", extraContext=extra_context)
        FILE_NAME = "index.html"
        main_url = self._save2File(contents, FILE_NAME, self.output_path)

        return main_url
468573
def loading_failed(self, rdf_format_opts, uri=""):
        """"""
        if uri:
            uri = " <%s>" % str(uri)
        printDebug(
            "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)"
            % (uri, str(rdf_format_opts)), "red")
        printDebug(
            "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>"
        )

        return
416224
def resource_to_rdf(resource, dataset=None, graph=None):
    '''
    
    '''
    graph = graph or Graph(namespace_manager=namespace_manager)
    if dataset and dataset.id:
        id = URIRef(url_for('datasets.show_redirect', dataset=dataset.id,
                            _external=True,
                            _anchor='resource-{0}'.format(resource.id)))
    else:
        id = BNode(resource.id)
    permalink = url_for('datasets.resource', id=resource.id, _external=True)
    r = graph.resource(id)
    r.set(RDF.type, DCAT.Distribution)
    r.set(DCT.identifier, Literal(resource.id))
    r.add(DCT.title, Literal(resource.title))
    r.add(DCT.description, Literal(resource.description))
    r.add(DCAT.downloadURL, URIRef(resource.url))
    r.add(DCAT.accessURL, URIRef(permalink))
    r.add(DCT.issued, Literal(resource.published))
    r.add(DCT.modified, Literal(resource.modified))
    if dataset and dataset.license:
        r.add(DCT.rights, Literal(dataset.license.title))
        if dataset.license.url:
            r.add(DCT.license, URIRef(dataset.license.url))
    if resource.filesize is not None:
        r.add(DCAT.bytesSize, Literal(resource.filesize))
    if resource.mime:
        r.add(DCAT.mediaType, Literal(resource.mime))
    if resource.format:
        r.add(DCT.term('format'), Literal(resource.format))
    if resource.checksum:
        checksum = graph.resource(BNode())
        checksum.set(RDF.type, SPDX.Checksum)
        algorithm = 'checksumAlgorithm_{0}'.format(resource.checksum.type)
        checksum.add(SPDX.algorithm, getattr(SPDX, algorithm))
        checksum.add(SPDX.checksumValue, Literal(resource.checksum.value))
        r.add(SPDX.checksum, checksum)
    return r
121096
def rdfgraph_to_ontol(rg):
    
    digraph = networkx.MultiDiGraph()
    from rdflib.namespace import RDF
    label_map = {}
    for c in rg.subjects(RDF.type, OWL.Class):
        cid = contract_uri_wrap(c)
        logging.info("C={}".format(cid))
        for lit in rg.objects(c, RDFS.label):
            label_map[cid] = lit.value
            digraph.add_node(cid, label=lit.value)
        for s in rg.objects(c, RDFS.subClassOf):
            # todo - blank nodes
            sid = contract_uri_wrap(s)
            digraph.add_edge(sid, cid, pred='subClassOf')

    logging.info("G={}".format(digraph))
    payload = {
        'graph': digraph,
        #'xref_graph': xref_graph,
        #'graphdoc': obographdoc,
        #'logical_definitions': logical_definitions
    }
            
    ont = Ontology(handle='wd', payload=payload)
    return ont
545345
def arcsOut(G: Graph, n: Node) -> RDFGraph:
    
    return RDFGraph(G.triples((n, None, None)))