Python networkx.degree() Examples

The following are 30 code examples of networkx.degree(). 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: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def hub_dominance(graph, communities, **kwargs):
    """Hub dominance.

    The hub dominance of a community is defined as the ratio of the degree of its most connected node w.r.t. the theoretically maximal degree within the community.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.hub_dominance(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: max([x[1] for x in
                                                      list(nx.degree(nx.subgraph(graph, coms)))]) / (len(coms) - 1),
                             **kwargs) 
Example #2
Source File: utils.py    From GraphRNN with MIT License 7 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #3
Source File: graph2vec.py    From graph2vec with GNU General Public License v3.0 6 votes vote down vote up
def dataset_reader(path):
    """
    Function to read the graph and features from a json file.
    :param path: The path to the graph json.
    :return graph: The graph object.
    :return features: Features hash table.
    :return name: Name of the graph.
    """
    name = path.strip(".json").split("/")[-1]
    data = json.load(open(path))
    graph = nx.from_edgelist(data["edges"])

    if "features" in data.keys():
        features = data["features"]
    else:
        features = nx.degree(graph)

    features = {int(k): v for k, v in features.items()}
    return graph, features, name 
Example #4
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 #5
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 #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: utils.py    From graph-generation with MIT License 6 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #8
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 #9
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 #10
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 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: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def newman_girvan_modularity(graph, communities, **kwargs):
    """Difference the fraction of intra community edges of a partition with the expected number of such edges if distributed according to a null model.

    In the standard version of modularity, the null model preserves the expected degree sequence of the graph under consideration. In other words, the modularity compares the real network structure with a corresponding one where nodes are connected without any preference about their neighbors.

    .. math:: Q(S) = \\frac{1}{m}\\sum_{c \\in S}(m_S - \\frac{(2 m_S + l_S)^2}{4m})

    where :math:`m` is the number of graph edges, :math:`m_S` is the number of community edges, :math:`l_S` is the number of edges from nodes in S to nodes outside S.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :return: FitnessResult object


    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.newman_girvan_modularity(g,communities)

    :References:

    1. Newman, M.E.J. & Girvan, M. `Finding and evaluating community structure in networks. <https://www.ncbi.nlm.nih.gov/pubmed/14995526/>`_ Physical Review E 69, 26113(2004).
    """

    graph = convert_graph_formats(graph, nx.Graph)
    partition = {}
    for cid, com in enumerate(communities.communities):
        for node in com:
            partition[node] = cid

    return FitnessResult(score=pq.PartitionQuality.community_modularity(partition, graph)) 
Example #12
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_degree(self):
        assert_edges_equal(self.G.degree(), list(nx.degree(self.G)))
        assert_equal(sorted(self.DG.degree()), sorted(nx.degree(self.DG)))
        assert_edges_equal(self.G.degree(nbunch=[0, 1]),
                           list(nx.degree(self.G, nbunch=[0, 1])))
        assert_equal(sorted(self.DG.degree(nbunch=[0, 1])),
                     sorted(nx.degree(self.DG, nbunch=[0, 1])))
        assert_edges_equal(self.G.degree(weight='weight'),
                           list(nx.degree(self.G, weight='weight')))
        assert_equal(sorted(self.DG.degree(weight='weight')),
                     sorted(nx.degree(self.DG, weight='weight'))) 
Example #13
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def flake_odf(graph, community, **kwargs):
    """Fraction of nodes in S that have fewer edges pointing inside than to the outside of the community.

    .. math:: f(S) = \\frac{| \{ u:u \in S,| \{(u,v) \in E: v \in S \}| < d(u)/2 \}|}{n_S}

    where :math:`E` is the graph edge set, :math:`v` is a node in :math:`S`, :math:`d(u)` is the degree of :math:`u` and :math:`n_S` is the set of community nodes.

    :param graph: a networkx/igraph object
    :param community: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.flake_odf(g,communities)

    :References:

    1. Flake, G.W., Lawrence, S., Giles, C.L., et al.: Efficient identification of web communities. In: KDD, vol. 2000, pp. 150–160 (2000)
    """

    return __quality_indexes(graph, community, pq.PartitionQuality.flake_odf, **kwargs) 
Example #14
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def max_odf(graph, community, **kwargs):
    """Maximum fraction of edges of a node of a community that point outside the community itself.

    .. math:: max_{u \\in S} \\frac{|\{(u,v)\\in E: v \\not\\in S\}|}{d(u)}

    where :math:`E` is the graph edge set, :math:`v` is a node in :math:`S` and :math:`d(u)` is the degree of :math:`u`

    :param graph: a networkx/igraph object
    :param community: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.max_odf(g,communities)

    :References:

    1. Flake, G.W., Lawrence, S., Giles, C.L., et al.: Efficient identification of web communities. In: KDD, vol. 2000, pp. 150–160 (2000)
    """

    return __quality_indexes(graph, community, pq.PartitionQuality.max_odf, **kwargs) 
Example #15
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fraction_over_median_degree(graph, community, **kwargs):
    """Fraction of community nodes of having internal degree higher than the median degree value.

    .. math:: f(S) = \\frac{|\{u: u \\in S,| \{(u,v): v \\in S\}| > d_m\}| }{n_S}


    where :math:`d_m` is the internal degree median value

    :param graph: a networkx/igraph object
    :param community: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.fraction_over_median_degree(g,communities)

    :References:

    1. Yang, J., Leskovec, J.: Defining and evaluating network communities based on ground-truth. Knowledge and Information Systems 42(1), 181–213 (2015)
    """

    return __quality_indexes(graph, community, pq.PartitionQuality.fraction_over_median_degree, **kwargs) 
Example #16
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def average_internal_degree(graph, community, **kwargs):
    """The average internal degree of the community set.

    .. math:: f(S) = \\frac{2m_S}{n_S}

     where :math:`m_S` is the number of community internal edges and :math:`n_S` is the number of community nodes.

    :param graph: a networkx/igraph object
    :param community: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.average_internal_degree(g,communities)

    :References:

    1. Radicchi, F., Castellano, C., Cecconi, F., Loreto, V., & Parisi, D. (2004). Defining and identifying communities in networks. Proceedings of the National Academy of Sciences, 101(9), 2658-2663.
    """

    return __quality_indexes(graph, community, pq.PartitionQuality.average_internal_degree, **kwargs) 
Example #17
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def avg_embeddedness(graph, communities, **kwargs):
    """Average embeddedness of nodes within the community.

    The embeddedness of a node n w.r.t. a community C is the ratio of its degree within the community and its overall degree.

    .. math:: emb(n,C) = \\frac{k_n^C}{k_n}

    The average embeddedness of a community C is:

    .. math:: avg_embd(c) = \\frac{1}{|C|} \sum_{i \in C} \\frac{k_n^C}{k_n}

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> ave = evaluation.avg_embeddedness(g,communities)

    :References:


    """

    return __quality_indexes(graph, communities,
                             lambda g, com:
                             np.mean([float(nx.degree(nx.subgraph(g, com))[n]) / nx.degree(g)[n] for n in com]),
                             **kwargs) 
Example #18
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_degree(self):
        assert_equal(self.G.degree(),nx.degree(self.G))
        assert_equal(self.DG.degree(),nx.degree(self.DG))
        assert_equal(self.G.degree(nbunch=[0,1]),nx.degree(self.G,nbunch=[0,1]))
        assert_equal(self.DG.degree(nbunch=[0,1]),nx.degree(self.DG,nbunch=[0,1]))
        assert_equal(self.G.degree(weight='weight'),nx.degree(self.G,weight='weight'))
        assert_equal(self.DG.degree(weight='weight'),nx.degree(self.DG,weight='weight')) 
Example #19
Source File: mnmf.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def _modularity_generator(self):
        """Calculating the sparse modularity matrix."""
        degs = nx.degree(self._graph)
        e_count = self._graph.number_of_edges()
        n_count = self._graph.number_of_nodes()
        modularity_mat_shape = (n_count, n_count)
        indices_1 = np.array([edge[0] for edge in self._graph.edges()] + [edge[1] for edge in self._graph.edges()])
        indices_2 = np.array([edge[1] for edge in self._graph.edges()] + [edge[0] for edge in self._graph.edges()])
        scores = [1.0-(float(degs[e[0]]*degs[e[1]])/(2*e_count)) for e in self._graph.edges()]
        scores = scores + [1.0-(float(degs[e[1]]*degs[e[0]])/(2*e_count)) for e in self._graph.edges()]
        mod_matrix = coo_matrix((scores, (indices_1, indices_2)), shape=modularity_mat_shape)
        return mod_matrix 
Example #20
Source File: test_edge_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_four_clique():
    paths = [
        (11, 12, 13, 14, 11, 13, 14, 12),  # first 4-clique
        (21, 22, 23, 24, 21, 23, 24, 22),  # second 4-clique
        # paths connecting the 4 cliques such that they are
        # 3-connected in G, but not in the subgraph.
        # Case where the nodes bridging them do not have degree less than 3.
        (100, 13),
        (12, 100, 22),
        (13, 200, 23),
        (14, 300, 24),
    ]
    G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))

    # The subgraphs and ccs are different for k=3
    local_ccs = fset(nx.k_edge_components(G, k=3))
    subgraphs = fset(nx.k_edge_subgraphs(G, k=3))
    assert_not_equal(local_ccs, subgraphs)

    # The cliques ares in the same cc
    clique1 = frozenset(paths[0])
    clique2 = frozenset(paths[1])
    assert_in(clique1.union(clique2).union({100}), local_ccs)

    # but different subgraphs
    assert_in(clique1, subgraphs)
    assert_in(clique2, subgraphs)

    assert_equal(G.degree(100), 3)

    _check_edge_connectivity(G) 
Example #21
Source File: test_edge_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_five_clique():
    # Make a graph that can be disconnected less than 4 edges, but no node has
    # degree less than 4.
    G = nx.disjoint_union(nx.complete_graph(5), nx.complete_graph(5))
    paths = [
        # add aux-connections
        (1, 100, 6), (2, 100, 7), (3, 200, 8), (4, 200, 100),
    ]
    G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
    assert_equal(min(dict(nx.degree(G)).values()), 4)

    # For k=3 they are the same
    assert_equal(
        fset(nx.k_edge_components(G, k=3)),
        fset(nx.k_edge_subgraphs(G, k=3))
    )

    # For k=4 they are the different
    # the aux nodes are in the same CC as clique 1 but no the same subgraph
    assert_not_equal(
        fset(nx.k_edge_components(G, k=4)),
        fset(nx.k_edge_subgraphs(G, k=4))
    )

    # For k=5 they are not the same
    assert_not_equal(
        fset(nx.k_edge_components(G, k=5)),
        fset(nx.k_edge_subgraphs(G, k=5))
    )

    # For k=6 they are the same
    assert_equal(
        fset(nx.k_edge_components(G, k=6)),
        fset(nx.k_edge_subgraphs(G, k=6))
    )
    _check_edge_connectivity(G)


# ----------------
# Undirected tests
# ---------------- 
Example #22
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 
Example #23
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_degree(self):
        assert_edges_equal(self.G.degree(), list(nx.degree(self.G)))
        assert_equal(sorted(self.DG.degree()), sorted(nx.degree(self.DG)))
        assert_edges_equal(self.G.degree(nbunch=[0, 1]),
                           list(nx.degree(self.G, nbunch=[0, 1])))
        assert_equal(sorted(self.DG.degree(nbunch=[0, 1])),
                     sorted(nx.degree(self.DG, nbunch=[0, 1])))
        assert_edges_equal(self.G.degree(weight='weight'),
                           list(nx.degree(self.G, weight='weight')))
        assert_equal(sorted(self.DG.degree(weight='weight')),
                     sorted(nx.degree(self.DG, weight='weight'))) 
Example #24
Source File: test_edge_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_four_clique():
    paths = [
        (11, 12, 13, 14, 11, 13, 14, 12),  # first 4-clique
        (21, 22, 23, 24, 21, 23, 24, 22),  # second 4-clique
        # paths connecting the 4 cliques such that they are
        # 3-connected in G, but not in the subgraph.
        # Case where the nodes bridging them do not have degree less than 3.
        (100, 13),
        (12, 100, 22),
        (13, 200, 23),
        (14, 300, 24),
    ]
    G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))

    # The subgraphs and ccs are different for k=3
    local_ccs = fset(nx.k_edge_components(G, k=3))
    subgraphs = fset(nx.k_edge_subgraphs(G, k=3))
    assert_not_equal(local_ccs, subgraphs)

    # The cliques ares in the same cc
    clique1 = frozenset(paths[0])
    clique2 = frozenset(paths[1])
    assert_in(clique1.union(clique2).union({100}), local_ccs)

    # but different subgraphs
    assert_in(clique1, subgraphs)
    assert_in(clique2, subgraphs)

    assert_equal(G.degree(100), 3)

    _check_edge_connectivity(G) 
Example #25
Source File: test_edge_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_five_clique():
    # Make a graph that can be disconnected less than 4 edges, but no node has
    # degree less than 4.
    G = nx.disjoint_union(nx.complete_graph(5), nx.complete_graph(5))
    paths = [
        # add aux-connections
        (1, 100, 6), (2, 100, 7), (3, 200, 8), (4, 200, 100),
    ]
    G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
    assert_equal(min(dict(nx.degree(G)).values()), 4)

    # For k=3 they are the same
    assert_equal(
        fset(nx.k_edge_components(G, k=3)),
        fset(nx.k_edge_subgraphs(G, k=3))
    )

    # For k=4 they are the different
    # the aux nodes are in the same CC as clique 1 but no the same subgraph
    assert_not_equal(
        fset(nx.k_edge_components(G, k=4)),
        fset(nx.k_edge_subgraphs(G, k=4))
    )

    # For k=5 they are not the same
    assert_not_equal(
        fset(nx.k_edge_components(G, k=5)),
        fset(nx.k_edge_subgraphs(G, k=5))
    )

    # For k=6 they are the same
    assert_equal(
        fset(nx.k_edge_components(G, k=6)),
        fset(nx.k_edge_subgraphs(G, k=6))
    )
    _check_edge_connectivity(G)


# ----------------
# Undirected tests
# ---------------- 
Example #26
Source File: calculation_helper.py    From M-NMF with GNU General Public License v3.0 5 votes vote down vote up
def modularity_generator(G):
    """
    Function to generate a modularity matrix.
    :param G: Graph object.
    :return laps: Modularity matrix.
    """
    print("Modularity calculation.\n")
    degs = nx.degree(G)
    e_count = len(nx.edges(G))
    modu = np.array([[float(degs[n_1]*degs[n_2])/(2*e_count) for n_1 in nx.nodes(G)] for n_2 in tqdm(nx.nodes(G))], dtype=np.float64)
    return modu 
Example #27
Source File: graph_gens.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def watts_strogatz_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – The number of nodes
    k (int) – Each node is joined with its k nearest neighbors in a ring topology.
    p (float) – The probability of rewiring each edge

    Average Degree is solely decided by k
    Diameter depends on the value of p
    :return: Graph Object
    '''
    strt_time = time()

    p = 0.2

    G = nx.watts_strogatz_graph(n=N, k=deg, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))

    end_time = time()

    print('Graph_Name: Watts_Strogatz_Graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)

    return best_G, best_avg_deg, best_diam

######################################################################## 
Example #28
Source File: graph_gens.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def powerlaw_cluster_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – the number of nodes
    m (int) – the number of random edges to add for each new node
    p (float,) – Probability of adding a triangle after adding a random edge
    Formula for m:  (m^2)- (Nm)/2 + avg_deg * (N/2) = 0  =>  From this equation we need to find m :
    p : Does not vary the average degree or diameter so much. : Higher value of p may cause average degree to overshoot intended average_deg
    so we give the control of average degree to parameter m: by setting a lower value of p: 0.1
    :return: Graph Object
    '''

    ## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree:   3.2000'
    strt_time = time()

    m = int(round((N - np.sqrt(N ** 2 - 4 * deg * N)) / 4))
    p = 0.2

    ## G at center:
    G = nx.powerlaw_cluster_graph(n=N, m=m, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))


    end_time = time()
    print('Graph_Name: powerlaw_cluster_graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)
    return best_G, best_avg_deg, best_diam

##################################################################### 
Example #29
Source File: graph.py    From momepy with MIT License 5 votes vote down vote up
def node_degree(graph, name="degree"):
    """
    Calculates node degree for each node.

    Wrapper around ``networkx.degree()``.

    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    name : str (default 'degree')
        calculated attribute name

    Returns
    -------
    Graph
        networkx.Graph

    Examples
    --------
    >>> network_graph = mm.node_degree(network_graph)
    """
    netx = graph.copy()

    degree = dict(nx.degree(netx))
    nx.set_node_attributes(netx, degree, name)

    return netx 
Example #30
Source File: graph.py    From momepy with MIT License 5 votes vote down vote up
def _mean_node_degree(graph, degree):
    """
    Calculates mean node degree in a graph.
    """
    return np.mean(list(dict(graph.nodes(degree)).values()))