Python networkx.ego_graph() Examples

The following are 24 code examples of networkx.ego_graph(). 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_ego.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_ego(self):
        G = nx.star_graph(3)
        H = nx.ego_graph(G, 0)
        assert_true(nx.is_isomorphic(G, H))
        G.add_edge(1, 11)
        G.add_edge(2, 22)
        G.add_edge(3, 33)
        H = nx.ego_graph(G, 0)
        assert_true(nx.is_isomorphic(nx.star_graph(3), H))
        G = nx.path_graph(3)
        H = nx.ego_graph(G, 0)
        assert_edges_equal(H.edges(), [(0, 1)])
        H = nx.ego_graph(G, 0, undirected=True)
        assert_edges_equal(H.edges(), [(0, 1)])
        H = nx.ego_graph(G, 0, center=False)
        assert_edges_equal(H.edges(), []) 
Example #2
Source File: test_ego.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ego(self):
        G = nx.star_graph(3)
        H = nx.ego_graph(G, 0)
        assert_true(nx.is_isomorphic(G, H))
        G.add_edge(1, 11)
        G.add_edge(2, 22)
        G.add_edge(3, 33)
        H = nx.ego_graph(G, 0)
        assert_true(nx.is_isomorphic(nx.star_graph(3), H))
        G = nx.path_graph(3)
        H = nx.ego_graph(G, 0)
        assert_edges_equal(H.edges(), [(0, 1)])
        H = nx.ego_graph(G, 0, undirected=True)
        assert_edges_equal(H.edges(), [(0, 1)])
        H = nx.ego_graph(G, 0, center=False)
        assert_edges_equal(H.edges(), []) 
Example #3
Source File: test_ego.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_ego(self):
        G=nx.star_graph(3)
        H=nx.ego_graph(G,0)
        assert_true(nx.is_isomorphic(G,H))
        G.add_edge(1,11)
        G.add_edge(2,22)
        G.add_edge(3,33)
        H=nx.ego_graph(G,0)
        assert_true(nx.is_isomorphic(nx.star_graph(3),H))
        G=nx.path_graph(3)
        H=nx.ego_graph(G,0)
        assert_equal(H.edges(), [(0, 1)])
        H=nx.ego_graph(G,0,undirected=True)
        assert_equal(H.edges(), [(0, 1)])
        H=nx.ego_graph(G,0,center=False)
        assert_equal(H.edges(), []) 
Example #4
Source File: overlapping_partition.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ego_networks(g_original, level=1):
    """
    Ego-networks returns overlapping communities centered at each nodes within a given radius.

    :param g_original: a networkx/igraph object
    :param level: extrac communities with all neighbors of distance<=level from a node. Deafault 1
    :return: NodeClustering object


    :Example:

    >>> from cdlib import algorithms
    >>> import networkx as nx
    >>> G = nx.karate_club_graph()
    >>> coms = algorithms.ego_networks(G)
    """

    g = convert_graph_formats(g_original, nx.Graph)

    coms = []
    for n in g.nodes():
        coms.append(list(nx.ego_graph(g, n, radius=level).nodes()))
    return NodeClustering(coms, g_original, "Ego Network", method_parameters={"level": 1}, overlap=True) 
Example #5
Source File: transaction_generator.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
def get_hub_vertices(self, num):
    """Get account vertices randomly (high-degree vertices are likely selected)

    :param num: Number of total account vertices
    :return: Account ID list
    """
    # if suspicious is None:
    #   candidates = self.g.nodes()
    # else:
    #   candidates = [n for n in self.g.nodes() if self.g.nodes[n]["suspicious"] == suspicious]  # True/False
    # candidates = [n for n in candidates if self.factor <= self.degrees[n]]
    # degrees = [self.degrees[n] for n in candidates]
    # probs = np.array(degrees) / float(sum(degrees))

    candidates = set()
    while len(candidates) < num:
      hub = random.choice(self.hubs)
      candidates.update([hub]+self.g.adj[hub].keys()) # candidates.update(nx.ego_graph(self.g, hub).nodes())
    return np.random.choice(list(candidates), num, False) 
