Definition row graph: an RDF graph consisting of the following triples:

- a reference triple for each <column name list> in a table's foreign keys where none of the column values is NULL.
19013
private ImmutableList<TargetAtom> getRefCQ(ForeignKeyConstraint fk) {
        ImmutableTerm sub = generateSubject(fk.getRelation(), true);
		ImmutableTerm obj = generateSubject(fk.getReferencedRelation(), true);

		TargetAtom atom = getAtom(getReferencePropertyIRI(fk), sub, obj);
		return ImmutableList.of(atom);
	}
956527
def graph(self, name, *args, **kwargs):
        
        return Graph(self, name, *args, **kwargs)
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()
853752
def _extend_module_definitions(self, graph):
        
        for mod_id in self._modules:
            mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module)
            modules = []
            for mod in graph.triples((mod_identity, SBOL.module, None)):
                md = self._get_rdf_identified(graph, mod[2])
                definition_id = self._get_triplet_value(graph, mod[2], SBOL.definition)
                md['definition'] = self._modules[definition_id]
                maps_to = []
                for m in graph.triples((mod[2], SBOL.mapsTo, None)):
                    mt = self._get_rdf_identified(graph, m[2])
                    mt['refinement'] = self._get_triplet_value(graph, m[2], SBOL.refinement)
                    local_id = self._get_triplet_value(graph, m[2], SBOL.local)
                    remote_id = self._get_triplet_value(graph, m[2], SBOL.remote)
                    mt['local'] = self._functional_component_store[local_id]
                    mt['remote'] = self._functional_component_store[remote_id]
                    maps_to.append(MapsTo(**mt))
                modules.append(Module(maps_to=maps_to, **md))
            self._modules[mod_id].modules = modules
1224979
def relations_used(self):
        
        g = self.get_graph()
        types = set()
        for (x,y,d) in g.edges(data=True):
            types.add(d['pred'])
        return list(types)
1177731
def dot(graph, simple=True, debug=False, landscape=False):
    """"""
    import sys

    from rdflib import ConjunctiveGraph
    from rdflib.plugin import register, Parser
    from rdflib.tools.rdf2dot import rdf2dot

    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')

    g = ConjunctiveGraph().parse(
        data=_jsonld(graph, 'expand'),
        format='json-ld',
    )

    g.bind('prov', 'http://www.w3.org/ns/prov#')
    g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#')
    g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#')
    g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#')

    if debug:
        rdf2dot(g, sys.stdout)
        return

    sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ')
    if landscape:
        sys.stdout.write('rankdir="LR" \n')
    if simple:
        _rdf2dot_simple(g, sys.stdout)
        return
    _rdf2dot_reduced(g, sys.stdout)
422294
def equiv_graph(self):
        
        eg = nx.Graph()
        for (u,v,d) in self.get_graph().edges(data=True):
            if d['pred'] == 'equivalentTo':
                eg.add_edge(u,v)
        return eg
593076
def _construct_query_for_uris_and_graphs(uris_and_graphs)
      value_pairs = uris_and_graphs.map do |(uri, graph)|
        u = RDF::URI.new(uri).to_base
        g = graph ? RDF::URI.new(graph).to_base : 'UNDEF'
        "(#{u} #{g})"
      end
      query = "CONSTRUCT { ?uri ?p ?o . #{ self.all_triples_construct("?uri") }} WHERE { GRAPH ?g { ?uri ?p ?o . #{ self.all_triples_where("?uri") } VALUES (?uri ?g) { #{ value_pairs.join(' ') } } } }"
    end
1062136
public static <K, VV, EV> Graph<K, VV, EV> fromDataSet(DataSet<Vertex<K, VV>> vertices,
			DataSet<Edge<K, EV>> edges, ExecutionEnvironment context) {

		return new Graph<>(vertices, edges, context);
	}
252735
protected KeyedGraph<V, E> prepareGraph() throws SQLException {
        LOGGER.info("Loading graph into memory...");
        final long start = System.currentTimeMillis();
        // Initialize the graph.
        KeyedGraph<V, E> graph;
        if (!globalOrientation.equals(GraphFunctionParser.Orientation.UNDIRECTED)) {
            if (weightColumn != null) {
                graph = new DirectedWeightedPseudoG<V, E>(vertexClass, edgeClass);
            } else {
                graph = new DirectedPseudoG<V, E>(vertexClass, edgeClass);
            }
        } else {
            if (weightColumn != null) {
                graph = new WeightedPseudoG<V, E>(vertexClass, edgeClass);
            } else {
                graph = new PseudoG<V, E>(vertexClass, edgeClass);
            }
        }
        final Statement st = connection.createStatement();
        final ResultSet edges = st.executeQuery("SELECT * FROM " +
                TableUtilities.parseInputTable(connection, inputTable));
        // Initialize the indices.
        initIndices(edges);
        try {
            // Add the edges.
            while (edges.next()) {
                loadEdge(graph, edges);
            }
            logTime(LOGGER, start);
            return graph;
        } catch (SQLException e) {
            LOGGER.error("Could not store edges in graph.", e);
            return null;
        } finally {
            edges.close();
            st.close();
        }
    }
