Python networkx.all_neighbors() Examples

The following are 13 code examples of networkx.all_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: ramsey.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def ramsey_R2(G):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return (set([]), set([]))

    node = next(G.nodes_iter())
    nbrs = nx.all_neighbors(G, node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs))
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs))

    c_1.add(node)
    i_2.add(node)
    return (max([c_1, c_2]), max([i_1, i_2])) 
Example #2
Source File: structuralholes.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def normalized_mutual_weight(G, u, v, norm=sum, weight=None):
    """Returns normalized mutual weight of the edges from `u` to `v`
    with respect to the mutual weights of the neighbors of `u` in `G`.

    `norm` specifies how the normalization factor is computed. It must
    be a function that takes a single argument and returns a number.
    The argument will be an iterable of mutual weights
    of pairs ``(u, w)``, where ``w`` ranges over each (in- and
    out-)neighbor of ``u``. Commons values for `normalization` are
    ``sum`` and ``max``.

    `weight` can be ``None`` or a string, if None, all edge weights
    are considered equal. Otherwise holds the name of the edge
    attribute used as weight.

    """
    scale = norm(mutual_weight(G, u, w, weight)
                 for w in set(nx.all_neighbors(G, u)))
    return 0 if scale == 0 else mutual_weight(G, u, v, weight) / scale 
Example #3
Source File: structuralholes.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def normalized_mutual_weight(G, u, v, norm=sum, weight=None):
    """Returns normalized mutual weight of the edges from `u` to `v`
    with respect to the mutual weights of the neighbors of `u` in `G`.

    `norm` specifies how the normalization factor is computed. It must
    be a function that takes a single argument and returns a number.
    The argument will be an iterable of mutual weights
    of pairs ``(u, w)``, where ``w`` ranges over each (in- and
    out-)neighbor of ``u``. Commons values for `normalization` are
    ``sum`` and ``max``.

    `weight` can be ``None`` or a string, if None, all edge weights
    are considered equal. Otherwise holds the name of the edge
    attribute used as weight.

    """
    scale = norm(mutual_weight(G, u, w, weight)
                 for w in set(nx.all_neighbors(G, u)))
    return 0 if scale == 0 else mutual_weight(G, u, v, weight) / scale 
Example #4
Source File: network_info.py    From lndmanage with MIT License 5 votes vote down vote up
def secondary_hops_added(self, node_pub_key):
        """
        Determines the number of secondary hops added if connected to the node.

        :param node_pub_key: str
        :return: int
        """
        potential_new_second_neighbors = set(
            nx.all_neighbors(self.node.network.graph, node_pub_key))
        current_close_neighbors = set(
            self.get_nodes_n_hops_away(self.node.pub_key, 2).keys())
        new_second_neighbors = potential_new_second_neighbors.difference(
            current_close_neighbors)
        return len(new_second_neighbors) 
Example #5
Source File: network_info.py    From lndmanage with MIT License 5 votes vote down vote up
def nodes_most_second_neighbors(self, node_pub_key, number_of_nodes=10):
        """
        Which node should be added in order to reach the most other nodes
        with two hops?

        :param node_pub_key: string
        :param number_of_nodes: int
        :return: list of results nodes, adding the most secondary neighbors
        """

        node_candidates = []

        # set of nodes currently two hops away
        current_close_neighbors = set(
            self.get_nodes_n_hops_away(node_pub_key, 2).keys())

        # loop through nodes in the network and check their direct neighbors
        for n in self.node.network.graph:
            potential_new_second_neighbors = set(
                nx.all_neighbors(self.node.network.graph, n))

            # subtract current_close_neighbors from
            # the potential new second neighbors
            new_second_neighbors = potential_new_second_neighbors.difference(
                current_close_neighbors)

            # add the node and its number of secondary neighbors to a list
            node_candidates.append([n, len(new_second_neighbors)])

        nodes_sorted = sorted(
            node_candidates, key=lambda x: x[1], reverse=True)

        return nodes_sorted[:number_of_nodes] 
Example #6
Source File: create_citenet.py    From aca with MIT License 5 votes vote down vote up
def find_neighbors(cite_graph):

    print ("find neighbors ....")
    indx_neighbors = {}
    for node in cite_graph.nodes():
        indx_neighbors.setdefault(node,[]).extend(list(nx.all_neighbors(cite_graph,node)))
    with codecs.open("./raw_data/indx_neighbors.json","w","utf-8") as fid:
        json.dump(indx_neighbors,fid) 
