Python networkx.NodeNotFound() Examples

The following are 30 code examples of networkx.NodeNotFound(). 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: selection_multipleDeploys.py    From YAFS with MIT License 6 votes vote down vote up
def compute_BEST_DES(self, node_src, alloc_DES, sim, DES_dst,message):
        try:

            bestLong = float('inf')
            minPath = []
            bestDES = []
            #print len(DES_dst)
            for dev in DES_dst:
                #print "DES :",dev
                node_dst = alloc_DES[dev]
                path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
                long = len(path)

                if  long < bestLong:
                    bestLong = long
                    minPath = path
                    bestDES = dev

            #print bestDES,minPath
            return minPath, bestDES

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
            # print "Simulation ends?"
            return [], None 
Example #2
Source File: selection_multipleDeploys.py    From YAFS with MIT License 6 votes vote down vote up
def compute_BEST_DES(self, node_src, alloc_DES, sim, DES_dst,message):
        try:

            bestLong = float('inf')
            minPath = []
            bestDES = []
            #print len(DES_dst)
            for dev in DES_dst:
                #print "DES :",dev
                node_dst = alloc_DES[dev]
                path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
                long = len(path)

                if  long < bestLong:
                    bestLong = long
                    minPath = path
                    bestDES = dev

            #print bestDES,minPath
            return minPath, bestDES

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
            # print "Simulation ends?"
            return [], None 
Example #3
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_shortest_path_length(self):
        assert_equal(nx.shortest_path_length(self.cycle, 0, 3), 3)
        assert_equal(nx.shortest_path_length(self.grid, 1, 12), 5)
        assert_equal(nx.shortest_path_length(self.directed_cycle, 0, 4), 4)
        # now with weights
        assert_equal(nx.shortest_path_length(self.cycle, 0, 3,
                                             weight='weight'),
                     3)
        assert_equal(nx.shortest_path_length(self.grid, 1, 12,
                                             weight='weight'),
                     5)
        assert_equal(nx.shortest_path_length(self.directed_cycle, 0, 4,
                                             weight='weight'),
                     4)
        # weights and method specified
        assert_equal(nx.shortest_path_length(self.cycle, 0, 3, weight='weight',
                                             method='dijkstra'),
                     3)
        assert_equal(nx.shortest_path_length(self.cycle, 0, 3, weight='weight',
                                             method='bellman-ford'),
                     3)
        # confirm bad method rejection
        assert_raises(ValueError,
                      nx.shortest_path_length,
                      self.cycle,
                      method='SPAM')
        # confirm absent source rejection
        assert_raises(nx.NodeNotFound, nx.shortest_path_length, self.cycle, 8) 
Example #4
Source File: test_lowest_common_ancestors.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_all_pairs_lowest_common_ancestor5(self):
        """Test that pairs not in the graph raises error."""
        assert_raises(nx.NodeNotFound, all_pairs_lca, self.DG, [(-1, -1)]) 
Example #5
Source File: test_lowest_common_ancestors.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_tree_all_pairs_lowest_common_ancestor11(self):
        """Test that None as a node in the graph raises an error."""
        G = nx.DiGraph([(None, 3)])
        assert_raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
        assert_raises(nx.NodeNotFound, list,
                      tree_all_pairs_lca(self.DG, pairs=G.edges())) 
Example #6
Source File: test_lowest_common_ancestors.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_tree_all_pairs_lowest_common_ancestor10(self):
        """Test that pairs not in the graph raises error."""
        lca = tree_all_pairs_lca(self.DG, 0, [(-1, -1)])
        assert_raises(nx.NodeNotFound, list, lca) 
Example #7
Source File: test_lowest_common_ancestors.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_tree_all_pairs_lowest_common_ancestor5(self):
        """Handles invalid input correctly."""
        empty_digraph = tree_all_pairs_lca(nx.DiGraph())
        assert_raises(nx.NetworkXPointlessConcept, list, empty_digraph)

        bad_pairs_digraph = tree_all_pairs_lca(self.DG, pairs=[(-1, -2)])
        assert_raises(nx.NodeNotFound, list, bad_pairs_digraph) 
