Python networkx.single_source_shortest_path_length() Examples

The following are 27 code examples of networkx.single_source_shortest_path_length(). 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_threshold.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_shortest_path(self):
        deg = [3, 2, 2, 1]
        G = nx.generators.havel_hakimi_graph(deg)
        cs1 = nxt.creation_sequence(deg, with_labels=True)
        for n, m in [(3, 0), (0, 3), (0, 2), (0, 1), (1, 3),
                     (3, 1), (1, 2), (2, 3)]:
            assert_equal(nxt.shortest_path(cs1, n, m),
                         nx.shortest_path(G, n, m))

        spl = nxt.shortest_path_length(cs1, 3)
        spl2 = nxt.shortest_path_length([t for v, t in cs1], 2)
        assert_equal(spl, spl2)

        spld = {}
        for j, pl in enumerate(spl):
            n = cs1[j][0]
            spld[n] = pl
        assert_equal(spld, nx.single_source_shortest_path_length(G, 3))

        assert_equal(nxt.shortest_path(['d', 'd', 'd', 'i', 'd', 'd'], 1, 2), [1, 2])
        assert_equal(nxt.shortest_path([3, 1, 2], 1, 2), [1, 2])
        assert_raises(TypeError, nxt.shortest_path, [3., 1., 2.], 1, 2)
        assert_raises(ValueError, nxt.shortest_path, [3, 1, 2], 'a', 2)
        assert_raises(ValueError, nxt.shortest_path, [3, 1, 2], 1, 'b')
        assert_equal(nxt.shortest_path([3, 1, 2], 1, 1), [1]) 
Example #2
Source File: test_threshold.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_shortest_path(self):
        deg=[3,2,2,1]
        G=nx.generators.havel_hakimi_graph(deg)
        cs1=nxt.creation_sequence(deg, with_labels=True)
        for n, m in [(3, 0), (0, 3), (0, 2), (0, 1), (1, 3),
                     (3, 1), (1, 2), (2, 3)]:
            assert_equal(nxt.shortest_path(cs1,n,m),
                         nx.shortest_path(G, n, m))

        spl=nxt.shortest_path_length(cs1,3)
        spl2=nxt.shortest_path_length([ t for v,t in cs1],2)
        assert_equal(spl, spl2)

        spld={}
        for j,pl in enumerate(spl):
            n=cs1[j][0]
            spld[n]=pl
        assert_equal(spld, nx.single_source_shortest_path_length(G, 3)) 
Example #3
Source File: test_threshold.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_shortest_path(self):
        deg = [3, 2, 2, 1]
        G = nx.generators.havel_hakimi_graph(deg)
        cs1 = nxt.creation_sequence(deg, with_labels=True)
        for n, m in [(3, 0), (0, 3), (0, 2), (0, 1), (1, 3),
                     (3, 1), (1, 2), (2, 3)]:
            assert_equal(nxt.shortest_path(cs1, n, m),
                         nx.shortest_path(G, n, m))

        spl = nxt.shortest_path_length(cs1, 3)
        spl2 = nxt.shortest_path_length([t for v, t in cs1], 2)
        assert_equal(spl, spl2)

        spld = {}
        for j, pl in enumerate(spl):
            n = cs1[j][0]
            spld[n] = pl
        assert_equal(spld, nx.single_source_shortest_path_length(G, 3))

        assert_equal(nxt.shortest_path(['d', 'd', 'd', 'i', 'd', 'd'], 1, 2), [1, 2])
        assert_equal(nxt.shortest_path([3, 1, 2], 1, 2), [1, 2])
        assert_raises(TypeError, nxt.shortest_path, [3., 1., 2.], 1, 2)
        assert_raises(ValueError, nxt.shortest_path, [3, 1, 2], 'a', 2)
        assert_raises(ValueError, nxt.shortest_path, [3, 1, 2], 1, 'b')
        assert_equal(nxt.shortest_path([3, 1, 2], 1, 1), [1]) 