Example #6
Source File: networkx.py    From GraphRole with MIT License 5 votes vote down vote up
def _get_egonet_features(self) -> pd.DataFrame:
        """
        Return egonet features for each node in the graph
        """
        egonet_features = {}
        for node in self.G.nodes:
            ego = nx.ego_graph(self.G, node, radius=1)
            ego_boundary = list(nx.edge_boundary(self.G, ego.nodes))
            egonet_features[node] = {
                'internal_edges': self._get_edge_sum(ego.edges),
                'external_edges': self._get_edge_sum(ego_boundary)
            }
        return pd.DataFrame.from_dict(egonet_features, orient='index')

    ### helpers ### 
Example #7
Source File: test_ego.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_ego_distance(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=2, distance=1)
        G.add_edge(1, 2, weight=2, distance=2)
        G.add_edge(2, 3, weight=2, distance=1)
        assert_nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3])
        eg = nx.ego_graph(G, 0, radius=3, distance='weight')
        assert_nodes_equal(eg.nodes(), [0, 1])
        eg = nx.ego_graph(G, 0, radius=3, distance='weight', undirected=True)
        assert_nodes_equal(eg.nodes(), [0, 1])
        eg = nx.ego_graph(G, 0, radius=3, distance='distance')
        assert_nodes_equal(eg.nodes(), [0, 1, 2]) 
Example #8
Source File: efficiency.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def local_efficiency(G):
    """Returns the average local efficiency of the graph.

    The *efficiency* of a pair of nodes in a graph is the multiplicative
    inverse of the shortest path distance between the nodes. The *local
    efficiency* of a node in the graph is the average global efficiency of the
    subgraph induced by the neighbors of the node. The *average local
    efficiency* is the average of the local efficiencies of each node [1]_.

    Parameters
    ----------
    G : :class:`networkx.Graph`
        An undirected graph for which to compute the average local efficiency.

    Returns
    -------
    float
        The average local efficiency of the graph.

    Notes
    -----
    Edge weights are ignored when computing the shortest path distances.

    See also
    --------
    global_efficiency

    References
    ----------
    .. [1] Latora, Vito, and Massimo Marchiori.
           "Efficient behavior of small-world networks."
           *Physical Review Letters* 87.19 (2001): 198701.
           <http://dx.doi.org/10.1103/PhysRevLett.87.198701>

    """
    # TODO This summation can be trivially parallelized.
    return sum(global_efficiency(nx.ego_graph(G, v)) for v in G) / len(G) 
Example #9
Source File: test_ego.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ego_distance(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=2, distance=1)
        G.add_edge(1, 2, weight=2, distance=2)
        G.add_edge(2, 3, weight=2, distance=1)
        assert_nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3])
        eg = nx.ego_graph(G, 0, radius=3, distance='weight')
        assert_nodes_equal(eg.nodes(), [0, 1])
        eg = nx.ego_graph(G, 0, radius=3, distance='weight', undirected=True)
        assert_nodes_equal(eg.nodes(), [0, 1])
        eg = nx.ego_graph(G, 0, radius=3, distance='distance')
        assert_nodes_equal(eg.nodes(), [0, 1, 2]) 
Example #10
Source File: test_ego.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_ego_distance(self):
        G=nx.Graph()                                                            
        G.add_edge(0,1,weight=2,distance=1)
        G.add_edge(1,2,weight=2,distance=2)
        G.add_edge(2,3,weight=2,distance=1) 
        assert_equal(sorted(nx.ego_graph(G,0,radius=3).nodes()),[0,1,2,3])
        eg=nx.ego_graph(G,0,radius=3,distance='weight')
        assert_equal(sorted(eg.nodes()),[0,1])
        eg=nx.ego_graph(G,0,radius=3,distance='weight',undirected=True)
        assert_equal(sorted(eg.nodes()),[0,1])
        eg=nx.ego_graph(G,0,radius=3,distance='distance')
        assert_equal(sorted(eg.nodes()),[0,1,2]) 
