def add_node_attrs(graph, node, attrs): """Add new attributes to a node. Parameters ---------- graph : networkx.(Di)Graph node : hashable Id of a node to add attributes to. attrs : dict Attributes to add. Raises ------ GraphError If a node with the specified id does not exist. """ if node not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % str(node)) normalize_attrs(attrs) node_attrs = graph.node[node] if node_attrs is None: graph.node[node] = copy.deepcopy(attrs) else: for key in attrs: if key in node_attrs: # node_attrs[key] = hyb_union(node_attrs[key], attrs_dict[key]) node_attrs[key] = node_attrs[key].union(attrs[key]) else: node_attrs[key] = attrs[key]
def test_add_edge_attrs(self): g = self.graph.to_undirected() new_attrs = {"b": FiniteSet({1})} add_edge_attrs(g, '1', '2', new_attrs) normalize_attrs(new_attrs) assert(valid_attributes(new_attrs, g.edge['1']['2'])) assert(valid_attributes(new_attrs, g.edge['2']['1']))
def update_edge_attrs(graph, s, t, attrs): """Update attributes of an edge. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict New attributes to assign to the edge Raises ------ GraphError If an edge between `s` and `t` does not exist. """ if not graph.has_edge(s, t): raise GraphError("Edge '%s->%s' does not exist!" % (str(s), str(t))) elif attrs is None: warnings.warn( "You want to update '%s->%s' attrs with an empty attrs_dict" % (str(s), str(t)), GraphAttrsWarning) else: new_attrs = deepcopy(attrs) normalize_attrs(new_attrs) graph.edge[s][t] = new_attrs if not graph.is_directed(): graph.edge[t][s] = new_attrs
def add_edge_attrs(graph, s, t, attrs): """Add attributes of an edge in a graph. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict Dictionary with attributes to remove. Raises ------ GraphError If an edge between `s` and `t` does not exist. """ new_attrs = deepcopy(attrs) if not graph.has_edge(s, t): raise (GraphError("Edge '%s->%s' does not exist" % (str(s), str(t)))) elif new_attrs is None: pass else: normalize_attrs(new_attrs) edge_attrs = get_edge(graph, s, t) for key, value in new_attrs.items(): if key in edge_attrs: edge_attrs[key] = edge_attrs[key].union(value) else: edge_attrs[key] = value set_edge(graph, s, t, edge_attrs)
def remove_edge_attrs(graph, s, t, attrs): """Remove attrs of an edge specified by attrs. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict Dictionary with attributes to remove. Raises ------ GraphError If an edge between `s` and `t` does not exist. """ if not graph.has_edge(s, t): raise GraphError("Edge %s-%s does not exist" % (str(s), str(t))) else: normalize_attrs(attrs) old_attrs = get_edge(graph, s, t) for key, value in attrs.items(): if key in old_attrs: new_set = old_attrs[key].difference(value) if new_set: old_attrs[key] = new_set else: del old_attrs[key] set_edge(graph, s, t, old_attrs)
def test_add_edge_attrs(self): g = self.graph.to_undirected() new_attrs = {"b": FiniteSet({1})} add_edge_attrs(g, '1', '2', new_attrs) normalize_attrs(new_attrs) assert (valid_attributes(new_attrs, g.edge['1']['2'])) assert (valid_attributes(new_attrs, g.edge['2']['1']))
def set_edge(graph, s, t, attrs): """Set edge attrs. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dictionary Dictionary with attributes to set. Raises ------ GraphError If an edge between `s` and `t` does not exist. """ new_attrs = deepcopy(attrs) if not graph.has_edge(s, t): raise GraphError( "Edge %s->%s does not exist" % (str(s), str(t))) normalize_attrs(new_attrs) graph.edge[s][t] = new_attrs if not graph.is_directed(): graph.edge[t][s] = new_attrs
def add_node(graph, node_id, attrs=None): """Add a node to a graph. Parameters ---------- graph : networkx.(Di)Graph node_id : hashable Prefix that is prepended to the new unique name. attrs : dict, optional Node attributes. Raises ------- regraph.exceptions.GraphError Raises an error if node already exists in the graph. """ new_attrs = deepcopy(attrs) if new_attrs is None: new_attrs = dict() if node_id not in graph.nodes(): graph.add_node(node_id) normalize_attrs(new_attrs) graph.node[node_id] = new_attrs else: raise GraphError("Node '%s' already exists!" % node_id)
def update_node_attrs(self, node_id, attrs, normalize=True): """Update attributes of a node. Parameters ---------- node_id : hashable, node to update. attrs : dict New attributes to assign to the node """ new_attrs = safe_deepcopy_dict(attrs) if node_id not in self.nodes(): raise GraphError("Node '{}' does not exist!".format(node_id)) elif new_attrs is None: warnings.warn( "You want to update '{}' attrs with an empty attrs_dict!". format(node_id), GraphAttrsWarning) else: if normalize is True: normalize_attrs(new_attrs) attrs_to_remove = set() for k in self._graph.nodes[node_id].keys(): if k not in new_attrs.keys(): attrs_to_remove.add(k) self._graph.add_node(node_id, **new_attrs) for k in attrs_to_remove: del self._graph.nodes[node_id][k]
def add_edge(self, s, t, attrs=None, **attr): """Add an edge to a graph. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict Edge attributes. """ if attrs is None: attrs = attr else: try: attrs.update(attr) except AttributeError: raise ReGraphError( "The attr_dict argument must be a dictionary.") new_attrs = safe_deepcopy_dict(attrs) if s not in self.nodes(): raise GraphError("Node '{}' does not exist!".format(s)) if t not in self.nodes(): raise GraphError("Node '{}' does not exist!".format(t)) normalize_attrs(new_attrs) if (s, t) in self.edges(): raise GraphError("Edge '{}'->'{}' already exists!".format(s, t)) self._graph.add_edge(s, t, **new_attrs)
def set_edge_attrs(self, source, target, attrs, update=False): """Set edge attributes. source : Id of the source node of the edge target : Id of the target node of the edge attrs : dict Dictionary containing attrs update : optional If is set to False, updates only the attributes whose keys are in 'attrs', all the attributes not mentioned in 'attrs' stay the same. Otherwise, overwrites all the attributes (default: False) """ normalize_attrs(attrs) query = ( cypher.match_edge( "s", "t", source, target, "rel", self._node_label, self._node_label, self._edge_label) + cypher.set_attributes("rel", attrs, update) ) result = self.execute(query) return result
def update_edge_attrs(self, s, t, attrs, normalize=True): """Update attributes of a node. Parameters ---------- s : hashable, source node of the edge to update. t : hashable, target node of the edge to update. attrs : dict New attributes to assign to the node """ if not self._graph.has_edge(s, t): raise GraphError("Edge '{}->{}' does not exist!".format(s, t)) if attrs is None: warnings.warn( "You want to update '{}->{}' attrs with an empty attrs_dict". format(s, t), GraphAttrsWarning) if normalize is True: normalize_attrs(attrs) attrs_to_remove = set() for k in self._graph.adj[s][t].keys(): if k not in attrs.keys(): attrs_to_remove.add(k) self._graph.add_edge(s, t, **attrs) for k in attrs_to_remove: del self._graph.adj[s][t][k]
def add_node_attrs(self, node, attrs): """Add attributes to the node.""" normalize_attrs(attrs) query = (generic.match_node("n", node, self._node_label) + rewriting.add_attributes("n", attrs)) result = self.execute(query) return result
def update_node_attrs(graph, node_id, attrs): """Update attributes of a node. Parameters ---------- graph : networkx.(Di)Graph node_id : hashable, node to update. attrs : dict New attributes to assign to the node Raises ------ GraphError If a node with the specified id does not exist. """ new_attrs = deepcopy(attrs) if node_id not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % str(node_id)) elif new_attrs is None: warnings.warn( "You want to update '%s' attrs with an empty attrs_dict!" % node_id, GraphAttrsWarning ) else: normalize_attrs(new_attrs) graph.node[node_id] = new_attrs
def update_node_attrs(graph, node_id, attrs): """Update attributes of a node. Parameters ---------- graph : networkx.(Di)Graph node_id : hashable, node to update. attrs : dict New attributes to assign to the node Raises ------ GraphError If a node with the specified id does not exist. """ new_attrs = deepcopy(attrs) if node_id not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % str(node_id)) elif new_attrs is None: warnings.warn( "You want to update '%s' attrs with an empty attrs_dict!" % node_id, GraphAttrsWarning) else: normalize_attrs(new_attrs) graph.node[node_id] = new_attrs
def test_add_node(self): attrs = {"a": {1}} add_node(self.graph, "a", attrs) assert("a" in self.graph.nodes()) normalize_attrs(attrs) assert(self.graph.node["a"] == attrs) assert(id(attrs) != id(self.graph.node["a"]))
def add_edge_attrs(graph, s, t, attrs): """Add attributes of an edge in a graph. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict Dictionary with attributes to remove. Raises ------ GraphError If an edge between `s` and `t` does not exist. """ new_attrs = deepcopy(attrs) if not graph.has_edge(s, t): raise( GraphError("Edge '%s->%s' does not exist" % (str(s), str(t))) ) elif new_attrs is None: pass else: normalize_attrs(new_attrs) edge_attrs = get_edge(graph, s, t) for key, value in new_attrs.items(): if key in edge_attrs: edge_attrs[key] = edge_attrs[key].union(value) else: edge_attrs[key] = value set_edge(graph, s, t, edge_attrs)
def remove_node_attrs(graph, node_id, attrs): """Remove attrs of a node specified by attrs_dict. Parameters ---------- graph : networkx.(Di)Graph node_id : hashable Node whose attributes to remove. attrs : dict Dictionary with attributes to remove. Raises ------ GraphError If a node with the specified id does not exist. """ if node_id not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % str(node_id)) elif attrs is None: warnings.warn( "You want to remove attrs from '%s' with an empty attrs_dict!" % node_id, GraphAttrsWarning) elif graph.node[node_id] is None: warnings.warn("Node '%s' does not have any attribute!" % node_id, GraphAttrsWarning) else: normalize_attrs(attrs) old_attrs = graph.node[node_id] for key, value in attrs.items(): if key in old_attrs: new_set = old_attrs[key].difference(value) if not new_set: del old_attrs[key] else: old_attrs[key] = new_set
def test_add_node(self): attrs = {"a": {1}} add_node(self.graph, "a", attrs) assert ("a" in self.graph.nodes()) normalize_attrs(attrs) assert (self.graph.node["a"] == attrs) assert (id(attrs) != id(self.graph.node["a"]))
def update_edge_attrs(graph, s, t, attrs): """Update attributes of an edge. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict New attributes to assign to the edge Raises ------ GraphError If an edge between `s` and `t` does not exist. """ if not graph.has_edge(s, t): raise GraphError("Edge '%s->%s' does not exist!" % (str(s), str(t))) elif attrs is None: warnings.warn( "You want to update '%s->%s' attrs with an empty attrs_dict" % (str(s), str(t)), GraphAttrsWarning ) else: new_attrs = deepcopy(attrs) normalize_attrs(new_attrs) graph.edge[s][t] = new_attrs if not graph.is_directed(): graph.edge[t][s] = new_attrs
def remove_node_attrs(self, node, attrs): """Remove attributes from the node.""" normalize_attrs(attrs) query = (generic.match_node("n", node, self._node_label) + rewriting.remove_attributes("n", attrs)) result = self.execute(query) return result
def relabel_node(self, node_id, new_id): """Change the 'id' property of the node.""" attrs = {"id": new_id} normalize_attrs(attrs) query = (generic.match_node("n", node_id) + generic.set_node_attrs("n", attrs, update=False)) result = self.execute(query) return result
def update_attrs(self, attrs): """Update attribures.""" new_attrs = copy.deepcopy(attrs) if new_attrs is None: pass else: normalize_attrs(new_attrs) self.attrs = new_attrs
def remove_edge_attrs(self, source, target, attrs): """Remove attributes from the edge.""" normalize_attrs(attrs) query = (generic.match_edge("s", "t", source, target, "rel", self._node_label, self._edge_label, self._edge_label) + rewriting.remove_attributes("rel", attrs)) result = self.execute(query) return result
def test_add_edge_attrs(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.add_edge_attrs(4, 1, {'amazing': True}) assert_graph_eq(rule.p, self.p) t = {'amazing': {True}} normalize_attrs(t) assert(rule.rhs.edge['s']['x'] == t) return
def test_update_node_attrs(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.update_node_attrs(4, {'b': 2}) assert(rule.p.node['d'] is None) test_dict = {'b': {2}} normalize_attrs(test_dict) assert(rule.rhs.node['s'] == test_dict) return
def add_node_attrs(self, node, attrs): """Add attributes to the node.""" normalize_attrs(attrs) query = ( cypher.match_node("n", node, self._node_label) + cypher.add_attributes("n", attrs) ) result = self.execute(query) return result
def __init__(self, graph, attrs=None): """Initialize graph node with graph object and attrs.""" self.graph = graph if attrs: if attrs is not None: normalize_attrs(attrs) self.attrs = attrs else: self.attrs = dict() return
def relabel_node(self, node_id, new_id): """Change the 'id' property of the node.""" attrs = {"id": new_id} normalize_attrs(attrs) query = ( cypher.match_node("n", node_id) + cypher.set_node_attrs("n", attrs, update=False) ) result = self.execute(query) return result
def remove_node_attrs(self, node, attrs): """Remove attributes from the node.""" normalize_attrs(attrs) query = ( cypher.match_node( "n", node, self._node_label) + cypher.remove_attributes("n", attrs) ) result = self.execute(query) return result
def add_edge(graph, s, t, attrs=None, **attr): """Add an edge to a graph. Parameters ---------- graph : networkx.(Di)Graph s : hashable, source node id. t : hashable, target node id. attrs : dict Edge attributes. Raises ------ ReGraphError If `attrs` is not a dictionary GraphError If either one of the nodes does not exist in the graph or an edge between `s` and `t` already exists. """ # Set up attribute dict (from Networkx to preserve the signature). if attrs is None: attrs = attr else: try: attrs.update(attr) except AttributeError: raise ReGraphError( "The attr_dict argument must be a dictionary." ) new_attrs = deepcopy(attrs) if s not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % s) if t not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % t) normalize_attrs(new_attrs) if graph.is_directed(): if (s, t) in graph.edges(): raise GraphError( "Edge '%s'->'%s' already exists!" % (s, t) ) graph.add_edge(s, t, new_attrs) else: if (s, t) in graph.edges() or (t, s) in graph.edges(): raise GraphError( "Edge '%s'->'%s' already exists!" % (s, t) ) graph.add_edge(s, t) graph.edge[s][t] = new_attrs graph.edge[t][s] = new_attrs
def test_add_node(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.add_node('g', {'a': 1}) assert_graph_eq(rule.p, self.p) assert_graph_eq(rule.lhs, self.pattern) assert('g' in rule.rhs) t = {'a': set([1])} normalize_attrs(t) assert(rule.rhs.node['g'] == t) return
def add_edge_attrs(self, source, target, attrs): """Add attributes to the edge.""" normalize_attrs(attrs) query = ( cypher.match_edge( "s", "t", source, target, "rel", self._node_label, self._node_label, self._edge_label) + cypher.add_attributes("rel", attrs) ) result = self.execute(query) return result
def remove_edge_attrs(self, source, target, attrs): """Remove attributes from the edge.""" normalize_attrs(attrs) query = ( cypher.match_edge( "s", "t", source, target, "rel", self._node_label, self._edge_label, self._edge_label) + cypher.remove_attributes("rel", attrs) ) result = self.execute(query) return result
def test_remove_node_attrs(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.add_node_attrs(4, {'a': 2}) rule.remove_node_attrs(4, {'a': 1}) t1 = {'a': set()} t2 = {'a': set([2])} normalize_attrs(t1) normalize_attrs(t2) assert(rule.p.node['d'] == t1) assert(rule.rhs.node['s'] == t2) return
def to_d3_json(self, attrs=True, node_attrs_to_attach=None, edge_attrs_to_attach=None, nodes=None): """Create a JSON representation of a graph.""" j_data = {"links": [], "nodes": []} if nodes is None: nodes = self.nodes() # dump nodes for node in nodes: node_data = {} node_data["id"] = node if attrs: node_attrs = self.get_node(node) normalize_attrs(node_attrs) attrs_json = dict() for key, value in node_attrs.items(): attrs_json[key] = value.to_json() node_data["attrs"] = attrs_json else: node_attrs = self.get_node(node) if node_attrs_to_attach is not None: for key in node_attrs_to_attach: if key in node_attrs.keys(): node_data[key] = list(node_attrs[key]) j_data["nodes"].append(node_data) # dump edges for s, t in self.edges(): if s in nodes and t in nodes: edge_data = {} edge_data["source"] = s edge_data["target"] = t if attrs: edge_attrs = self.get_edge(s, t) normalize_attrs(edge_attrs) attrs_json = dict() for key, value in edge_attrs.items(): attrs_json[key] = value.to_json() edge_data["attrs"] = attrs_json else: if edge_attrs_to_attach is not None: for key in edge_attrs_to_attach: edge_attrs = self.get_edge(s, t) if key in edge_attrs.keys(): edge_data[key] = list(edge_attrs[key]) j_data["links"].append(edge_data) return j_data
def add_nodes_from(self, nodes, ignore_naming=False, profiling=False, holistic=False): """Add nodes to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if holistic: carry_variables = set() for n in nodes: if type(n) != str: try: n_id, attrs = n normalize_attrs(attrs) q, carry_variables =\ rewriting.add_node( n_id, n_id, 'new_id_' + n_id, node_label=self._node_label, attrs=attrs, ignore_naming=ignore_naming) except ValueError as e: q, carry_variables =\ rewriting.add_node( n, n, 'new_id_' + n, node_label=self._node_label, ignore_naming=ignore_naming) else: q, carry_variables =\ rewriting.add_node( n, n, 'new_id_' + n, node_label=self._node_label, ignore_naming=ignore_naming) query += q + generic.with_vars(carry_variables) if len(carry_variables) > 0: query += generic.return_vars(carry_variables) result = self.execute(query) return result else: for n in nodes: if type(n) != str: try: n_id, attrs = n self.add_node(n_id, attrs) except ValueError: self.add_node(n) else: self.add_node(n)
def add_edges_from(self, edges, profiling=False, holistic=False): """Add edges to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if holistic: nodes_to_match = set() edge_creation_queries = [] for e in edges: try: u, v, attrs = e nodes_to_match.add(u) nodes_to_match.add(v) normalize_attrs(attrs) edge_creation_queries.append( cypher.add_edge( edge_var=u + "_" + v, source_var=u, target_var=v, edge_label=self._edge_label, attrs=attrs)) except ValueError: u, v = e nodes_to_match.add(u) nodes_to_match.add(v) edge_creation_queries.append( cypher.add_edge( edge_var=u + "_" + v, source_var=u, target_var=v, edge_label=self._edge_label)) if len(edges) > 0: query += cypher.match_nodes( {n: n for n in nodes_to_match}, node_label=self._node_label) for q in edge_creation_queries: query += q result = self.execute(query) return result else: for e in edges: try: u, v, attrs = e self.add_edge(u, v, attrs) except ValueError: u, v = e self.add_edge(u, v)
def test_add_edge(self): try: add_edge(self.graph, '1', '2') raise ValueError("") except: pass s = '1' t = '5' attrs = {"a": {1}} add_edge(self.graph, s, t, attrs) normalize_attrs(attrs) assert((s, t) in self.graph.edges()) assert(self.graph.edge[s][t] == attrs) assert(id(self.graph.edge[s][t]) != id(attrs))
def test_add_edge(self): try: add_edge(self.graph, '1', '2') raise ValueError("") except: pass s = '1' t = '5' attrs = {"a": {1}} add_edge(self.graph, s, t, attrs) normalize_attrs(attrs) assert ((s, t) in self.graph.edges()) assert (self.graph.edge[s][t] == attrs) assert (id(self.graph.edge[s][t]) != id(attrs))
def add_attrs(self, attrs): """Add attrs to the container.""" if attrs is not None: normalize_attrs(attrs) else: attrs = dict() node_attrs = self.attrs if node_attrs is None: self.attrs = attrs else: for key in attrs: if key in node_attrs: node_attrs[key] = node_attrs[key].union(attrs[key]) else: node_attrs[key] = attrs[key] return
def test_remove_edge_attrs(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.remove_edge_attrs(2, 3, {'a': set()}) t1 = {'a': {1}} normalize_attrs(t1) assert(rule.p.edge['b']['c'] == t1) assert(rule.rhs.edge['y']['z'] == t1) rule.remove_edge_attrs(2, 3, {'a': {1}}) t2 = {'a': set()} normalize_attrs(t2) print(t2) print(rule.p.edge['b']['c']) assert(rule.p.edge['b']['c'] == t2) assert(rule.rhs.edge['y']['z'] == t2) return
def add_edges_from(self, edges, profiling=False, holistic=False): """Add edges to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if holistic: nodes_to_match = set() edge_creation_queries = [] for e in edges: try: u, v, attrs = e nodes_to_match.add(u) nodes_to_match.add(v) normalize_attrs(attrs) edge_creation_queries.append( rewriting.add_edge(edge_var=u + "_" + v, source_var=u, target_var=v, edge_label=self._edge_label, attrs=attrs)) except ValueError: u, v = e nodes_to_match.add(u) nodes_to_match.add(v) edge_creation_queries.append( rewriting.add_edge(edge_var=u + "_" + v, source_var=u, target_var=v, edge_label=self._edge_label)) if len(edges) > 0: query += rewriting.match_nodes({n: n for n in nodes_to_match}, node_label=self._node_label) for q in edge_creation_queries: query += q result = self.execute(query) return result else: for e in edges: try: u, v, attrs = e self.add_edge(u, v, attrs) except ValueError: u, v = e self.add_edge(u, v)
def add_nodes_from(self, nodes, ignore_naming=False, profiling=False, holistic=False): """Add nodes to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if holistic: carry_variables = set() for n in nodes: if type(n) != str: try: n_id, attrs = n normalize_attrs( attrs) q, carry_variables =\ cypher.add_node( n_id, n_id, 'new_id_' + n_id, node_label=self._node_label, attrs=attrs, ignore_naming=ignore_naming) except ValueError as e: q, carry_variables =\ cypher.add_node( n, n, 'new_id_' + n, node_label=self._node_label, ignore_naming=ignore_naming) else: q, carry_variables =\ cypher.add_node( n, n, 'new_id_' + n, node_label=self._node_label, ignore_naming=ignore_naming) query += q + cypher.with_vars(carry_variables) if len(carry_variables) > 0: query += cypher.return_vars(carry_variables) result = self.execute(query) return result else: for n in nodes: try: n_id, attrs = n self.add_node(n_id, attrs) except ValueError: self.add_node(n)
def add_edge(self, source, target, attrs=None, profiling=False): """Add an edge to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if attrs is None: attrs = dict() normalize_attrs(attrs) query += cypher.match_nodes( {"s": source, "t": target}, node_label=self._node_label) query += cypher.add_edge( edge_var='new_edge', source_var="s", target_var="t", edge_label=self._edge_label, attrs=attrs) result = self.execute(query) return result
def set_node_attrs(self, node, attrs, update=False): """Set node attributes. node : Id of the node whose attrs should be set attrs : dict Dictionary containing attrs update : optional If is set to False, updates only the attributes whose keys are in 'attrs', all the attributes not mentioned in 'attrs' stay the same. Otherwise, overwrites all the attributes (default: False) """ normalize_attrs(attrs) query = ( cypher.match_node("n", node, self._node_label) + cypher.set_attributes("n", attrs, update) ) result = self.execute(query) return result
def remove_node_attrs(graph, node_id, attrs): """Remove attrs of a node specified by attrs_dict. Parameters ---------- graph : networkx.(Di)Graph node_id : hashable Node whose attributes to remove. attrs : dict Dictionary with attributes to remove. Raises ------ GraphError If a node with the specified id does not exist. """ if node_id not in graph.nodes(): raise GraphError("Node '%s' does not exist!" % str(node_id)) elif attrs is None: warnings.warn( "You want to remove attrs from '%s' with an empty attrs_dict!" % node_id, GraphAttrsWarning ) elif graph.node[node_id] is None: warnings.warn( "Node '%s' does not have any attribute!" % node_id, GraphAttrsWarning ) else: normalize_attrs(attrs) old_attrs = graph.node[node_id] for key, value in attrs.items(): if key in old_attrs: new_set = old_attrs[key].difference(value) if not new_set: del old_attrs[key] else: old_attrs[key] = new_set
def add_node(self, node, attrs=None, ignore_naming=False, profiling=False): """Add a node to the graph db.""" if profiling: query = "PROFILE\n" else: query = "" if attrs is None: attrs = dict() normalize_attrs(attrs) query +=\ cypher.add_node( "n", node, 'new_id', node_label=self._node_label, attrs=attrs, literal_id=True, ignore_naming=ignore_naming)[0] +\ cypher.return_vars(['new_id']) result = self.execute(query) new_id = result.single()['new_id'] return new_id
def test_add_node_attrs(self): rule = Rule(self.p, self.pattern, self.rhs, self.p_lhs, self.p_rhs) rule.add_node_attrs(1, {'a': 1}) t1 = {'a': {1}} t2 = {'a': {1, 2}} t3 = {'a': {1, 2}, 'b': {1}} normalize_attrs(t1) normalize_attrs(t2) normalize_attrs(t3) assert(rule.rhs.node['x'] == t1) rule.add_node_attrs(4, {'a': 1}) assert(rule.rhs.node['s'] == t1) rule.add_node_attrs(4, {'a': 2}) assert(rule.rhs.node['s'] == t2) rule.add_node_attrs(4, {'b': 1}) assert(rule.rhs.node['s'] == t3) return
def update_edge_attrs(self, n1, n2, attrs): """Update the attributes of an edge with a new set `attrs`.""" if n1 not in self.lhs.nodes(): raise RuleError( "Node '%s' does not exist in the left hand side of the rule" % n1 ) if n2 not in self.lhs.nodes(): raise RuleError( "Node '%s' does not exist in the left hand side of the rule" % n2 ) normalize_attrs(attrs) if self.lhs.is_directed(): if (n1, n2) not in self.lhs.edges(): raise RuleError( "Edge '%s->%s' does not exist in the left hand " "side of the rule" % (n1, n2) ) p_keys_1 = keys_by_value(self.p_lhs, n1) p_keys_2 = keys_by_value(self.p_lhs, n2) if len(p_keys_1) == 0: raise RuleError( "Node '%s' is being removed by the rule, cannot update " "attributes from the incident edge" % n2 ) if len(p_keys_2) == 0: raise RuleError( "Node '%s' is being removed by the rule, cannot update " "attributes from the incident edge" % n1 ) for k1 in p_keys_1: for k2 in p_keys_2: self.p.edge[k1][k2] = None primitives.update_edge_attrs( self.rhs, self.p_rhs[k1], self.p_rhs[k2], attrs ) else: if (n1, n2) not in self.lhs.edges() and\ (n2, n1) not in self.lhs.edges(): raise RuleError( "Edge '%s->%s' does not exist in the " "left hand side of the rule" % (n1, n2) ) p_keys_1 = keys_by_value(self.p_lhs, n1) p_keys_2 = keys_by_value(self.p_lhs, n2) if len(p_keys_1) == 0: raise RuleError( "Node '%s' is being removed by the rule, cannot update " "attributes from the incident edge" % n1 ) if len(p_keys_2) == 0: raise RuleError( "Node '%s' is being removed by the rule, cannot update " "attributes from the incident edge" % n2 ) for k1 in p_keys_1: for k2 in p_keys_2: self.p.edge[k1][k2] = None primitives.update_edge_attrs( self.rhs, self.p_rhs[k1], self.p_rhs[k2], attrs ) return