Python networkx.non_edges() Examples
The following are 14
code examples of networkx.non_edges().
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
networkx
, or try the search function
.
Example #1
Source File: test_function.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_non_edges(self): # All possible edges exist graph = nx.complete_graph(5) nedges = list(nx.non_edges(graph)) assert_equal(len(nedges), 0) graph = nx.path_graph(4) expected = [(0, 2), (0, 3), (1, 3)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true( (u, v) in nedges or (v, u) in nedges ) graph = nx.star_graph(4) expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true( (u, v) in nedges or (v, u) in nedges ) # Directed graphs graph = nx.DiGraph() graph.add_edges_from([(0, 2), (2, 0), (2, 1)]) expected = [(0, 1), (1, 0), (1, 2)] nedges = list(nx.non_edges(graph)) for e in expected: assert_true(e in nedges)
Example #2
Source File: test_function.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_non_edges(self): # All possible edges exist graph = nx.complete_graph(5) nedges = list(nx.non_edges(graph)) assert_equal(len(nedges), 0) graph = nx.path_graph(4) expected = [(0, 2), (0, 3), (1, 3)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) graph = nx.star_graph(4) expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) # Directed graphs graph = nx.DiGraph() graph.add_edges_from([(0, 2), (2, 0), (2, 1)]) expected = [(0, 1), (1, 0), (1, 2)] nedges = list(nx.non_edges(graph)) for e in expected: assert_true(e in nedges)
Example #3
Source File: link_prediction.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _apply_prediction(G, func, ebunch=None): """Applies the given function to each edge in the specified iterable of edges. `G` is an instance of :class:`networkx.Graph`. `func` is a function on two inputs, each of which is a node in the graph. The function can return anything, but it should return a value representing a prediction of the likelihood of a "link" joining the two nodes. `ebunch` is an iterable of pairs of nodes. If not specified, all non-edges in the graph `G` will be used. """ if ebunch is None: ebunch = nx.non_edges(G) return ((u, v, func(u, v)) for u, v in ebunch)
Example #4
Source File: test_function.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_non_edges(self): # All possible edges exist graph = nx.complete_graph(5) nedges = list(nx.non_edges(graph)) assert_equal(len(nedges), 0) graph = nx.path_graph(4) expected = [(0, 2), (0, 3), (1, 3)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) graph = nx.star_graph(4) expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) # Directed graphs graph = nx.DiGraph() graph.add_edges_from([(0, 2), (2, 0), (2, 1)]) expected = [(0, 1), (1, 0), (1, 2)] nedges = list(nx.non_edges(graph)) for e in expected: assert_true(e in nedges)
Example #5
Source File: link_prediction.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def _apply_prediction(G, func, ebunch=None): """Applies the given function to each edge in the specified iterable of edges. `G` is an instance of :class:`networkx.Graph`. `func` is a function on two inputs, each of which is a node in the graph. The function can return anything, but it should return a value representing a prediction of the likelihood of a "link" joining the two nodes. `ebunch` is an iterable of pairs of nodes. If not specified, all non-edges in the graph `G` will be used. """ if ebunch is None: ebunch = nx.non_edges(G) return ((u, v, func(u, v)) for u, v in ebunch)
Example #6
Source File: link_prediction.py From EDeN with MIT License | 5 votes |
def make_train_test_set(graph, radius, test_proportion=.3, ratio_neg_to_pos=10): """make_train_test_set.""" pos = [(u, v) for u, v in graph.edges()] neg = [(u, v) for u, v in nx.non_edges(graph)] random.shuffle(pos) random.shuffle(neg) pos_dim = len(pos) neg_dim = len(neg) max_n_neg = min(pos_dim * ratio_neg_to_pos, neg_dim) neg = neg[:max_n_neg] neg_dim = len(neg) tr_pos = pos[:-int(pos_dim * test_proportion)] te_pos = pos[-int(pos_dim * test_proportion):] tr_neg = neg[:-int(neg_dim * test_proportion)] te_neg = neg[-int(neg_dim * test_proportion):] # remove edges tr_graph = graph.copy() tr_graph.remove_edges_from(te_pos) tr_pos_graphs = list(_make_subgraph_set(tr_graph, radius, tr_pos)) tr_neg_graphs = list(_make_subgraph_set(tr_graph, radius, tr_neg)) te_pos_graphs = list(_make_subgraph_set(tr_graph, radius, te_pos)) te_neg_graphs = list(_make_subgraph_set(tr_graph, radius, te_neg)) tr_graphs = tr_pos_graphs + tr_neg_graphs te_graphs = te_pos_graphs + te_neg_graphs tr_targets = [1] * len(tr_pos_graphs) + [0] * len(tr_neg_graphs) te_targets = [1] * len(te_pos_graphs) + [0] * len(te_neg_graphs) tr_graphs, tr_targets = paired_shuffle(tr_graphs, tr_targets) te_graphs, te_targets = paired_shuffle(te_graphs, te_targets) return (tr_graphs, np.array(tr_targets)), (te_graphs, np.array(te_targets))
Example #7
Source File: link_prediction_utils.py From EDeN with MIT License | 5 votes |
def show_graph(g, vertex_color='typeof', size=15, vertex_label=None): """show_graph.""" degrees = [len(g.neighbors(u)) for u in g.nodes()] print(('num nodes=%d' % len(g))) print(('num edges=%d' % len(g.edges()))) print(('num non edges=%d' % len(list(nx.non_edges(g))))) print(('max degree=%d' % max(degrees))) print(('median degree=%d' % np.percentile(degrees, 50))) draw_graph(g, size=size, vertex_color=vertex_color, vertex_label=vertex_label, vertex_size=200, edge_label=None) # display degree distribution size = int((max(degrees) - min(degrees)) / 1.5) plt.figure(figsize=(size, 3)) plt.title('Degree distribution') _bins = np.arange(min(degrees), max(degrees) + 2) - .5 n, bins, patches = plt.hist(degrees, _bins, alpha=0.3, facecolor='navy', histtype='bar', rwidth=0.8, edgecolor='k') labels = np.array([str(int(i)) for i in n]) for xi, yi, label in zip(bins, n, labels): plt.text(xi + 0.5, yi, label, ha='center', va='bottom') plt.xticks(bins + 0.5) plt.xlim((min(degrees) - 1, max(degrees) + 1)) plt.ylim((0, max(n) * 1.1)) plt.xlabel('Node degree') plt.ylabel('Counts') plt.grid(linestyle=":") plt.show()
Example #8
Source File: split_train_test.py From EvalNE with MIT License | 5 votes |
def _getall_false_edges(G, fe_train_frac): print("Generating all non-edges and splitting them in train and test...") train_E_false = list() test_E_false = list() for e in nx.non_edges(G): r = random.uniform(0, 1) if r <= fe_train_frac: train_E_false.append(e) else: test_E_false.append(e) return train_E_false, test_E_false
Example #9
Source File: quality.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def inter_community_non_edges(G, partition): """Returns the number of inter-community non-edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition. Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # return inter_community_edges(nx.complement(G), partition)
Example #10
Source File: quality.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def inter_community_non_edges(G, partition): """Returns the number of inter-community non-edges according to the given partition of the nodes of `G`. `G` must be a NetworkX graph. `partition` must be a partition of the nodes of `G`. A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition. Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`. """ # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # return inter_community_edges(nx.complement(G), partition)
Example #11
Source File: link_prediction.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def resource_allocation_index(G, ebunch=None): r"""Compute the resource allocation index of all node pairs in ebunch. Resource allocation index of `u` and `v` is defined as .. math:: \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|} where :math:`\Gamma(u)` denotes the set of neighbors of `u`. Parameters ---------- G : graph A NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Resource allocation index will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all non-existent edges in the graph will be used. Default value: None. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their resource allocation index. Examples -------- >>> import networkx as nx >>> G = nx.complete_graph(5) >>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... '(%d, %d) -> %.8f' % (u, v, p) ... '(0, 1) -> 0.75000000' '(2, 3) -> 0.75000000' References ---------- .. [1] T. Zhou, L. Lu, Y.-C. Zhang. Predicting missing links via local information. Eur. Phys. J. B 71 (2009) 623. http://arxiv.org/pdf/0901.0553.pdf """ if ebunch is None: ebunch = nx.non_edges(G) def predict(u, v): return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v)) return ((u, v, predict(u, v)) for u, v in ebunch)
Example #12
Source File: link_prediction.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def jaccard_coefficient(G, ebunch=None): r"""Compute the Jaccard coefficient of all node pairs in ebunch. Jaccard coefficient of nodes `u` and `v` is defined as .. math:: \frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|} where :math:`\Gamma(u)` denotes the set of neighbors of `u`. Parameters ---------- G : graph A NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Jaccard coefficient will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all non-existent edges in the graph will be used. Default value: None. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their Jaccard coefficient. Examples -------- >>> import networkx as nx >>> G = nx.complete_graph(5) >>> preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... '(%d, %d) -> %.8f' % (u, v, p) ... '(0, 1) -> 0.60000000' '(2, 3) -> 0.60000000' References ---------- .. [1] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004). http://www.cs.cornell.edu/home/kleinber/link-pred.pdf """ if ebunch is None: ebunch = nx.non_edges(G) def predict(u, v): cnbors = list(nx.common_neighbors(G, u, v)) union_size = len(set(G[u]) | set(G[v])) if union_size == 0: return 0 else: return len(cnbors) / union_size return ((u, v, predict(u, v)) for u, v in ebunch)
Example #13
Source File: link_prediction.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def adamic_adar_index(G, ebunch=None): r"""Compute the Adamic-Adar index of all node pairs in ebunch. Adamic-Adar index of `u` and `v` is defined as .. math:: \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|} where :math:`\Gamma(u)` denotes the set of neighbors of `u`. Parameters ---------- G : graph NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Adamic-Adar index will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all non-existent edges in the graph will be used. Default value: None. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their Adamic-Adar index. Examples -------- >>> import networkx as nx >>> G = nx.complete_graph(5) >>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... '(%d, %d) -> %.8f' % (u, v, p) ... '(0, 1) -> 2.16404256' '(2, 3) -> 2.16404256' References ---------- .. [1] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004). http://www.cs.cornell.edu/home/kleinber/link-pred.pdf """ if ebunch is None: ebunch = nx.non_edges(G) def predict(u, v): return sum(1 / math.log(G.degree(w)) for w in nx.common_neighbors(G, u, v)) return ((u, v, predict(u, v)) for u, v in ebunch)
Example #14
Source File: link_prediction.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def preferential_attachment(G, ebunch=None): r"""Compute the preferential attachment score of all node pairs in ebunch. Preferential attachment score of `u` and `v` is defined as .. math:: |\Gamma(u)| |\Gamma(v)| where :math:`\Gamma(u)` denotes the set of neighbors of `u`. Parameters ---------- G : graph NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Preferential attachment score will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all non-existent edges in the graph will be used. Default value: None. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their preferential attachment score. Examples -------- >>> import networkx as nx >>> G = nx.complete_graph(5) >>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... '(%d, %d) -> %d' % (u, v, p) ... '(0, 1) -> 16' '(2, 3) -> 16' References ---------- .. [1] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004). http://www.cs.cornell.edu/home/kleinber/link-pred.pdf """ if ebunch is None: ebunch = nx.non_edges(G) return ((u, v, G.degree(u) * G.degree(v)) for u, v in ebunch)