Example #4
Source File: test_unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        assert_equal(nx.single_source_shortest_path_length(self.cycle,0),
                     {0:0,1:1,2:2,3:3,4:3,5:2,6:1}) 
Example #5
Source File: test_unweighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        pl = nx.single_source_shortest_path_length
        lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
        assert_equal(dict(pl(self.cycle,0)), lengths)
        lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
        assert_equal(dict(pl(self.directed_cycle,0)), lengths) 
Example #6
Source File: test_unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        pl = nx.single_source_shortest_path_length
        lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
        assert_equal(dict(pl(self.cycle, 0)), lengths)
        lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
        assert_equal(dict(pl(self.directed_cycle, 0)), lengths) 
Example #7
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        ans = dict(nx.shortest_path_length(self.cycle, 0))
        assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans,
                     dict(nx.single_source_shortest_path_length(self.cycle,
                                                                0)))
        ans = dict(nx.shortest_path_length(self.grid, 1))
        assert_equal(ans[16], 6)
        # now with weights
        ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight'))
        assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
            self.cycle, 0)))
        ans = dict(nx.shortest_path_length(self.grid, 1, weight='weight'))
        assert_equal(ans[16], 6)
        # weights and method specified
        ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                           method='dijkstra'))
        assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
            self.cycle, 0)))
        ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                           method='bellman-ford'))
        assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.single_source_bellman_ford_path_length(
            self.cycle, 0))) 
Example #8
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        l = dict(nx.shortest_path_length(self.cycle,0))
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l, dict(nx.single_source_shortest_path_length(self.cycle,0)))
        l = dict(nx.shortest_path_length(self.grid,1))
        assert_equal(l[16],6)
        # now with weights
        l = dict(nx.shortest_path_length(self.cycle, 0, weight='weight'))
        assert_equal(l, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(l, dict(nx.single_source_dijkstra_path_length(
            self.cycle, 0)))
        l = dict(nx.shortest_path_length(self.grid, 1, weight='weight'))
        assert_equal(l[16], 6) 
Example #9
Source File: utils.py    From P-GNN with MIT License 5 votes vote down vote up
def single_source_shortest_path_length_range(graph, node_range, cutoff):
    dists_dict = {}
    for node in node_range:
        dists_dict[node] = nx.single_source_shortest_path_length(graph, node, cutoff)
    return dists_dict 
Example #10
Source File: unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def all_pairs_shortest_path_length(G, cutoff=None):
    """Computes the shortest path lengths between all nodes in ``G``.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        ``cutoff`` are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary of shortest path lengths keyed by source and target.

    Notes
    -----
    The dictionary returned only has keys for reachable node pairs.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = nx.all_pairs_shortest_path_length(G)
    >>> print(length[1][4])
    3
    >>> length[1]
    {0: 1, 1: 0, 2: 1, 3: 2, 4: 3}

    """
    length = single_source_shortest_path_length
    # TODO This can be trivially parallelized.
    return {n: length(G, n, cutoff=cutoff) for n in G} 
Example #11
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_single_source_shortest_path_length(self):
        l=nx.shortest_path_length(self.cycle,0)
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l,nx.single_source_shortest_path_length(self.cycle,0))
        l=nx.shortest_path_length(self.grid,1)
        assert_equal(l[16],6)
        # now with weights
        l=nx.shortest_path_length(self.cycle,0,weight='weight')
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l,nx.single_source_dijkstra_path_length(self.cycle,0))
        l=nx.shortest_path_length(self.grid,1,weight='weight')
        assert_equal(l[16],6) 
Example #12
Source File: vitality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def weiner_index(G, weight=None):
    # compute sum of distances between all node pairs
    # (with optional weights)
    weiner=0.0
    if weight is None:
        for n in G:
            path_length=nx.single_source_shortest_path_length(G,n)
            weiner+=sum(path_length.values())
    else:
        for n in G:
            path_length=nx.single_source_dijkstra_path_length(G,
                    n,weight=weight)
            weiner+=sum(path_length.values())
    return weiner 
