Python networkx.neighbors() Examples

The following are 30 code examples of networkx.neighbors(). 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: __init__.py    From EDeN with MIT License 6 votes vote down vote up
def compute_matching_neighborhoods_fraction(GA, GB, pairings):
    count = 0
    matches = dict([(i, j) for i, j in enumerate(pairings)])
    matching_edges = defaultdict(list)
    for i, j in GA.edges():
        ii = matches[i]
        jj = matches[j]
        if (ii, jj) in GB.edges():
            matching_edges[i].append(j)
            matching_edges[j].append(i)
    for u in GA.nodes():
        if matching_edges.get(u, False):
            neighbors = nx.neighbors(GA, u)
            matches_neighborhood = True
            for v in neighbors:
                if v not in matching_edges[u]:
                    matches_neighborhood = False
                    break
            if matches_neighborhood:
                count += 1
    return float(count) / len(GA.nodes()) 
Example #2
Source File: label_propagation.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def _make_a_pick(self, neighbors):
        """
        Choosing a neighbor from a propagation source node.

        Arg types:
            * **neigbours** *(list)* - Neighbouring nodes.
        """
        scores = {}
        for neighbor in neighbors:
            neighbor_label = self._labels[neighbor]
            if neighbor_label in scores.keys():
                scores[neighbor_label] = scores[neighbor_label] + 1
            else:
                scores[neighbor_label] = 1
        top = [key for key, val in scores.items() if val == max(scores.values())]
        return random.sample(top, 1)[0] 
Example #3
Source File: __init__.py    From EDeN with MIT License 6 votes vote down vote up
def annotate_with_bfs(orig_graph, start, max_depth=20):
    graph = orig_graph.copy()
    for u in graph.nodes():
        graph.node[u]['vec'].append(1)

    visited, queue, dist = set(), [start], dict()
    dist[start] = 0
    while queue:
        vertex = queue.pop(0)
        if dist[vertex] <= max_depth:
            if vertex not in visited:
                visited.add(vertex)
                val = max_depth - dist[vertex]
                graph.node[vertex]['vec'][-1] = val
                next_nodes = [u for u in graph.neighbors(vertex)
                              if u not in visited]
                next_dist = dist[vertex] + 1
                for u in next_nodes:
                    dist[u] = next_dist
                queue.extend(next_nodes)
    return graph 
Example #4
Source File: walkers.py    From role2vec with GNU General Public License v3.0 6 votes vote down vote up
def preprocess_transition_probs(self):
        """
        Preprocessing of transition probabilities for guiding the random walks.
        """
        G = self.G

        alias_nodes = {}
        print("")
        print("Preprocesing.\n")
        for node in tqdm(G.nodes()):
            unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(G.neighbors(node))]
            norm_const = sum(unnormalized_probs)
            normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]
            alias_nodes[node] = alias_setup(normalized_probs)

        alias_edges = {}
        triads = {}

        for edge in tqdm(G.edges()):
            alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])
            alias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0])

        self.alias_nodes = alias_nodes
        self.alias_edges = alias_edges 
Example #5
Source File: walkers.py    From role2vec with GNU General Public License v3.0 6 votes vote down vote up
def get_alias_edge(self, src, dst):
        """
        Get the alias edge setup lists for a given edge.
        """
        G = self.G
        p = self.p
        q = self.q

        unnormalized_probs = []
        for dst_nbr in sorted(G.neighbors(dst)):
            if dst_nbr == src:
                unnormalized_probs.append(G[dst][dst_nbr]['weight']/p)
            elif G.has_edge(dst_nbr, src):
                unnormalized_probs.append(G[dst][dst_nbr]['weight'])
            else:
                unnormalized_probs.append(G[dst][dst_nbr]['weight']/q)
        norm_const = sum(unnormalized_probs)
        normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]

        return alias_setup(normalized_probs) 
Example #6
Source File: gam.py    From GAM with GNU General Public License v3.0 6 votes vote down vote up
def make_step(self, node, graph, features, labels, inverse_labels):
        """
        :param node: Source node for step.
        :param graph: NetworkX graph.
        :param features: Feature matrix.
        :param labels: Node labels hash table.
        :param inverse_labels: Inverse node label hash table.
        """
        orig_neighbors = set(nx.neighbors(graph, node))
        label = self.sample_node_label(orig_neighbors, graph, features)
        labels = list(set(orig_neighbors).intersection(set(inverse_labels[str(label)])))
        new_node = random.choice(labels)
        new_node_attributes = torch.zeros((len(self.identifiers), 1))
        new_node_attributes[label, 0] = 1.0
        attention_score = self.attention[label]
        return new_node_attributes, new_node, attention_score 