Example #7
Source File: ramsey.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ramsey_R2(G):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return set(), set()

    node = arbitrary_element(G)
    nbrs = nx.all_neighbors(G, node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())

    c_1.add(node)
    i_2.add(node)
    # Choose the larger of the two cliques and the larger of the two
    # independent sets, according to cardinality.
    return max(c_1, c_2, key=len), max(i_1, i_2, key=len) 
Example #8
Source File: ramsey.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def ramsey_R2(G):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return set(), set()

    node = arbitrary_element(G)
    nbrs = nx.all_neighbors(G, node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())

    c_1.add(node)
    i_2.add(node)
    # Choose the larger of the two cliques and the larger of the two
    # independent sets, according to cardinality.
    return max(c_1, c_2, key=len), max(i_1, i_2, key=len) 
Example #9
Source File: graphity.py    From r2graphity with MIT License 4 votes vote down vote up
def functionalityScan(graphity, pattern):
	
	# search is performed by defining "anchor" node, where initial pattern is found
	# search then moved from there 1 level up to search surrounding nodes (number of levels could be increased)
	# pattern lists for now are kept rather small
	# TODO determine distance between found patterns to see which functionalities lie close to each other
	patternNum = len(pattern)
	anchorList = []
	
	allCalls = nx.get_node_attributes(graphity, 'calls')
	
	for function in allCalls:
		for call in allCalls[function]:
			
			api = call[1]
			anchorpat = pattern[0]
			
			if anchorpat in api: 
				if not filter(lambda daAnchor: daAnchor['address'] == function, anchorList):
					
					# maintain a dict of patterns per anchor to keep track of found patterns
					patternCheck = {}
					for item in pattern:
						patternCheck[item] = False
					patternCheck[anchorpat] = function
					
					anchorList.append({'address':function, 'patterns':patternCheck})

	# anchor nodes found and more than one pattern searched for							
	if patternNum > 1 and len(anchorList) > 0:
		for anchor in anchorList:
		
			scanNodeForApi(anchor, anchor['address'], patternNum)
			if False in anchor['patterns'].values():
			
				anchorNeighbors = nx.all_neighbors(graphity, anchor['address'])
				for neighbor in anchorNeighbors:
					scanNodeForApi(anchor, neighbor, patternNum)
			
	return anchorList
				

# Search for a specific pattern within a node, orient by anchor pattern 
Example #10
Source File: structuralholes.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def constraint(G, nodes=None, weight=None):
    r"""Returns the constraint on all nodes in the graph ``G``.

    The *constraint* is a measure of the extent to which a node *v* is
    invested in those nodes that are themselves invested in the
    neighbors of *v*. Formally, the *constraint on v*, denoted `c(v)`,
    is defined by

    .. math::

       c(v) = \sum_{w \in N(v) \setminus \{v\}} \ell(v, w)

    where `N(v)` is the subset of the neighbors of `v` that are either
    predecessors or successors of `v` and `\ell(v, w)` is the local
    constraint on `v` with respect to `w` [1]_. For the definition of local
    constraint, see :func:`local_constraint`.

    Parameters
    ----------
    G : NetworkX graph
        The graph containing ``v``. This can be either directed or undirected.

    nodes : container, optional
        Container of nodes in the graph ``G`` to compute the constraint. If
        None, the constraint of every node is computed.

    weight : None or string, optional
      If None, all edge weights are considered equal.
      Otherwise holds the name of the edge attribute used as weight.

    Returns
    -------
    dict
        Dictionary with nodes as keys and the constraint on the node as values.

    See also
    --------
    local_constraint

    References
    ----------
    .. [1] Burt, Ronald S.
           "Structural holes and good ideas".
           American Journal of Sociology (110): 349–399.

    """
    if nodes is None:
        nodes = G
    constraint = {}
    for v in nodes:
        # Constraint is not defined for isolated nodes
        if len(G[v]) == 0:
            constraint[v] = float('nan')
            continue
        constraint[v] = sum(local_constraint(G, v, n, weight)
                            for n in set(nx.all_neighbors(G, v)))
    return constraint 