Example #13
Source File: network_info.py    From lndmanage with MIT License 5 votes vote down vote up
def get_nodes_n_hops_away(self, node_pub_key, n):
        """
        Returns all nodes, which are n hops away from a given
        node_pub_key node.

        :param node_pub_key: string
        :param n: int
        :return: dict with nodes and distance as value
        """

        return nx.single_source_shortest_path_length(
            self.node.network.graph, node_pub_key, cutoff=n) 
Example #14
Source File: bindiff.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _distances_from_function_exit(function):
        """
        :param function:    A normalized Function object.
        :returns:           A dictionary of basic block addresses and their distance to the exit of the function.
        """
        reverse_graph = function.graph.reverse()
        # we aren't guaranteed to have an exit from the function so explicitly add the node
        reverse_graph.add_node("start")
        found_exits = False
        for n in function.graph.nodes():
            if len(list(function.graph.successors(n))) == 0:
                reverse_graph.add_edge("start", n)
                found_exits = True

        # if there were no exits (a function with a while 1) let's consider the block with the highest address to
        # be the exit. This isn't the most scientific way, but since this case is pretty rare it should be okay
        if not found_exits:
            last = max(function.graph.nodes(), key=lambda x:x.addr)
            reverse_graph.add_edge("start", last)

        dists = networkx.single_source_shortest_path_length(reverse_graph, "start")

        # remove temp node
        del dists["start"]

        # correct for the added node
        for n in dists:
            dists[n] -= 1

        return dists 
Example #15
Source File: bindiff.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _distances_from_function_start(function):
        """
        :param function:    A normalized Function object.
        :returns:           A dictionary of basic block addresses and their distance to the start of the function.
        """
        return networkx.single_source_shortest_path_length(function.graph,
                                                           function.startpoint) 
Example #16
Source File: distance_measures.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def eccentricity(G, v=None, sp=None):
    """Return the eccentricity of nodes in G.

    The eccentricity of a node v is the maximum distance from v to
    all other nodes in G.

    Parameters
    ----------
    G : NetworkX graph
       A graph

    v : node, optional
       Return value of specified node

    sp : dict of dicts, optional
       All pairs shortest path lengths as a dictionary of dictionaries

    Returns
    -------
    ecc : dictionary
       A dictionary of eccentricity values keyed by node.
    """
#    if v is None:                # none, use entire graph
#        nodes=G.nodes()
#    elif v in G:               # is v a single node
#        nodes=[v]
#    else:                      # assume v is a container of nodes
#        nodes=v
    order = G.order()

    e = {}
    for n in G.nbunch_iter(v):
        if sp is None:
            length = networkx.single_source_shortest_path_length(G, n)
            L = len(length)
        else:
            try:
                length = sp[n]
                L = len(length)
            except TypeError:
                raise networkx.NetworkXError('Format of "sp" is invalid.')
        if L != order:
            if G.is_directed():
                msg = ('Found infinite path length because the digraph is not'
                       ' strongly connected')
            else:
                msg = ('Found infinite path length because the graph is not'
                       ' connected')
            raise networkx.NetworkXError(msg)

        e[n] = max(length.values())

    if v in G:
        return e[v]  # return single value
    else:
        return e 
Example #17
Source File: ego.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
    """Returns induced subgraph of neighbors centered at node n within
    a given radius.

    Parameters
    ----------
    G : graph
      A NetworkX Graph or DiGraph

    n : node
      A single node

    radius : number, optional
      Include all neighbors of distance<=radius from n.

    center : bool, optional
      If False, do not include center node in graph

    undirected : bool, optional
      If True use both in- and out-neighbors of directed graphs.

    distance : key, 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.

    Notes
    -----
    For directed graphs D this produces the "out" neighborhood
    or successors.  If you want the neighborhood of predecessors
    first reverse the graph with D.reverse().  If you want both
    directions use the keyword argument undirected=True.

    Node, edge, and graph attributes are copied to the returned subgraph.
    """
    if undirected:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G.to_undirected(),
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G.to_undirected(),
                                                            n, cutoff=radius))
    else:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G,
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))

    H = G.subgraph(sp).copy()
    if not center:
        H.remove_node(n)
    return H 