Example #8
Source File: test_weighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_single_node_graph(self):
        G = nx.DiGraph()
        G.add_node(0)
        assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]})
        assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0})
        assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None]}, {0: 0}))
        assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
        assert_raises(nx.NodeNotFound, nx.bellman_ford_predecessor_and_distance, G, 1)
        assert_raises(nx.NodeNotFound, nx.goldberg_radzik, G, 1) 
Example #9
Source File: astar.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def astar_path_length(G, source, target, heuristic=None, weight='weight'):
    """Return the length of the shortest path between source and target using
    the A* ("A-star") algorithm.

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

    source : node
       Starting node for path

    target : node
       Ending node for path

    heuristic : function
       A function to evaluate the estimate of the distance
       from the a node to the target.  The function takes
       two nodes arguments and must return a number.

    Raises
    ------
    NetworkXNoPath
        If no path exists between source and target.

    See Also
    --------
    astar_path

    """
    if source not in G or target not in G:
        msg = 'Either source {} or target {} is not in G'
        raise nx.NodeNotFound(msg.format(source, target))

    path = astar_path(G, source, target, heuristic, weight)
    return sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:])) 
Example #10
Source File: test_lowest_common_ancestors.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_all_pairs_lowest_common_ancestor10(self):
        """Test that it bails on None as a node."""
        G = nx.DiGraph([(None, 3)])
        assert_raises(nx.NetworkXError, all_pairs_lca, G)
        assert_raises(nx.NodeNotFound, all_pairs_lca,
                      self.DG, pairs=G.edges()) 
Example #11
Source File: test_lowest_common_ancestors.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_all_pairs_lowest_common_ancestor5(self):
        """Test that pairs not in the graph raises error."""
        assert_raises(nx.NodeNotFound, all_pairs_lca, self.DG, [(-1, -1)]) 
Example #12
Source File: test_lowest_common_ancestors.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tree_all_pairs_lowest_common_ancestor11(self):
        """Test that None as a node in the graph raises an error."""
        G = nx.DiGraph([(None, 3)])
        assert_raises(nx.NetworkXError, list, tree_all_pairs_lca(G))
        assert_raises(nx.NodeNotFound, list,
                      tree_all_pairs_lca(self.DG, pairs=G.edges())) 
Example #13
Source File: test_lowest_common_ancestors.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tree_all_pairs_lowest_common_ancestor5(self):
        """Handles invalid input correctly."""
        empty_digraph = tree_all_pairs_lca(nx.DiGraph())
        assert_raises(nx.NetworkXPointlessConcept, list, empty_digraph)

        bad_pairs_digraph = tree_all_pairs_lca(self.DG, pairs=[(-1, -2)])
        assert_raises(nx.NodeNotFound, list, bad_pairs_digraph) 
Example #14
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_shortest_path(self):
        assert_equal(nx.shortest_path(self.cycle, 0, 3), [0, 1, 2, 3])
        assert_equal(nx.shortest_path(self.cycle, 0, 4), [0, 6, 5, 4])
        validate_grid_path(4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12))
        assert_equal(nx.shortest_path(self.directed_cycle, 0, 3), [0, 1, 2, 3])
        # now with weights
        assert_equal(nx.shortest_path(self.cycle, 0, 3, weight='weight'),
                     [0, 1, 2, 3])
        assert_equal(nx.shortest_path(self.cycle, 0, 4, weight='weight'),
                     [0, 6, 5, 4])
        validate_grid_path(4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12,
                                                         weight='weight'))
        assert_equal(nx.shortest_path(self.directed_cycle, 0, 3,
                                      weight='weight'),
                     [0, 1, 2, 3])
        # weights and method specified
        assert_equal(nx.shortest_path(self.directed_cycle, 0, 3,
                                      weight='weight', method='dijkstra'),
                     [0, 1, 2, 3])
        assert_equal(nx.shortest_path(self.directed_cycle, 0, 3,
                                      weight='weight', method='bellman-ford'),
                     [0, 1, 2, 3])
        # when Dijkstra's will probably (depending on precise implementation)
        # incorrectly return [0, 1, 3] instead
        assert_equal(nx.shortest_path(self.neg_weights, 0, 3, weight='weight',
                                      method='bellman-ford'),
                     [0, 2, 3])
        # confirm bad method rejection
        assert_raises(ValueError, nx.shortest_path, self.cycle, method='SPAM')
        # confirm absent source rejection
        assert_raises(nx.NodeNotFound, nx.shortest_path, self.cycle, 8) 
