Python networkx.nodes() Examples

The following are 30 code examples of networkx.nodes(). 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: graph.py    From bioconda-utils with MIT License 6 votes vote down vote up
def build_from_recipes(recipes):
    logger.info("Building Recipe DAG")

    package2recipes = {}
    recipe_list = []
    for recipe in recipes:
        for package in recipe.package_names:
            package2recipes.setdefault(package, set()).add(recipe)
            recipe_list.append(recipe)

    dag = nx.DiGraph()
    dag.add_nodes_from(recipe.reldir for recipe in recipes)
    dag.add_edges_from(
        (recipe2, recipe)
        for recipe in recipe_list
        for dep in recipe.get_deps()
        for recipe2 in package2recipes.get(dep, [])
    )

    logger.info("Building Recipe DAG: done (%i nodes, %i edges)", len(dag), len(dag.edges()))
    return dag 
Example #2
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_add_star(self):
        G = self.G.copy()
        nlist = [12, 13, 14, 15]
        nx.add_star(G, nlist)
        assert_edges_equal(G.edges(nlist), [(12, 13), (12, 14), (12, 15)])

        G = self.G.copy()
        nx.add_star(G, nlist, weight=2.0)
        assert_edges_equal(G.edges(nlist, data=True),
                           [(12, 13, {'weight': 2.}),
                            (12, 14, {'weight': 2.}),
                            (12, 15, {'weight': 2.})])

        G = self.G.copy()
        nlist = [12]
        nx.add_star(G, nlist)
        assert_nodes_equal(G, list(self.G) + nlist)

        G = self.G.copy()
        nlist = []
        nx.add_star(G, nlist)
        assert_nodes_equal(G.nodes, self.Gnodes)
        assert_edges_equal(G.edges, self.G.edges) 
Example #3
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_set_node_attributes():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        G = nx.path_graph(3, create_using=G)

        # Test single value
        attr = 'hello'
        vals = 100
        nx.set_node_attributes(G, attr, vals)
        assert_equal(G.node[0][attr], vals)
        assert_equal(G.node[1][attr], vals)
        assert_equal(G.node[2][attr], vals)

        # Test multiple values
        attr = 'hi'
        vals = dict(zip(sorted(G.nodes()), range(len(G))))
        nx.set_node_attributes(G, attr, vals)
        assert_equal(G.node[0][attr], 0)
        assert_equal(G.node[1][attr], 1)
        assert_equal(G.node[2][attr], 2) 
Example #4
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 #5
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_info_digraph(self):
        G=nx.DiGraph(name='path_graph(5)')
        G.add_path([0,1,2,3,4])
        info=nx.info(G)
        expected_graph_info='\n'.join(['Name: path_graph(5)',
                                       'Type: DiGraph',
                                       'Number of nodes: 5',
                                       'Number of edges: 4',
                                       'Average in degree:   0.8000',
                                       'Average out degree:   0.8000'])
        assert_equal(info,expected_graph_info)

        info=nx.info(G,n=1)
        expected_node_info='\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info,expected_node_info)

        assert_raises(nx.NetworkXError,nx.info,G,n=-1) 
Example #6
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_info(self):
        G=nx.path_graph(5)
        info=nx.info(G)
        expected_graph_info='\n'.join(['Name: path_graph(5)',
                                       'Type: Graph',
                                       'Number of nodes: 5',
                                       'Number of edges: 4',
                                       'Average degree:   1.6000'])
        assert_equal(info,expected_graph_info)

        info=nx.info(G,n=1)
        expected_node_info='\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 0 2'])
        assert_equal(info,expected_node_info) 
Example #7
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_info_digraph(self):
        G = nx.DiGraph(name='path_graph(5)')
        nx.add_path(G, [0, 1, 2, 3, 4])
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: DiGraph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average in degree:   0.8000',
                                         'Average out degree:   0.8000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info, expected_node_info)

        assert_raises(nx.NetworkXError, nx.info, G, n=-1) 
Example #8
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 #9
Source File: calculation_helper.py    From GEMSEC with GNU General Public License v3.0 6 votes vote down vote up
def simulate_walks(self, num_walks, walk_length):
        """
        Repeatedly simulate random walks from each node.
        """
        G = self.G
        walks = []
        nodes = list(G.nodes())
        for walk_iter in range(num_walks):
            print(" ")
            print("Random walk series " + str(walk_iter+1) + ". initiated.")
            print(" ")
            random.shuffle(nodes)
            for node in tqdm(nodes):
                walks.append(self.node2vec_walk(walk_length=walk_length, start_node=node))

        return walks, self.count_frequency_values(walks) 
Example #10
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_info(self):
        G = nx.path_graph(5)
        G.name = "path_graph(5)"
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: Graph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average degree:   1.6000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 0 2'])
        assert_equal(info, expected_node_info) 
Example #11
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_info_digraph(self):
        G = nx.DiGraph(name='path_graph(5)')
        nx.add_path(G, [0, 1, 2, 3, 4])
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: DiGraph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average in degree:   0.8000',
                                         'Average out degree:   0.8000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info, expected_node_info)

        assert_raises(nx.NetworkXError, nx.info, G, n=-1) 