72829
def _rdf2dot_reduced(g, stream):
    
    import cgi
    import collections

    import rdflib

    from rdflib.tools.rdf2dot import LABEL_PROPERTIES, NODECOLOR

    types = collections.defaultdict(set)
    fields = collections.defaultdict(set)
    nodes = {}

    def node(x):
        """Return a name of the given node."""
        return nodes.setdefault(x, 'node{0}'.format(len(nodes)))

    def label(x, g):
        """Generate a label for the node."""
        for labelProp in LABEL_PROPERTIES:
            label_ = g.value(x, labelProp)
            if label_:
                return label_

        try:
            return g.namespace_manager.compute_qname(x)[2]
        except Exception:
            return x

    def formatliteral(l, g):
        """Format and escape literal."""
        v = cgi.escape(l)
        if l.datatype:
            return '&quot;%s&quot;^^%s' % (v, qname(l.datatype, g))
        elif l.language:
            return '&quot;%s&quot;@%s' % (v, l.language)
        return '&quot;%s&quot;' % v

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

    def color(p):
        """Choose node color."""
        return 'BLACK'

    for s, p, o in g:
        sn = node(s)
        if p == rdflib.RDFS.label:
            continue

        # inject the type predicate into the node itself
        if p == rdflib.RDF.type:
            types[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://purl.org/dc/terms/isPartOf'):
            fields[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://www.w3.org/ns/prov#wasInformedBy'):
            continue

        if isinstance(o, (rdflib.URIRef, rdflib.BNode)):
            on = node(o)
            opstr = (
                '\t%s -> %s [ color=%s, label=< <font point-size="12" '
                'color="#336633">%s</font> > ] ;\n'
            )
            stream.write(opstr % (sn, on, color(p), qname(p, g)))
        else:
            fields[sn].add((qname(p, g), formatliteral(o, g)))

    for u, n in nodes.items():
        stream.write(u"# %s %s\n" % (u, n))
        f = [
            '<tr><td align="left"><b>%s</b></td><td align="left">'
            '<b>%s</b></td></tr>' % x for x in sorted(types[n])
        ]
        f += [
            '<tr><td align="left">%s</td><td align="left">%s</td></tr>' % x
            for x in sorted(fields[n])
        ]
        opstr = (
            '%s [ shape=none, color=%s label=< <table color="#666666"'
            ' cellborder="0" cellspacing="0" border="1"><tr>'
            '<td colspan="2" bgcolor="grey"><B>%s</B></td></tr><tr>'
            '<td href="%s" bgcolor="#eeeeee" colspan="2">'
            '<font point-size="12" color="#6666ff">%s</font></td>'
            '</tr>%s</table> > ] \n'
        )
        stream.write(opstr % (n, NODECOLOR, label(u, g), u, u, ''.join(f)))

    stream.write('}\n')
775730
def get_subgraphs_by_citation(graph):
    
    rv = defaultdict(graph.fresh_copy)

    for u, v, key, data in graph.edges(keys=True, data=True):
        if CITATION not in data:
            continue
        dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]

        rv[dk].add_edge(u, v, key=key, **data)

    cleanup(graph, rv)

    return dict(rv)
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
477968
def build_groetzch_graph():
    """"""
    # Because the graph is so complicated, we want to
    # build it via adjacency matrix specification
    
    # -- Initialize the matrix to all zeros
    adj = [[0 for _ in range(11)] for _ in range(11)]

    # -- Add individual edge connections
    row_connections = []

    row_connections.append( (1,2,7,10) )
    row_connections.append( (0,3,6,9) )
    row_connections.append( (0,4,6,8) )
    row_connections.append( (1,4,8,10) )
    row_connections.append( (2,3,7,9) )
    row_connections.append( (6,7,8,9,10) )
    row_connections.append( (1,2,5) )
    row_connections.append( (0,4,5) )
    row_connections.append( (2,3,5) )
    row_connections.append( (1,4,5) )
    row_connections.append( (0,3,5) )

    for j, tpl in enumerate(row_connections):
        for i in tpl:
            adj[j][i] = 1
            adj[i][j] = 1
    
    # Debug print the adjacency matrix
    #for row in adj:
    #    print row

    graph, _ = create_graph_from_adjacency_matrix(adj)

    return graph
741505
def dataset_from_rdf(graph, dataset=None, node=None):
    '''
    
    '''
    dataset = dataset or Dataset()

    if node is None:  # Assume first match is the only match
        node = graph.value(predicate=RDF.type, object=DCAT.Dataset)

    d = graph.resource(node)

    dataset.title = rdf_value(d, DCT.title)
    dataset.description = sanitize_html(d.value(DCT.description))
    dataset.frequency = frequency_from_rdf(d.value(DCT.accrualPeriodicity))

    acronym = rdf_value(d, SKOS.altLabel)
    if acronym:
        dataset.acronym = acronym

    tags = [tag.toPython() for tag in d.objects(DCAT.keyword)]
    tags += [theme.toPython() for theme in d.objects(DCAT.theme)]
    dataset.tags = list(set(tags))

    identifier = rdf_value(d, DCT.identifier)
    if identifier:
        dataset.extras['dct:identifier'] = identifier

    if isinstance(d.identifier, URIRef):
        dataset.extras['uri'] = d.identifier.toPython()

    dataset.temporal_coverage = temporal_from_rdf(d.value(DCT.temporal))

    licenses = set()
    for distrib in d.objects(DCAT.distribution | DCAT.distributions):
        resource_from_rdf(distrib, dataset)
        for predicate in DCT.license, DCT.rights:
            value = distrib.value(predicate)
            if isinstance(value, (URIRef, Literal)):
                licenses.add(value.toPython())
            elif isinstance(value, RdfResource):
                licenses.add(value.identifier.toPython())

    default_license = dataset.license or License.default()
    dataset.license = License.guess(*licenses, default=default_license)

    return dataset
272170
def links
      rows.map do |row|
        attributes = Link::ATTRS.dup - [:url]
        Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }])
      end
    end
950231
def get_graph(graph, conn, **kwargs):
    
    sparql = render_without_request("sparqlGraphDataTemplate.rq",
                                    prefix=NSM.prefix(),
                                    graph=graph)
    return conn.query(sparql, **kwargs)