Example #7
Source File: walkers.py    From role2vec with GNU General Public License v3.0 6 votes vote down vote up
def node2vec_walk(self, start_node):
        """
        Simulate a random walk starting from start node.
        """
        G = self.G
        alias_nodes = self.alias_nodes
        alias_edges = self.alias_edges

        walk = [start_node]

        while len(walk) < self.walk_length:
            cur = walk[-1]
            cur_nbrs = sorted(G.neighbors(cur))
            if len(cur_nbrs) > 0:
                if len(walk) == 1:
                    walk.append(cur_nbrs[alias_draw(alias_nodes[cur][0], alias_nodes[cur][1])])
                else:
                    prev = walk[-2]
                    next = cur_nbrs[alias_draw(alias_edges[(prev, cur)][0], alias_edges[(prev, cur)][1])]
                    walk.append(next)
            else:
                break
        walk = [str(node) for node in walk]
        return walk 
Example #8
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_neighbors(self):
        graph = nx.complete_graph(100)
        pop = random.sample(list(graph), 1)
        nbors = list(nx.neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), len(graph) - 1)

        graph = nx.path_graph(100)
        node = random.sample(list(graph), 1)[0]
        nbors = list(nx.neighbors(graph, node))
        # should be all the other vertices in the graph
        if node != 0 and node != 99:
            assert_equal(len(nbors), 2)
        else:
            assert_equal(len(nbors), 1)

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.neighbors(graph, 0))
        assert_equal(len(nbors), 99) 
Example #9
Source File: calculation_helper.py    From GEMSEC with GNU General Public License v3.0 6 votes vote down vote up
def node2vec_walk(self, walk_length, start_node):
        """
        Simulate a random walk starting from start node.
        """
        G = self.G
        alias_nodes = self.alias_nodes
        alias_edges = self.alias_edges

        walk = [start_node]

        while len(walk) < walk_length:
            cur = walk[-1]
            cur_nbrs = sorted(G.neighbors(cur))
            if len(cur_nbrs) > 0:
                if len(walk) == 1:
                    walk.append(cur_nbrs[alias_draw(alias_nodes[cur][0], alias_nodes[cur][1])])
                else:
                    prev = walk[-2]
                    next = cur_nbrs[alias_draw(alias_edges[(prev, cur)][0], alias_edges[(prev, cur)][1])]
                    walk.append(next)
            else:
                break

        return walk 
Example #10
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_neighbors(self):
        graph = nx.complete_graph(100)
        pop = random.sample(graph.nodes(), 1)
        nbors = list(nx.neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), len(graph) - 1)

        graph = nx.path_graph(100)
        node = random.sample(graph.nodes(), 1)[0]
        nbors = list(nx.neighbors(graph, node))
        # should be all the other vertices in the graph
        if node != 0 and node != 99:
            assert_equal(len(nbors), 2)
        else:
            assert_equal(len(nbors), 1)

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.neighbors(graph, 0))
        assert_equal(len(nbors), 99) 
Example #11
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_neighbors_complete_graph(self):
        graph = nx.complete_graph(100)
        pop = random.sample(list(graph), 1)
        nbors = list(nx.neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), len(graph) - 1)

        graph = nx.path_graph(100)
        node = random.sample(list(graph), 1)[0]
        nbors = list(nx.neighbors(graph, node))
        # should be all the other vertices in the graph
        if node != 0 and node != 99:
            assert_equal(len(nbors), 2)
        else:
            assert_equal(len(nbors), 1)

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.neighbors(graph, 0))
        assert_equal(len(nbors), 99) 