Example #12
Source File: Demon.py    From DEMON with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, graph=None, network_filename=None, epsilon=0.25, min_community_size=3, file_output=None):
        """
        Constructor

        :@param network_filename: the networkx filename
        :@param epsilon: the tolerance required in order to merge communities
        :@param min_community_size:min nodes needed to form a community
        :@param file_output: True/False
        """
        if graph is None:
            self.g = nx.Graph()
            if network_filename is not None:
                self.__read_graph(network_filename)
            else:
                raise ImportError
        else:
            self.g = graph
        self.epsilon = epsilon
        self.min_community_size = min_community_size
        self.file_output = file_output
        self.base = os.getcwd() 
Example #13
Source File: walkers.py    From MUSAE 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
        print("\n") 
Example #14
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 #15
Source File: walkers.py    From MUSAE with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, G, p, q, num_walks, walk_length):
        """
        :param G: NetworkX graph object.
        :param p: Return parameter.
        :param q: In-out parameter.
        :param num_walks: Number of walks per source node.
        :param walk_length: Random walk length.
        """
        self.G = G
        self.nodes = nx.nodes(self.G)
        print("Edge weighting.\n")
        for edge in tqdm(self.G.edges()):
            self.G[edge[0]][edge[1]]['weight'] = 1.0
            self.G[edge[1]][edge[0]]['weight'] = 1.0
        self.p = p
        self.q = q
        self.num_walks = num_walks
        self.walk_length = walk_length
        self.preprocess_transition_probs()
        self.simulate_walks() 
Example #16
Source File: walkers.py    From walklets with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, nx_G, is_directed, args):
        """
        Constructor for SecondOrderRandomWalker.
        :param  nx_G: Nx graph object.
        :param is_directed: Directed nature of the graph -- True/False.
        :param args: Arguments object.
        """
        self.G = nx_G
        self.nodes = nx.nodes(self.G)
        print("Edge weighting.\n")
        for edge in tqdm(self.G.edges()):
            self.G[edge[0]][edge[1]]['weight'] = 1.0
            self.G[edge[1]][edge[0]]['weight'] = 1.0
        self.is_directed = is_directed
        self.walk_length = args.walk_length
        self.walk_number = args.walk_number
        self.p = args.P
        self.q = args.Q 
Example #17
Source File: walkers.py    From role2vec with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, G, p, q, num_walks, walk_length):
        """
        :param G: NetworkX object.
        :param p: Return parameter.
        :param q: In-out parameter.
        :param num_walks: Number of walks per source.
        :param walk_length: Number of nodes in walk.
        """
        self.G = G
        self.nodes = nx.nodes(self.G)
        print("Edge weighting.\n")
        for edge in tqdm(self.G.edges()):
            self.G[edge[0]][edge[1]]['weight'] = 1.0
            self.G[edge[1]][edge[0]]['weight'] = 1.0
        self.p = p
        self.q = q
        self.num_walks = num_walks
        self.walk_length = walk_length
        self.preprocess_transition_probs()
        self.simulate_walks() 
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_custom2(self):
        """Case of equal nodes."""
        G = nx.complete_graph(4)
        self.test(G, 0, 0, [1, 2, 3]) 
Example #19
Source File: walkers.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def simulate_walks(self):
        """
        Doing a fixed number of truncated random walk from every node in the graph.
        """
        self.walks = []
        for iteration in range(self.num_walks):
            print("\nRandom walk round: "+str(iteration+1)+"/"+str(self.num_walks)+".\n")
            for node in tqdm(self.G.nodes()):
                walk_from_node = self.do_walk(node)
                self.walks.append(walk_from_node) 
Example #20
Source File: walkers.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, G, num_walks, walk_length):
        """
        :param G: NetworkX graph object.
        :param num_walks: Number of walks per source node.
        :param walk_length: Number of nodes in turnctaed randonm walk.
        """
        self.G = G
        self.num_walks = num_walks
        self.walk_length = walk_length
        self.simulate_walks() 
Example #21
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_cycle(self):
        G = self.G.copy()
        nlist = [12, 13, 14, 15]
        oklists = [[(12, 13), (12, 15), (13, 14), (14, 15)],
                   [(12, 13), (13, 14), (14, 15), (15, 12)]]
        nx.add_cycle(G, nlist)
        assert_true(sorted(G.edges(nlist)) in oklists)
        G = self.G.copy()
        oklists = [[(12, 13, {'weight': 1.}),
                    (12, 15, {'weight': 1.}),
                    (13, 14, {'weight': 1.}),
                    (14, 15, {'weight': 1.})],
                   [(12, 13, {'weight': 1.}),
                    (13, 14, {'weight': 1.}),
                    (14, 15, {'weight': 1.}),
                    (15, 12, {'weight': 1.})]]
        nx.add_cycle(G, nlist, weight=1.0)
        assert_true(sorted(G.edges(nlist, data=True)) in oklists)

        G = self.G.copy()
        nlist = [12]
        nx.add_cycle(G, nlist)
        assert_nodes_equal(G, list(self.G) + nlist)

        G = self.G.copy()
        nlist = []
        nx.add_cycle(G, nlist)
        assert_nodes_equal(G.nodes, self.Gnodes)
        assert_edges_equal(G.edges, self.G.edges) 