Example #15
Source File: test_weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_absent_source_bellman_ford(self):
        # the check is in _bellman_ford; this provides regression testing
        # against later changes to "client" Bellman-Ford functions
        G = nx.path_graph(2)
        for fn in (nx.bellman_ford_predecessor_and_distance,
                   nx.bellman_ford_path,
                   nx.bellman_ford_path_length,
                   nx.single_source_bellman_ford_path,
                   nx.single_source_bellman_ford_path_length,
                   nx.single_source_bellman_ford,):
            assert_raises(nx.NodeNotFound, fn, G, 3, 0) 
Example #16
Source File: test_weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_absent_source(self):
        G = nx.path_graph(2)
        for fn in (nx.multi_source_dijkstra_path,
                   nx.multi_source_dijkstra_path_length,
                   nx.multi_source_dijkstra,):
            assert_raises(nx.NodeNotFound, fn, G, [3], 0) 
Example #17
Source File: selection_multipleDeploys.py    From YAFS with MIT License 5 votes vote down vote up
def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message):
        try:
            bestSpeed = float('inf')
            minPath = []
            bestDES = []
            # print "LEN %i" %len(DES_dst)
            for dev in DES_dst:
                #print "DES :",dev
                node_dst = alloc_DES[dev]
                path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
                speed = 0
                for i in range(len(path) - 1):
                    link = (path[i], path[i + 1])
                    #print " LINK : ",link
                    #print " BYTES :", message.bytes
                    speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW])
                    #print " Spped :" , speed
                    #print sim.topology.G.edges[link][Topology.LINK_BW]

                att_node = sim.topology.get_nodes_att()[path[-1]]


                time_service = message.inst / float(att_node["IPT"])
                # print "Tims serviice %s" %time_service
                speed += time_service  # HW - computation of last node
                #print "SPEED: ",speed
                if  speed < bestSpeed:
                    bestSpeed = speed
                    minPath = path
                    bestDES = dev

            # print "DES %s   PATH %s" %(bestDES,minPath)
            return minPath, bestDES

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
            print "Simulation ends?"
            return [], None 
Example #18
Source File: selection_multipleDeploys.py    From YAFS with MIT License 5 votes vote down vote up
def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message):
        try:
            bestSpeed = float('inf')
            minPath = []
            bestDES = []
            #print len(DES_dst)
            for dev in DES_dst:
                #print "DES :",dev
                node_dst = alloc_DES[dev]
                path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
                speed = 0
                for i in range(len(path) - 1):
                    link = (path[i], path[i + 1])
                   # print "LINK : ",link
                   # print " BYTES :", message.bytes
                    speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW])
                    #print sim.topology.G.edges[link][Topology.LINK_BW]

                att_node = sim.topology.get_nodes_att()[path[-1]]

                time_service = message.inst / float(att_node["IPT"])
                speed += time_service  # HW - computation of last node
                #print "SPEED: ",speed
                if  speed < bestSpeed:
                    bestSpeed = speed
                    minPath = path
                    bestDES = dev

            #print bestDES,minPath
            return minPath, bestDES

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
            # print "Simulation ends?"
            return [], None 