Example #18
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def single_source_shortest_path_length(G, source, cutoff=None):
    """Compute the shortest path lengths from source to all reachable nodes.

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

    source : node
       Starting node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dict
        Dict keyed by node to shortest path length to source.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = nx.single_source_shortest_path_length(G, 0)
    >>> length[4]
    4
    >>> for node in length:
    ...     print('{}: {}'.format(node, length[node]))
    0: 0
    1: 1
    2: 2
    3: 3
    4: 4

    See Also
    --------
    shortest_path_length
    """
    if source not in G:
        raise nx.NodeNotFound('Source {} is not in G'.format(source))
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {source: 1}
    return dict(_single_shortest_path_length(G.adj, nextlevel, cutoff)) 
Example #19
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def single_target_shortest_path_length(G, target, cutoff=None):
    """Compute the shortest path lengths to target from all reachable nodes.

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

    target : node
       Target node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : iterator
        (source, shortest path length) iterator

    Examples
    --------
    >>> G = nx.path_graph(5, create_using=nx.DiGraph())
    >>> length = dict(nx.single_target_shortest_path_length(G, 4))
    >>> length[0]
    4
    >>> for node in range(5):
    ...     print('{}: {}'.format(node, length[node]))
    0: 4
    1: 3
    2: 2
    3: 1
    4: 0

    See Also
    --------
    single_source_shortest_path_length, shortest_path_length
    """
    if target not in G:
        raise nx.NodeNotFound('Target {} is not in G'.format(source))

    if cutoff is None:
        cutoff = float('inf')
    # handle either directed or undirected
    adj = G.pred if G.is_directed() else G.adj
    nextlevel = {target: 1}
    return _single_shortest_path_length(adj, nextlevel, cutoff) 
Example #20
Source File: networkx.py    From Verum with Apache License 2.0 4 votes vote down vote up
def query(self, topic, max_depth=4, config=None, dont_follow=['enrichment', 'classification']):
        """
            :param topic: a  graph to return the context of.  At least one node ID in topic \
             must be in full graph g to return any context.
            :param max_depth: The maximum distance from the topic to search
            :param config: The titanDB configuration to use if not using the one configured with the plugin
            :param dont_follow: A list of attribute types to not follow
            :return: subgraph in networkx format
        """
        distances = dict()

        if config is None:
            config = self.context_graph

        # Conver topic from a graph into a set of nodes
        topic_nodes = set()
        for n, d in topic.nodes(data=True):
            topic_nodes.add("class={0}&key={1}&value={2}".format(d['class'], d['key'], d['value']))

        nodes = topic_nodes.copy()

        for t in topic:
            # get all nodes within max_depth distance from each topic and add them to the set
            new_distances = nx.single_source_shortest_path_length(self.context_graph.to_undirected(), t, cutoff=max_depth)
            nodes = nodes.union(set(new_distances.keys()))

            # Update shortest distances from topic to node
            for n in new_distances.keys():
                if n in distances:
                    if new_distances[n] < distances[n]:
                        distances[n] = new_distances[n]
                else:
                    distances[n] = new_distances[n]

        # remove dont_follow nodes:
        nodes_to_remove = set()
        for n in nodes:
            if self.context_graph.node[n]['key'] in dont_follow:
                nodes_to_remove.add(n)
        nodes = nodes.difference(nodes_to_remove)

        # Get the subgraph represented by the nodes:
        g = nx.MultiDiGraph(self.context_graph.subgraph(nodes))

        # Prune out non-relevant components by removing those that contain no topic nodes.
        #  This gets ride of nodes that were found by following dont_follow nodes
        for component in nx.connected_components(g.to_undirected()):
            if len(topic_nodes.intersection(set(component))) <= 0:  # if there's no overlap betweent the component and topic
                g.remove_nodes_from(component)  # remove the component

        # add the topic distances to the subgraph
        for n in g.nodes():
            g.node[n]['topic_distance'] = distances[n]

        return g 