Example #22
Source File: walkers.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def simulate_walks(self):
        """
        Repeatedly simulate random walks from each node.
        """
        G = self.G
        self.walks = []
        nodes = list(G.nodes())
        for iteration in range(self.num_walks):
            print("\nRandom walk round: "+str(iteration+1)+"/"+str(self.num_walks)+".\n")
            random.shuffle(nodes)
            for node in tqdm(nodes):
                self.walks.append(self.node2vec_walk(start_node=node)) 
Example #23
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_restricted_view(self):
        H = nx.restricted_view(self.G, [0, 2, 5], [(1, 2), (3, 4)])
        assert_equal(set(H.nodes), {1, 3, 4})
        assert_equal(set(H.edges), {(1, 1)}) 
Example #24
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_create_empty_copy(self):
        G = nx.create_empty_copy(self.G, with_data=False)
        assert_nodes_equal(G, list(self.G))
        assert_equal(G.graph, {})
        assert_equal(G._node, {}.fromkeys(self.G.nodes(), {}))
        assert_equal(G._adj, {}.fromkeys(self.G.nodes(), {}))
        G = nx.create_empty_copy(self.G)
        assert_nodes_equal(G, list(self.G))
        assert_equal(G.graph, self.G.graph)
        assert_equal(G._node, self.G._node)
        assert_equal(G._adj, {}.fromkeys(self.G.nodes(), {})) 
Example #25
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_set_node_attributes():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        # Test single value
        G = nx.path_graph(3, create_using=G)
        vals = 100
        attr = 'hello'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], vals)
        assert_equal(G.nodes[1][attr], vals)
        assert_equal(G.nodes[2][attr], vals)

        # Test dictionary
        G = nx.path_graph(3, create_using=G)
        vals = dict(zip(sorted(G.nodes()), range(len(G))))
        attr = 'hi'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], 0)
        assert_equal(G.nodes[1][attr], 1)
        assert_equal(G.nodes[2][attr], 2)

        # Test dictionary of dictionaries
        G = nx.path_graph(3, create_using=G)
        d = {'hi': 0, 'hello': 200}
        vals = dict.fromkeys(G.nodes(), d)
        vals.pop(0)
        nx.set_node_attributes(G, vals)
        assert_equal(G.nodes[0], {})
        assert_equal(G.nodes[1]["hi"], 0)
        assert_equal(G.nodes[2]["hello"], 200) 
Example #26
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_non_neighbors(self):
        graph = nx.complete_graph(100)
        pop = random.sample(list(graph), 1)
        nbors = list(nx.non_neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), 0)

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

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 0)

        # disconnected graph
        graph = nx.Graph()
        graph.add_nodes_from(range(10))
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 9) 
Example #27
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_custom2(self):
        """Case of equal nodes."""
        G = nx.complete_graph(4)
        self.test(G, 0, 0, [1, 2, 3]) 
Example #28
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_set_node_attributes():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        # Test single value
        G = nx.path_graph(3, create_using=G)
        vals = 100
        attr = 'hello'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], vals)
        assert_equal(G.nodes[1][attr], vals)
        assert_equal(G.nodes[2][attr], vals)

        # Test dictionary
        G = nx.path_graph(3, create_using=G)
        vals = dict(zip(sorted(G.nodes()), range(len(G))))
        attr = 'hi'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], 0)
        assert_equal(G.nodes[1][attr], 1)
        assert_equal(G.nodes[2][attr], 2)

        # Test dictionary of dictionaries
        G = nx.path_graph(3, create_using=G)
        d = {'hi': 0, 'hello': 200}
        vals = dict.fromkeys(G.nodes(), d)
        vals.pop(0)
        nx.set_node_attributes(G, vals)
        assert_equal(G.nodes[0], {})
        assert_equal(G.nodes[1]["hi"], 0)
        assert_equal(G.nodes[2]["hello"], 200) 
Example #29
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, args):
        self.args = args
        if self.args.aggregator == "complex":
            self.aggregator = complex_aggregator
        else:
            self.aggregator = aggregator
        self.multiplier = len(self.aggregator(0))
        self.graph = dataset_reader(self.args.input)
        self.nodes = nx.nodes(self.graph)
        self.create_features() 
Example #30
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def basic_stat_extractor(self):
        self.base_features = []
        self.sub_graph_container = {}
        for node in tqdm(range(0,len(self.nodes))):
            sub_g, overall_counts, nebs = inducer(self.graph, node)
            in_counts = len(nx.edges(sub_g))
            self.sub_graph_container[node] = nebs
            deg = nx.degree(sub_g, node)
            trans = nx.clustering(sub_g, node)
            self.base_features.append([in_counts, overall_counts, float(in_counts)/float(overall_counts), float(overall_counts - in_counts)/float(overall_counts),deg, trans])
        self.features = {}
        self.features[0] = np.array(self.base_features)
        print("") 
        del self.base_features