Example #19
Source File: astar.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def astar_path_length(G, source, target, heuristic=None, weight='weight'):
    """Returns the length of the shortest path between source and target using
    the A* ("A-star") algorithm.

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

    source : node
       Starting node for path

    target : node
       Ending node for path

    heuristic : function
       A function to evaluate the estimate of the distance
       from the a node to the target.  The function takes
       two nodes arguments and must return a number.

    Raises
    ------
    NetworkXNoPath
        If no path exists between source and target.

    See Also
    --------
    astar_path

    """
    if source not in G or target not in G:
        msg = 'Either source {} or target {} is not in G'
        raise nx.NodeNotFound(msg.format(source, target))

    path = astar_path(G, source, target, heuristic, weight)
    return sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:])) 
Example #20
Source File: test_weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_absent_source(self):
        # the check is in _dijkstra_multisource, but this will provide
        # regression testing against later changes to any of the "client"
        # Dijkstra or Bellman-Ford functions
        G = nx.path_graph(2)
        for fn in (nx.dijkstra_path,
                   nx.dijkstra_path_length,
                   nx.single_source_dijkstra_path,
                   nx.single_source_dijkstra_path_length,
                   nx.single_source_dijkstra,
                   nx.dijkstra_predecessor_and_distance,):
            assert_raises(nx.NodeNotFound, fn, G, 3, 0) 
Example #21
Source File: selection_multipleDeploys.py    From YAFS with MIT License 5 votes vote down vote up
def compute_most_near(self,node_src,alloc_DES,sim,DES_dst):
        """
        This functions caches the minimun path among client-devices and fog-devices-Module Calculator and it chooses the best calculator process deployed in that node
        """
        #By Placement policy we know that:
        try:
            minLenPath = float('inf')
            minPath = []
            bestDES = []
            for dev in DES_dst:
                node_dst = alloc_DES[dev]
                path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
                if len(path)<minLenPath:
                    minLenPath = len(path)
                    minPath = path
                    bestDES = dev

            return minPath,bestDES
        except nx.NetworkXNoPath as e:
            self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
            print "Simulation ends?. Time:", sim.env.now
            # sim.stop = True ## You can stop all DES process
            return [], None

        except nx.NodeNotFound as e:
            self.logger.warning("Node not found: %s - %s "%(node_src,node_dst))
            print "Simulation ends?. Time:",sim.env.now
            # sim.stop = True ## You can stop all DES process
            return [],None 
Example #22
Source File: decompiler_utils.py    From FIDL with MIT License 4 votes vote down vote up
def all_paths_between(c, start_node=None, end_node=None, co=40):
    """Calculates all paths between ``start_node`` and ``end_node``

    Calculating paths is one of these things that \
    is better done with the paralell index graph (``c.i_cfg``) \
    It haywires when done with complex elements.

    FIXME: the co (cutoff) param is necessary to avoid complexity
    explosion. However, there is a problem if it's reached...

    :param c: a :class:`controlFlowinator` object
    :type c: :class:`controlFlowinator`
    :param start_node: a :class:`controlFlowinator` node
    :type start_node: :class:`cexpr_t`
    :param start_node: a :class:`controlFlowinator` node
    :type start_node: :class:`cexpr_t`
    :param co: the *cutoff* value controls the maximum path length.
    :type co: int, optional
    :return: it **yields** a list of nodes for each path
    :rtype: list
    """

    if not start_node:
        start_index = min(c.i_cfg.nodes)
    else:
        start_index = c.node2index[start_node]

    # Use the node with the highest index
    # as default value
    if not end_node:
        node_indexes = [n.index for n in c.g.nodes()]
        # higher value is usually
        # the last return node
        if node_indexes:
            end_index = max(node_indexes)
        else:
            end_index = start_index
    else:
        end_index = c.node2index[end_node]

    # Find all *simple* paths
    # These paths are lists of citem indexes
    try:
        all_paths_i = nx.all_simple_paths(
            c.i_cfg,
            source=start_index,
            target=end_index,
            cutoff=co)
    except nx.NodeNotFound as e:
        # TODO: this problem is related to
        # the cutoff. Figure out what happens...
        traceback.print_exc()
        all_paths_i = []

    # ------------------------------------------------
    # Translate the indexes to cinsn_t, cexpr_t nodes
    # before yielding back to the caller
    # ------------------------------------------------
    for p_i in all_paths_i:
        p_nodes = [c.index2node[x] for x in p_i]
        yield p_nodes 