Example #11
Source File: utils.py    From GraphRNN with MIT License 5 votes vote down vote up
def citeseer_ego():
    _, _, G = data.Graph_load(dataset='citeseer')
    G = max(nx.connected_component_subgraphs(G), key=len)
    G = nx.convert_node_labels_to_integers(G)
    graphs = []
    for i in range(G.number_of_nodes()):
        G_ego = nx.ego_graph(G, i, radius=3)
        if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400):
            graphs.append(G_ego)
    return graphs 
Example #12
Source File: Demon.py    From DEMON with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def execute(self):
        """
        Execute Demon algorithm

        """

        for n in self.g.nodes():
            self.g.nodes[n]['communities'] = [n]

        all_communities = {}

        for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'):

            ego_minus_ego = nx.ego_graph(self.g, ego, 1, False)
            community_to_nodes = self.__overlapping_label_propagation(ego_minus_ego, ego)

            # merging phase
            for c in community_to_nodes.keys():
                if len(community_to_nodes[c]) > self.min_community_size:
                    actual_community = community_to_nodes[c]
                    all_communities = self.__merge_communities(all_communities, actual_community)

        # write output on file
        if self.file_output:
            with open(self.file_output, "w") as out_file_com:
                for idc, c in enumerate(all_communities.keys()):
                    out_file_com.write("%d\t%s\n" % (idc, str(sorted(c))))

        return list(all_communities.keys()) 
Example #13
Source File: utils.py    From graph-generation with MIT License 5 votes vote down vote up
def citeseer_ego():
    _, _, G = data.Graph_load(dataset='citeseer')
    G = max(nx.connected_component_subgraphs(G), key=len)
    G = nx.convert_node_labels_to_integers(G)
    graphs = []
    for i in range(G.number_of_nodes()):
        G_ego = nx.ego_graph(G, i, radius=3)
        if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400):
            graphs.append(G_ego)
    return graphs 
Example #14
Source File: data.py    From GraphRNN with MIT License 4 votes vote down vote up
def Graph_load(dataset = 'cora'):
    '''
    Load a single graph dataset
    :param dataset: dataset name
    :return:
    '''
    names = ['x', 'tx', 'allx', 'graph']
    objects = []
    for i in range(len(names)):
        load = pkl.load(open("dataset/ind.{}.{}".format(dataset, names[i]), 'rb'), encoding='latin1')
        # print('loaded')
        objects.append(load)
        # print(load)
    x, tx, allx, graph = tuple(objects)
    test_idx_reorder = parse_index_file("dataset/ind.{}.test.index".format(dataset))
    test_idx_range = np.sort(test_idx_reorder)

    if dataset == 'citeseer':
        # Fix citeseer dataset (there are some isolated nodes in the graph)
        # Find isolated nodes, add them as zero-vecs into the right position
        test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1)
        tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
        tx_extended[test_idx_range - min(test_idx_range), :] = tx
        tx = tx_extended

    features = sp.vstack((allx, tx)).tolil()
    features[test_idx_reorder, :] = features[test_idx_range, :]
    G = nx.from_dict_of_lists(graph)
    adj = nx.adjacency_matrix(G)
    return adj, features, G


######### code test ########
# adj, features,G = Graph_load()
# print(adj)
# print(G.number_of_nodes(), G.number_of_edges())

# _,_,G = Graph_load(dataset='citeseer')
# G = max(nx.connected_component_subgraphs(G), key=len)
# G = nx.convert_node_labels_to_integers(G)
#
# count = 0
# max_node = 0
# for i in range(G.number_of_nodes()):
#     G_ego = nx.ego_graph(G, i, radius=3)
#     # draw_graph(G_ego,prefix='test'+str(i))
#     m = G_ego.number_of_nodes()
#     if m>max_node:
#         max_node = m
#     if m>=50:
#         print(i, G_ego.number_of_nodes(), G_ego.number_of_edges())
#         count += 1
# print('count', count)
# print('max_node', max_node) 
Example #15
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def local_straightness_centrality(
    graph, radius=5, name="straightness", distance=None, weight="mm_len"
):
    """
    Calculates local straightness for each node based on the defined distance.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute.

    .. math::
        C_{S}(i)=\\frac{1}{n-1} \\sum_{j \\in V, j \\neq i} \\frac{d_{i j}^{E u}}{d_{i j}}

    where :math:`\\mathrm{d}^{\\mathrm{E} \\mathrm{u}}_{\\mathrm{ij}}` is the Euclidean distance
    between nodes `i` and `j` along a straight line.


    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n during ego_graph generation.
    weight : str, optional
      Use the specified edge attribute as the edge distance in shortest
      path calculations in closeness centrality algorithm

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


    Examples
    --------
    >>> network_graph = mm.local_straightness_centrality(network_graph, radius=400, distance='edge_length')

    """
    warnings.warn(
        "local_straightness_centrality() is deprecated and will be removed in momepy 0.4.0. "
        "Use straightness_centrality() instead.",
        FutureWarning,
    )

    return straightness_centrality(
        graph=graph, radius=radius, name=name, distance=distance, weight=weight
    ) 