Example #11
Source File: structuralholes.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def local_constraint(G, u, v, weight=None):
    r"""Returns the local constraint on the node ``u`` with respect to
    the node ``v`` in the graph ``G``.

    Formally, the *local constraint on u with respect to v*, denoted
    $\ell(v)$, is defined by

    .. math::

       \ell(u, v) = \left(p_{uv} + \sum_{w \in N(v)} p_{uw} p{wv}\right)^2,

    where $N(v)$ is the set of neighbors of $v$ and $p_{uv}$ is the
    normalized mutual weight of the (directed or undirected) edges
    joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. The *mutual
    weight* of $u$ and $v$ is the sum of the weights of edges joining
    them (edge weights are assumed to be one if the graph is
    unweighted).

    Parameters
    ----------
    G : NetworkX graph
        The graph containing ``u`` and ``v``. This can be either
        directed or undirected.

    u : node
        A node in the graph ``G``.

    v : node
        A node in the graph ``G``.

    weight : None or string, optional
      If None, all edge weights are considered equal.
      Otherwise holds the name of the edge attribute used as weight.

    Returns
    -------
    float
        The constraint of the node ``v`` in the graph ``G``.

    See also
    --------
    constraint

    References
    ----------
    .. [1] Burt, Ronald S.
           "Structural holes and good ideas".
           American Journal of Sociology (110): 349–399.

    """
    nmw = normalized_mutual_weight
    direct = nmw(G, u, v, weight=weight)
    indirect = sum(nmw(G, u, w, weight=weight) * nmw(G, w, v, weight=weight)
                   for w in set(nx.all_neighbors(G, u)))
    return (direct + indirect) ** 2 
Example #12
Source File: structuralholes.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def constraint(G, nodes=None, weight=None):
    r"""Returns the constraint on all nodes in the graph ``G``.

    The *constraint* is a measure of the extent to which a node *v* is
    invested in those nodes that are themselves invested in the
    neighbors of *v*. Formally, the *constraint on v*, denoted `c(v)`,
    is defined by

    .. math::

       c(v) = \sum_{w \in N(v) \setminus \{v\}} \ell(v, w)

    where `N(v)` is the subset of the neighbors of `v` that are either
    predecessors or successors of `v` and `\ell(v, w)` is the local
    constraint on `v` with respect to `w` [1]_. For the definition of local
    constraint, see :func:`local_constraint`.

    Parameters
    ----------
    G : NetworkX graph
        The graph containing ``v``. This can be either directed or undirected.

    nodes : container, optional
        Container of nodes in the graph ``G`` to compute the constraint. If
        None, the constraint of every node is computed.

    weight : None or string, optional
      If None, all edge weights are considered equal.
      Otherwise holds the name of the edge attribute used as weight.

    Returns
    -------
    dict
        Dictionary with nodes as keys and the constraint on the node as values.

    See also
    --------
    local_constraint

    References
    ----------
    .. [1] Burt, Ronald S.
           "Structural holes and good ideas".
           American Journal of Sociology (110): 349–399.

    """
    if nodes is None:
        nodes = G
    constraint = {}
    for v in nodes:
        # Constraint is not defined for isolated nodes
        if len(G[v]) == 0:
            constraint[v] = float('nan')
            continue
        constraint[v] = sum(local_constraint(G, v, n, weight)
                            for n in set(nx.all_neighbors(G, v)))
    return constraint 
Example #13
Source File: structuralholes.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def local_constraint(G, u, v, weight=None):
    r"""Returns the local constraint on the node ``u`` with respect to
    the node ``v`` in the graph ``G``.

    Formally, the *local constraint on u with respect to v*, denoted
    $\ell(v)$, is defined by

    .. math::

       \ell(u, v) = \left(p_{uv} + \sum_{w \in N(v)} p_{uw} p{wv}\right)^2,

    where $N(v)$ is the set of neighbors of $v$ and $p_{uv}$ is the
    normalized mutual weight of the (directed or undirected) edges
    joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. The *mutual
    weight* of $u$ and $v$ is the sum of the weights of edges joining
    them (edge weights are assumed to be one if the graph is
    unweighted).

    Parameters
    ----------
    G : NetworkX graph
        The graph containing ``u`` and ``v``. This can be either
        directed or undirected.

    u : node
        A node in the graph ``G``.

    v : node
        A node in the graph ``G``.

    weight : None or string, optional
      If None, all edge weights are considered equal.
      Otherwise holds the name of the edge attribute used as weight.

    Returns
    -------
    float
        The constraint of the node ``v`` in the graph ``G``.

    See also
    --------
    constraint

    References
    ----------
    .. [1] Burt, Ronald S.
           "Structural holes and good ideas".
           American Journal of Sociology (110): 349–399.

    """
    nmw = normalized_mutual_weight
    direct = nmw(G, u, v, weight=weight)
    indirect = sum(nmw(G, u, w, weight=weight) * nmw(G, w, v, weight=weight)
                   for w in set(nx.all_neighbors(G, u)))
    return (direct + indirect) ** 2