Example #23
Source File: WAPathSelectionNPlacement.py    From YAFS with MIT License 4 votes vote down vote up
def compute_Latency(self,sim,node_src,node_dst):
        try:
            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
            totalTimelatency = 0
            for i in range(len(path) - 1):
                link = (path[i], path[i + 1])
                totalTimelatency += sim.topology.G.edges[link][Topology.LINK_PR]
            return totalTimelatency

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            return 9999999


    # def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message):
    #     try:
    #         bestSpeed = float('inf')
    #         minPath = []
    #         bestDES = []
    #         #print len(DES_dst)
    #         for dev in DES_dst:
    #             #print "DES :",dev
    #             node_dst = alloc_DES[dev]
    #             path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
    #             speed = 0
    #             for i in range(len(path) - 1):
    #                 link = (path[i], path[i + 1])
    #                # print "LINK : ",link
    #                # print " BYTES :", message.bytes
    #                 speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW])
    #                 #print sim.topology.G.edges[link][Topology.LINK_BW]
    #
    #             att_node = sim.topology.get_nodes_att()[path[-1]]
    #             #TODO ISAAC
    #             # if att_node["id"]==100:
    #             #     print "\t last cloud"
    #             #     speed += 10000
    #
    #             time_service = message.inst / float(att_node["IPT"])
    #             speed += time_service  # HW - computation of last node
    #             #print "SPEED: ",speed
    #             if  speed < bestSpeed:
    #                 bestSpeed = speed
    #                 minPath = path
    #                 bestDES = dev
    #
    #         #print bestDES,minPath
    #         return minPath, bestDES
    #
    #     except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
    #         self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
    #         # print "Simulation ends?"
    #         return [], None 
Example #24
Source File: MCDAPathSelectionNPlacement.py    From YAFS with MIT License 4 votes vote down vote up
def compute_NodeDESCandidates(self, node_src, alloc_DES, sim, DES_dst):

        try:
            # print len(DES_dst)
            nodes = []
            for dev in DES_dst:
                # print "DES :",dev
                node_dst = alloc_DES[dev]
                try:
                    nodes.append(self.get_the_path(sim.topology.G, node_src,node_dst))

                except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
                    self.logger.warning("No path between two nodes: %s - %s " % (node_src, node_dst))

            return nodes

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            self.logger.warning("No path between from nodes: %s " % (node_src))
            # print "Simulation ends?"
            return []


    # def compute_SAR(self, sim, node_src, node_dst, message):
    #     try:
    #         print "COMPUTING LAT. node_src: %i to node_dst: %i" % (node_src, node_dst)
    #
    #         path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
    #         print "PATH ", path
    #
    #         totalTimelatency = 0
    #         for i in range(len(path) - 1):
    #             link = (path[i], path[i + 1])
    #             print "LINK : ", link
    #             # print " BYTES :", message.bytes
    #             totalTimelatency += sim.topology.G.edges[link][Topology.LINK_PR] + (
    #                 message.bytes / sim.topology.G.edges[link][Topology.LINK_BW])
    #             # print sim.topology.G.edges[link][Topology.LINK_BW]
    #
    #         att_node = sim.topology.get_nodes_att()[path[-1]]
    #         time_service = message.inst / float(att_node["IPT"])
    #         totalTimelatency += time_service  # HW - computation of last node
    #         print totalTimelatency
    #
    #         return totalTimelatency
    #
    #     except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
    #         return 9999999 