Example #21
Source File: ego.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
    """Returns induced subgraph of neighbors centered at node n within
    a given radius.

    Parameters
    ----------
    G : graph
      A NetworkX Graph or DiGraph

    n : node
      A single node

    radius : number, optional
      Include all neighbors of distance<=radius from n.

    center : bool, optional
      If False, do not include center node in graph

    undirected : bool, optional
      If True use both in- and out-neighbors of directed graphs.

    distance : key, 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.

    Notes
    -----
    For directed graphs D this produces the "out" neighborhood
    or successors.  If you want the neighborhood of predecessors
    first reverse the graph with D.reverse().  If you want both
    directions use the keyword argument undirected=True.

    Node, edge, and graph attributes are copied to the returned subgraph.
    """
    if undirected:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G.to_undirected(),
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G.to_undirected(),
                                                            n, cutoff=radius))
    else:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G,
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))

    H = G.subgraph(sp).copy()
    if not center:
        H.remove_node(n)
    return H 
Example #22
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def single_target_shortest_path_length(G, target, cutoff=None):
    """Compute the shortest path lengths to target from all reachable nodes.

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

    target : node
       Target node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : iterator
        (source, shortest path length) iterator

    Examples
    --------
    >>> G = nx.path_graph(5, create_using=nx.DiGraph())
    >>> length = dict(nx.single_target_shortest_path_length(G, 4))
    >>> length[0]
    4
    >>> for node in range(5):
    ...     print('{}: {}'.format(node, length[node]))
    0: 4
    1: 3
    2: 2
    3: 1
    4: 0

    See Also
    --------
    single_source_shortest_path_length, shortest_path_length
    """
    if target not in G:
        raise nx.NodeNotFound('Target {} is not in G'.format(target))

    if cutoff is None:
        cutoff = float('inf')
    # handle either directed or undirected
    adj = G.pred if G.is_directed() else G.adj
    nextlevel = {target: 1}
    return _single_shortest_path_length(adj, nextlevel, cutoff) 
Example #23
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def single_source_shortest_path_length(G, source, cutoff=None):
    """Compute the shortest path lengths from source to all reachable nodes.

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

    source : node
       Starting node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dict
        Dict keyed by node to shortest path length to source.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = nx.single_source_shortest_path_length(G, 0)
    >>> length[4]
    4
    >>> for node in length:
    ...     print('{}: {}'.format(node, length[node]))
    0: 0
    1: 1
    2: 2
    3: 3
    4: 4

    See Also
    --------
    shortest_path_length
    """
    if source not in G:
        raise nx.NodeNotFound('Source {} is not in G'.format(source))
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {source: 1}
    return dict(_single_shortest_path_length(G.adj, nextlevel, cutoff)) 
Example #24
Source File: distance_measures.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def eccentricity(G, v=None, sp=None):
    """Returns the eccentricity of nodes in G.

    The eccentricity of a node v is the maximum distance from v to
    all other nodes in G.

    Parameters
    ----------
    G : NetworkX graph
       A graph

    v : node, optional
       Return value of specified node

    sp : dict of dicts, optional
       All pairs shortest path lengths as a dictionary of dictionaries

    Returns
    -------
    ecc : dictionary
       A dictionary of eccentricity values keyed by node.
    """
#    if v is None:                # none, use entire graph
#        nodes=G.nodes()
#    elif v in G:               # is v a single node
#        nodes=[v]
#    else:                      # assume v is a container of nodes
#        nodes=v
    order = G.order()

    e = {}
    for n in G.nbunch_iter(v):
        if sp is None:
            length = networkx.single_source_shortest_path_length(G, n)
            L = len(length)
        else:
            try:
                length = sp[n]
                L = len(length)
            except TypeError:
                raise networkx.NetworkXError('Format of "sp" is invalid.')
        if L != order:
            if G.is_directed():
                msg = ('Found infinite path length because the digraph is not'
                       ' strongly connected')
            else:
                msg = ('Found infinite path length because the graph is not'
                       ' connected')
            raise networkx.NetworkXError(msg)

        e[n] = max(length.values())

    if v in G:
        return e[v]  # return single value
    else:
        return e 