Example #16
Source File: clique.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def node_clique_number(G,nodes=None,cliques=None):
    """ Returns the size of the largest maximal clique containing
    each given node.

    Returns a single or list depending on input nodes.
    Optional list of cliques can be input if already computed.
    """
    if cliques is None:
        if nodes is not None:
            # Use ego_graph to decrease size of graph
            if isinstance(nodes,list):
                d={}
                for n in nodes:
                    H=networkx.ego_graph(G,n)
                    d[n]=max( (len(c) for c in find_cliques(H)) )
            else:
                H=networkx.ego_graph(G,nodes)
                d=max( (len(c) for c in find_cliques(H)) )
            return d
        # nodes is None--find all cliques
        cliques=list(find_cliques(G))

    if nodes is None:
        nodes=G.nodes()   # none, get entire graph

    if not isinstance(nodes, list):   # check for a list
        v=nodes
        # assume it is a single value
        d=max([len(c) for c in cliques if v in c])
    else:
        d={}
        for v in nodes:
            d[v]=max([len(c) for c in cliques if v in c])
    return d

    # if nodes is None:                 # none, use entire graph
    #     nodes=G.nodes()
    # elif  not isinstance(nodes, list):    # check for a list
    #     nodes=[nodes]             # assume it is a single value

    # if cliques is None:
    #     cliques=list(find_cliques(G))
    # d={}
    # for v in nodes:
    #     d[v]=max([len(c) for c in cliques if v in c])

    # if nodes in G:
    #     return d[v] #return single value
    # return d 
Example #17
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def gamma(graph, radius=5, name="gamma", distance=None):
    """
    Calculates connectivity gamma index for subgraph around each node if radius is set, or for
    whole graph, if ``radius=None``.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute.

    .. math::
        \\alpha=\\frac{e}{3(v-2)}

    where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.

    Adapted from :cite:`dibble2017`.

    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n.

    Returns
    -------
    Graph
        networkx.Graph if radius is set
    float
        gamma index for graph if ``radius=None``

    Examples
    --------
    >>> network_graph = mm.gamma(network_graph, radius=3)

    """
    netx = graph.copy()

    if radius:
        for n in tqdm(netx, total=len(netx)):
            sub = nx.ego_graph(
                netx, n, radius=radius, distance=distance
            )  # define subgraph of steps=radius
            netx.nodes[n][name] = _gamma(sub)

        return netx

    return _gamma(netx) 
Example #18
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def edge_node_ratio(graph, radius=5, name="edge_node_ratio", distance=None):
    """
    Calculates edge / node ratio for subgraph around each node if radius is set, or for
    whole graph, if ``radius=None``.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute.

    .. math::
        \\alpha=e/v

    where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.

    Adapted from :cite:`dibble2017`.

    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n.

    Returns
    -------
    Graph
        networkx.Graph if radius is set
    float
        edge / node ratio for graph if ``radius=None``

    Examples
    --------
    >>> network_graph = mm.edge_node_ratio(network_graph, radius=3)
    """
    netx = graph.copy()

    if radius:
        for n in tqdm(netx, total=len(netx)):
            sub = nx.ego_graph(
                netx, n, radius=radius, distance=distance
            )  # define subgraph of steps=radius
            netx.nodes[n][name] = _edge_node_ratio(
                sub
            )  # save value calulated for subgraph to node

        return netx

    return _edge_node_ratio(netx) 