Example #25
Source File: MCDAPathSelectionNPlacement.py    From YAFS with MIT License 4 votes vote down vote up
def compute_Latency(self,sim,node_src,node_dst):
        try:
            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
            totalTimelatency = 0
            for i in range(len(path) - 1):
                link = (path[i], path[i + 1])
                totalTimelatency += sim.topology.G.edges[link][Topology.LINK_PR]
            return totalTimelatency

        except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
            return 9999999


    # def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message):
    #     try:
    #         bestSpeed = float('inf')
    #         minPath = []
    #         bestDES = []
    #         #print len(DES_dst)
    #         for dev in DES_dst:
    #             #print "DES :",dev
    #             node_dst = alloc_DES[dev]
    #             path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
    #             speed = 0
    #             for i in range(len(path) - 1):
    #                 link = (path[i], path[i + 1])
    #                # print "LINK : ",link
    #                # print " BYTES :", message.bytes
    #                 speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW])
    #                 #print sim.topology.G.edges[link][Topology.LINK_BW]
    #
    #             att_node = sim.topology.get_nodes_att()[path[-1]]
    #             #TODO ISAAC
    #             # if att_node["id"]==100:
    #             #     print "\t last cloud"
    #             #     speed += 10000
    #
    #             time_service = message.inst / float(att_node["IPT"])
    #             speed += time_service  # HW - computation of last node
    #             #print "SPEED: ",speed
    #             if  speed < bestSpeed:
    #                 bestSpeed = speed
    #                 minPath = path
    #                 bestDES = dev
    #
    #         #print bestDES,minPath
    #         return minPath, bestDES
    #
    #     except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
    #         self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
    #         # print "Simulation ends?"
    #         return [], None 
Example #26
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def single_target_shortest_path(G, target, cutoff=None):
    """Compute shortest path to target from all nodes that reach target.

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

    target : node label
       Target node for path

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

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5, create_using=nx.DiGraph())
    >>> path = nx.single_target_shortest_path(G, 4)
    >>> path[0]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path, single_source_shortest_path
    """
    if target not in G:
        raise nx.NodeNotFound("Target {} not in G".format(source))

    def join(p1, p2):
        return p2 + p1
    # handle undirected graphs
    adj = G.pred if G.is_directed() else G.adj
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {target: 1}     # list of nodes to check at next level
    paths = {target: [target]}  # paths dictionary  (paths to key from source)
    return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join)) 
Example #27
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def bidirectional_shortest_path(G, source, target):
    """Return a list of nodes in a shortest path between source and target.

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

    source : node label
       starting node for path

    target : node label
       ending node for path

    Returns
    -------
    path: list
       List of nodes in a path from source to target.

    Raises
    ------
    NetworkXNoPath
       If no path exists between source and target.

    See Also
    --------
    shortest_path

    Notes
    -----
    This algorithm is used by shortest_path(G, source, target).
    """

    if source not in G or target not in G:
        msg = 'Either source {} or target {} is not in G'
        raise nx.NodeNotFound(msg.format(source, target))

    # call helper to do the real work
    results = _bidirectional_pred_succ(G, source, target)
    pred, succ, w = results

    # build path from pred+w+succ
    path = []
    # from source to w
    while w is not None:
        path.append(w)
        w = pred[w]
    path.reverse()
    # from w to target
    w = succ[path[-1]]
    while w is not None:
        path.append(w)
        w = succ[w]

    return path 
Example #28
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 #29
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 #30
Source File: weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def bellman_ford_path(G, source, target, weight='weight'):
    """Returns the shortest path from source to target in a weighted graph G.

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

    source : node
       Starting node

    target : node
       Ending node

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight

    Returns
    -------
    path : list
       List of nodes in a shortest path.

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    NetworkXNoPath
       If no path exists between source and target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.bellman_ford_path(G, 0, 4))
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    dijkstra_path(), bellman_ford_path_length()
    """
    length, path = single_source_bellman_ford(G, source,
                                              target=target, weight=weight)
    return path