Example #12
Source File: network.py    From lndmanage with MIT License 6 votes vote down vote up
def nodes_in_neighborhood_of_nodes(self, nodes, blacklist_nodes, nnodes=100):
        """
        Takes a list of nodes and finds the neighbors with most connections to the nodes.

        :param nodes: list
        :param blacklist_nodes: list of node_pub_keys to be excluded from counting
        :param nnodes: int, limit for the number of nodes returned
        :return: list of tuples, (str pub_key, int number of neighbors)
        """
        nodes = set(nodes)
        # eliminate blacklisted nodes
        nodes = nodes.difference(blacklist_nodes)
        neighboring_nodes = []
        for general_node in self.graph.nodes:
            neighbors_general_node = set(self.neighbors(general_node))
            intersection_with_nodes = nodes.intersection(neighbors_general_node)
            number_of_connection_with_nodes = len(intersection_with_nodes)
            neighboring_nodes.append((general_node, number_of_connection_with_nodes))

        sorted_neighboring_nodes = sorted(neighboring_nodes, key=lambda x: x[1], reverse=True)
        return sorted_neighboring_nodes[:nnodes] 
Example #13
Source File: model.py    From LabelPropagation with GNU General Public License v3.0 5 votes vote down vote up
def do_a_propagation(self):
        """
        Doing a propagation round.
        """
        random.seed(self.seeding)
        random.shuffle(self.nodes)
        for node in tqdm(self.nodes):
            neighbors = nx.neighbors(self.graph, node)
            pick = self.make_a_pick(node, neighbors)
            self.labels[node] = pick
        current_label_count = len(set(self.labels.values()))
        if self.label_count == current_label_count:
            self.flag = False
        else:
            self.label_count = current_label_count 
Example #14
Source File: walkers.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def do_walk(self, node):
        """
        Doing a single truncated random walk from a source node.
        :param node: Source node of the truncated random walk.
        :return walk: A single random walk.
        """
        walk = [node]
        while len(walk) < self.walk_length:
            nebs = [n for n in nx.neighbors(self.G, walk[-1])]
            if len(nebs) == 0:
                break
            walk.append(random.choice(nebs))
        return walk 
Example #15
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_neighbors(self):
        assert_equal(self.G.neighbors(1),nx.neighbors(self.G,1))
        assert_equal(self.DG.neighbors(1),nx.neighbors(self.DG,1)) 
Example #16
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_custom1(self):
        """Case of no common neighbors."""
        G = nx.Graph()
        G.add_nodes_from([0, 1])
        self.test(G, 0, 1, []) 
Example #17
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_neighbors(self):
        assert_equal(list(self.G.neighbors(1)), list(nx.neighbors(self.G, 1)))
        assert_equal(list(self.DG.neighbors(1)), list(nx.neighbors(self.DG, 1))) 
Example #18
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_custom1(self):
        """Case of no common neighbors."""
        G = nx.Graph()
        G.add_nodes_from([0, 1])
        self.test(G, 0, 1, []) 
Example #19
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def inducer(graph, node):
    nebs = nx.neighbors(graph, node)
    sub_nodes = nebs + [node]
    sub_g = nx.subgraph(graph, sub_nodes)
    out_counts = np.sum(map(lambda x: len(nx.neighbors(graph,x)), sub_nodes))
    return sub_g, out_counts, nebs 
Example #20
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_neighbors(self):
        assert_equal(self.G.neighbors(1), nx.neighbors(self.G, 1))
        assert_equal(self.DG.neighbors(1), nx.neighbors(self.DG, 1)) 
Example #21
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_custom1(self):
        """Case of no common neighbors."""
        G = nx.Graph()
        G.add_nodes_from([0, 1])
        self.test(G, 0, 1, []) 
Example #22
Source File: model.py    From LabelPropagation with GNU General Public License v3.0 5 votes vote down vote up
def make_a_pick(self, source, neighbors):
        """
        Choosing a neighbor from a propagation source node.
        :param source: Source node.
        :param neigbors: Neighboring nodes.
        """
        scores = {}
        for neighbor in neighbors:
            neighbor_label = self.labels[neighbor]
            if neighbor_label in scores.keys():
                scores[neighbor_label] = scores[neighbor_label] + self.weights[(neighbor, source)]
            else:
                scores[neighbor_label] = self.weights[(neighbor, source)]
        top = [key for key, val in scores.items() if val == max(scores.values())]
        return random.sample(top, 1)[0] 