Example #19
Source File: clique.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def node_clique_number(G, nodes=None, cliques=None):
    """ Returns the size of the largest maximal clique containing
    each given node.

    Returns a single or list depending on input nodes.
    Optional list of cliques can be input if already computed.
    """
    if cliques is None:
        if nodes is not None:
            # Use ego_graph to decrease size of graph
            if isinstance(nodes, list):
                d = {}
                for n in nodes:
                    H = nx.ego_graph(G, n)
                    d[n] = max((len(c) for c in find_cliques(H)))
            else:
                H = nx.ego_graph(G, nodes)
                d = max((len(c) for c in find_cliques(H)))
            return d
        # nodes is None--find all cliques
        cliques = list(find_cliques(G))

    if nodes is None:
        nodes = list(G.nodes())   # none, get entire graph

    if not isinstance(nodes, list):   # check for a list
        v = nodes
        # assume it is a single value
        d = max([len(c) for c in cliques if v in c])
    else:
        d = {}
        for v in nodes:
            d[v] = max([len(c) for c in cliques if v in c])
    return d

    # if nodes is None:                 # none, use entire graph
    #     nodes=G.nodes()
    # elif  not isinstance(nodes, list):    # check for a list
    #     nodes=[nodes]             # assume it is a single value

    # if cliques is None:
    #     cliques=list(find_cliques(G))
    # d={}
    # for v in nodes:
    #     d[v]=max([len(c) for c in cliques if v in c])

    # if nodes in G:
    #     return d[v] #return single value
    # return d 
Example #20
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def cyclomatic(graph, radius=5, name="cyclomatic", distance=None):
    """
    Calculates cyclomatic complexity for subgraph around each node if radius is set, or for
    whole graph, if ``radius=None``.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute.

    .. math::
        \\alpha=e-v+1

    where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.

    Adapted from :cite:`bourdic2012`.

    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n.

    Returns
    -------
    Graph
        networkx.Graph if radius is set
    float
        cyclomatic complexity for graph if ``radius=None``

    Examples
    --------
    >>> network_graph = mm.cyclomatic(network_graph, radius=3)
    """
    netx = graph.copy()

    if radius:
        for n in tqdm(netx, total=len(netx)):
            sub = nx.ego_graph(
                netx, n, radius=radius, distance=distance
            )  # define subgraph of steps=radius
            netx.nodes[n][name] = _cyclomatic(
                sub
            )  # save value calulated for subgraph to node

        return netx

    return _cyclomatic(netx) 
Example #21
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def mean_node_degree(graph, radius=5, name="mean_nd", degree="degree", distance=None):
    """
    Calculates mean node degree for subgraph around each node if radius is set, or for
    whole graph, if ``radius=None``.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute.


    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        radius defining the extent of subgraph
    name : str, optional
        calculated attribute name
    degree : str
        name of attribute of node degree (:py:func:`momepy.node_degree`)
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n.

    Returns
    -------
    Graph
        networkx.Graph if radius is set
    float
        mean node degree for graph if ``radius=None``

    Examples
    --------
    >>> network_graph = mm.mean_node_degree(network_graph, radius=3)
    """
    netx = graph.copy()

    if radius:
        for n in tqdm(netx, total=len(netx)):
            sub = nx.ego_graph(
                netx, n, radius=radius, distance=distance
            )  # define subgraph of steps=radius
            netx.nodes[n][name] = _mean_node_degree(sub, degree=degree)

        return netx

    return _mean_node_degree(netx, degree=degree) 