Example #25
Source File: ego.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def ego_graph(G,n,radius=1,center=True,undirected=False,distance=None):
    """Returns induced subgraph of neighbors centered at node n within
    a given radius.
    
    Parameters
    ----------
    G : graph
      A NetworkX Graph or DiGraph

    n : node 
      A single node 

    radius : number, optional
      Include all neighbors of distance<=radius from n.
      
    center : bool, optional
      If False, do not include center node in graph 

    undirected : bool, optional      
      If True use both in- and out-neighbors of directed graphs.

    distance : key, 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.

    Notes
    -----
    For directed graphs D this produces the "out" neighborhood
    or successors.  If you want the neighborhood of predecessors
    first reverse the graph with D.reverse().  If you want both
    directions use the keyword argument undirected=True.

    Node, edge, and graph attributes are copied to the returned subgraph.
    """
    if undirected:
        if distance is not None:
            sp,_=nx.single_source_dijkstra(G.to_undirected(),
                                           n,cutoff=radius,
                                           weight=distance)
        else:
            sp=nx.single_source_shortest_path_length(G.to_undirected(),
                                                     n,cutoff=radius)
    else:
        if distance is not None:
            sp,_=nx.single_source_dijkstra(G,
                                           n,cutoff=radius,
                                           weight=distance)
        else:
            sp=nx.single_source_shortest_path_length(G,n,cutoff=radius)

    H=G.subgraph(sp).copy()
    if not center:
        H.remove_node(n)
    return  H 
Example #26
Source File: generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def average_shortest_path_length(G, weight=None):
    r"""Return the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`,
    `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

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

    weight : None or string, optional (default = None)
       If None, every edge has weight/distance/cost 1.
       If a string, use this edge attribute as the edge weight.
       Any edge attribute not present defaults to 1.

    Raises
    ------
    NetworkXError:
       if the graph is not connected.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.average_shortest_path_length(G))
    2.0

    For disconnected graphs you can compute the average shortest path
    length for each component:
    >>> G=nx.Graph([(1,2),(3,4)])
    >>> for g in nx.connected_component_subgraphs(G):
    ...     print(nx.average_shortest_path_length(g))
    1.0
    1.0

    """
    if G.is_directed():
        if not nx.is_weakly_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    else:
        if not nx.is_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    avg=0.0
    if weight is None:
        for node in G:
            path_length=nx.single_source_shortest_path_length(G, node)
            avg += sum(path_length.values())
    else:
        for node in G:
            path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight)
            avg += sum(path_length.values())
    n=len(G)
    return avg/(n*(n-1)) 
Example #27
Source File: distance_measures.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def eccentricity(G, v=None, sp=None):
    """Return the eccentricity of nodes in G.

    The eccentricity of a node v is the maximum distance from v to
    all other nodes in G.

    Parameters
    ----------
    G : NetworkX graph
       A graph

    v : node, optional
       Return value of specified node       

    sp : dict of dicts, optional       
       All pairs shortest path lengths as a dictionary of dictionaries

    Returns
    -------
    ecc : dictionary
       A dictionary of eccentricity values keyed by node.
    """
#    nodes=
#    nodes=[]
#    if v is None:                # none, use entire graph 
#        nodes=G.nodes()
#    elif v in G:               # is v a single node
#        nodes=[v]
#    else:                      # assume v is a container of nodes
#        nodes=v
    order=G.order()

    e={}
    for n in G.nbunch_iter(v):
        if sp is None:
            length=networkx.single_source_shortest_path_length(G,n)
            L = len(length)
        else:
            try:
                length=sp[n]
                L = len(length)
            except TypeError:
                raise networkx.NetworkXError('Format of "sp" is invalid.')
        if L != order:
            msg = "Graph not connected: infinite path length"
            raise networkx.NetworkXError(msg)
            
        e[n]=max(length.values())

    if v in G:
        return e[v]  # return single value
    else:
        return e