Example #23
Source File: calculation_helper.py    From LabelPropagation with GNU General Public License v3.0 5 votes vote down vote up
def min_norm(g, node_1, node_2):
    """
    Calculating the min normalized neighbourhood overlap.
    :param g: NetworkX graph.
    :param node_1: First end node of edge.
    :param node_2: Second end node of edge.
    """
    inter = len(set(nx.neighbors(g, node_1)).intersection(set(nx.neighbors(g, node_2))))
    min_norm = min(len(set(nx.neighbors(g, node_1))), len(set(nx.neighbors(g, node_2))))
    return float(inter)/float(min_norm) 
Example #24
Source File: calculation_helper.py    From LabelPropagation with GNU General Public License v3.0 5 votes vote down vote up
def overlap(g, node_1, node_2):
    """
    Calculating the neighbourhood overlap.
    :param g: NetworkX graph.
    :param node_1: First end node of edge.
    :param node_2: Second end node of edge.
    """
    inter = len(set(nx.neighbors(g, node_1)).intersection(set(nx.neighbors(g, node_2))))
    return float(inter) 
Example #25
Source File: calculation_helper.py    From LabelPropagation with GNU General Public License v3.0 5 votes vote down vote up
def normalized_overlap(g, node_1, node_2):
    """
    Calculating the normalized neighbourhood overlap.
    :param g: NetworkX graph.
    :param node_1: First end node of edge.
    :param node_2: Second end node of edge.
    """
    inter = len(set(nx.neighbors(g, node_1)).intersection(set(nx.neighbors(g, node_2))))
    unio = len(set(nx.neighbors(g, node_1)).union(set(nx.neighbors(g, node_2))))
    return float(inter)/float(unio) 
Example #26
Source File: network.py    From lndmanage with MIT License 5 votes vote down vote up
def second_neighbors(self, node_pub_key):
        """
        Finds all the node pub keys of second nearest neighbor nodes (multiple appearances allowed).

        :param node_pub_key: str
        :return: node_pub_key: str
        """
        for neighbor_list in [self.graph.neighbors(n) for n in self.graph.neighbors(node_pub_key)]:
            for n in neighbor_list:
                yield n 
Example #27
Source File: network.py    From lndmanage with MIT License 5 votes vote down vote up
def neighbors(self, node_pub_key):
        """
        Finds all the node pub keys of nearest neighbor nodes.

        :param node_pub_key:  str
        :return: node_pub_key: str
        """
        neighbors = nx.neighbors(self.graph, node_pub_key)
        for n in neighbors:
            yield n 
Example #28
Source File: helpers.py    From BoostedFactorization with GNU General Public License v3.0 5 votes vote down vote up
def do_a_walk(self, node):
        """
        Doing a single random walk from a source
        :param node: Source node.
        :return nodes: Truncated random walk
        """
        nodes = [node]
        while len(nodes) < self.args.walk_length:
            nebs = [n for n in nx.neighbors(self.graph, nodes[-1])]
            if len(nebs) > 0:
                nodes = nodes + random.sample(nebs, 1)
            else:
                break
        return nodes 
Example #29
Source File: calculation_helper.py    From GEMSEC with GNU General Public License v3.0 5 votes vote down vote up
def preprocess_transition_probs(self):
        """
        Preprocessing of transition probabilities for guiding the random walks.
        """
        G = self.G
        is_directed = self.is_directed

        alias_nodes = {}
        print("")
        print("Preprocesing.\n")
        for node in tqdm(G.nodes()):
             unnormalized_probs = [G[node][nbr]["weight"] for nbr in sorted(G.neighbors(node))]
             norm_const = sum(unnormalized_probs)
             normalized_probs =  [float(u_prob)/norm_const for u_prob in unnormalized_probs]
             alias_nodes[node] = alias_setup(normalized_probs)

        alias_edges = {}
        triads = {}

        if is_directed:
            for edge in G.edges():
                alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])
        else:
            for edge in tqdm(G.edges()):
                alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])
                alias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0])

        self.alias_nodes = alias_nodes
        self.alias_edges = alias_edges

        return 
Example #30
Source File: calculation_helper.py    From GEMSEC with GNU General Public License v3.0 5 votes vote down vote up
def small_walk(self, start_node):
        """
        Generate a node sequence from a start node.
        """
        walk = [start_node]
        while len(walk) != self.length:
            end_point = walk[-1]
            neighbors = [neb for neb in nx.neighbors(self.graph, end_point)]
            if len(neighbors) > 0:
                walk.append(random.choice(neighbors))
            else:
                break
        return walk