Example #22
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def meshedness(graph, radius=5, name="meshedness", distance=None):
    """
    Calculates meshedness for subgraph around each node if radius is set, or for
    whole graph, if ``radius=None``.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in distance
    attribute.

    .. math::
        \\alpha=\\frac{e-v+1}{2 v-5}

    where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.

    Adapted from :cite:`feliciotti2018`.


    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int, optional
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n.

    Returns
    -------
    Graph
        networkx.Graph if radius is set
    float
        meshedness for graph if ``radius=None``

    Examples
    --------
    >>> network_graph = mm.meshedness(network_graph, radius=800, distance='edge_length')
    """
    netx = graph.copy()

    if radius:
        for n in tqdm(netx, total=len(netx)):
            sub = nx.ego_graph(
                netx, n, radius=radius, distance=distance
            )  # define subgraph of steps=radius
            netx.nodes[n][name] = _meshedness(
                sub
            )  # save value calulated for subgraph to node

        return netx

    return _meshedness(netx) 
Example #23
Source File: clique.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def node_clique_number(G, nodes=None, cliques=None):
    """ Returns the size of the largest maximal clique containing
    each given node.

    Returns a single or list depending on input nodes.
    Optional list of cliques can be input if already computed.
    """
    if cliques is None:
        if nodes is not None:
            # Use ego_graph to decrease size of graph
            if isinstance(nodes, list):
                d = {}
                for n in nodes:
                    H = networkx.ego_graph(G, n)
                    d[n] = max((len(c) for c in find_cliques(H)))
            else:
                H = networkx.ego_graph(G, nodes)
                d = max((len(c) for c in find_cliques(H)))
            return d
        # nodes is None--find all cliques
        cliques = list(find_cliques(G))

    if nodes is None:
        nodes = list(G.nodes())   # none, get entire graph

    if not isinstance(nodes, list):   # check for a list
        v = nodes
        # assume it is a single value
        d = max([len(c) for c in cliques if v in c])
    else:
        d = {}
        for v in nodes:
            d[v] = max([len(c) for c in cliques if v in c])
    return d

    # if nodes is None:                 # none, use entire graph
    #     nodes=G.nodes()
    # elif  not isinstance(nodes, list):    # check for a list
    #     nodes=[nodes]             # assume it is a single value

    # if cliques is None:
    #     cliques=list(find_cliques(G))
    # d={}
    # for v in nodes:
    #     d[v]=max([len(c) for c in cliques if v in c])

    # if nodes in G:
    #     return d[v] #return single value
    # return d 
Example #24
Source File: data.py    From graph-generation with MIT License 4 votes vote down vote up
def Graph_load(dataset = 'cora'):
    '''
    Load a single graph dataset
    :param dataset: dataset name
    :return:
    '''
    names = ['x', 'tx', 'allx', 'graph']
    objects = []
    for i in range(len(names)):
        load = pkl.load(open("dataset/ind.{}.{}".format(dataset, names[i]), 'rb'), encoding='latin1')
        # print('loaded')
        objects.append(load)
        # print(load)
    x, tx, allx, graph = tuple(objects)
    test_idx_reorder = parse_index_file("dataset/ind.{}.test.index".format(dataset))
    test_idx_range = np.sort(test_idx_reorder)

    if dataset == 'citeseer':
        # Fix citeseer dataset (there are some isolated nodes in the graph)
        # Find isolated nodes, add them as zero-vecs into the right position
        test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1)
        tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
        tx_extended[test_idx_range - min(test_idx_range), :] = tx
        tx = tx_extended

    features = sp.vstack((allx, tx)).tolil()
    features[test_idx_reorder, :] = features[test_idx_range, :]
    G = nx.from_dict_of_lists(graph)
    adj = nx.adjacency_matrix(G)
    return adj, features, G


######### code test ########
# adj, features,G = Graph_load()
# print(adj)
# print(G.number_of_nodes(), G.number_of_edges())

# _,_,G = Graph_load(dataset='citeseer')
# G = max(nx.connected_component_subgraphs(G), key=len)
# G = nx.convert_node_labels_to_integers(G)
#
# count = 0
# max_node = 0
# for i in range(G.number_of_nodes()):
#     G_ego = nx.ego_graph(G, i, radius=3)
#     # draw_graph(G_ego,prefix='test'+str(i))
#     m = G_ego.number_of_nodes()
#     if m>max_node:
#         max_node = m
#     if m>=50:
#         print(i, G_ego.number_of_nodes(), G_ego.number_of_edges())
#         count += 1
# print('count', count)
# print('max_node', max_node)