Python networkx.shortest_path() Examples

The following are 30 code examples of networkx.shortest_path(). 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 get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):
        """
        Get the path between a node of the topology and a module deployed in a node. Furthermore it chooses the process deployed in that node.
        """
        node_src = topology_src  # TOPOLOGY SOURCE where the message is generated

        # print "Node (Topo id): %s" %node_src
        # print "Service DST: %s "%message.dst
        DES_dst = alloc_module[app_name][message.dst]
        # print "DES DST: %s" % DES_dst
        minLenPath = float('inf')
        minPath = []
        bestDES = 0
        for des in DES_dst:
            node_dst = sim.alloc_DES[des]
            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
            if len(path) < minLenPath:
                minLenPath = len(path)
                minPath = [path]
                bestDES = [des]

        return minPath, bestDES 
Example #2
Source File: utg.py    From droidbot with MIT License 6 votes vote down vote up
def get_event_path(self, current_state, target_state):
        path_events = []
        try:
            states = nx.shortest_path(G=self.G, source=current_state.state_str, target=target_state.state_str)
            if not isinstance(states, list) or len(states) < 2:
                self.logger.warning("Error getting path from %s to %s" %
                                    (current_state.state_str, target_state.state_str))
            start_state = states[0]
            for state in states[1:]:
                edge = self.G[start_state][state]
                edge_event_strs = list(edge["events"].keys())
                if self.random_input:
                    random.shuffle(edge_event_strs)
                path_events.append(edge["events"][edge_event_strs[0]]["event"])
                start_state = state
        except Exception as e:
            print(e)
            self.logger.warning("Cannot find a path from %s to %s" % (current_state.state_str, target_state.state_str))
        return path_events 
Example #3
Source File: selection.py    From YAFS with MIT License 6 votes vote down vote up
def get_path(self, sim, app_name,message, topology_src, alloc_DES, alloc_module, traffic,from_des):
        paths = []
        dst_idDES = []

        node_src = topology_src #TOPOLOGY SOURCE where the message is generated
        DES_dst = alloc_module[app_name][message.dst]

        #Among all possible path we choose the smallest
        bestPath = []
        bestDES = []
        print (DES_dst)
        for des in DES_dst:
            dst_node = alloc_DES[des]
            # print "DES Node %i " %dst_node

            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
            bestPath = [path]
            bestDES  = [des]
            print (path)


        return bestPath,bestDES 
Example #4
Source File: coupling.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def shortest_undirected_path(self, physical_qubit1, physical_qubit2):
        """Returns the shortest undirected path between physical_qubit1 and physical_qubit2.

        Args:
            physical_qubit1 (int): A physical qubit
            physical_qubit2 (int): Another physical qubit
        Returns:
            List: The shortest undirected path
        Raises:
            CouplingError: When there is no path between physical_qubit1, physical_qubit2.
        """
        try:
            return nx.shortest_path(self.graph.to_undirected(as_view=True), source=physical_qubit1,
                                    target=physical_qubit2)
        except nx.exception.NetworkXNoPath:
            raise CouplingError(
                "Nodes %s and %s are not connected" % (str(physical_qubit1), str(physical_qubit2))) 
Example #5
Source File: selection_multipleDeploys.py    From YAFS with MIT License 6 votes vote down vote up
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):

        node_src = topology_src
        DES_dst = alloc_module[app_name][message.dst]  # returns an array with all DES process serving

        if message.dst not in self.rr.keys():
            self.rr[message.dst] = 0

        # print "GET PATH"
        # print "\tNode _ src (id_topology): %i" % node_src
        # print "\tRequest service: %s " % (message.dst)
        # print "\tProcess serving that service: %s (pos ID: %i)" % (DES_dst, self.rr[message.dst])

        next_DES_dst =DES_dst[self.rr[message.dst]]

        dst_node = alloc_DES[next_DES_dst]
        path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
        bestPath = [path]
        bestDES = [next_DES_dst]
        self.rr[message.dst] = (self.rr[message.dst] + 1) % len(DES_dst)

        return bestPath, bestDES 
Example #6
Source File: selection_multipleDeploys.py    From YAFS with MIT License 6 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:

        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 
Example #7
Source File: hierarchies.py    From ReGraph with MIT License 6 votes vote down vote up
def get_typing(self, source, target):
        """Get a typing dict associated to the edge 'source->target'."""
        if (source, target) in self.edges():
            if self.is_graph(source):
                return self.get_edge(source, target)["mapping"]
            else:
                edge = self.get_edge(source, target)
                return (edge["lhs_mapping"], edge["rhs_mapping"])
        else:
            try:
                path = nx.shortest_path(self._graph, source, target)
            except:
                raise HierarchyError(
                    "No path from '{}' to '{}' in the hierarchy".format(
                        source, target))
            return self.compose_path_typing(path) 
Example #8
Source File: CentricitySelection.py    From YAFS with MIT License 6 votes vote down vote up
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):

        node_src = topology_src

        DES_dst = alloc_module[app_name][message.dst]

        bestPath = []
        bestDES = []
        for des in DES_dst:
            dst_node = alloc_DES[des]

       #     print type(node_src)
        #    print type(dst_node)
         #   print "NODE SRC: %s" %node_src
          #  print "NODE DST: %s" %dst_node

            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=str(dst_node)))
           # print path

            bestPath = [path]
            bestDES  = [des]

        return bestPath,bestDES 
Example #9
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 #10
Source File: network_analysis.py    From ditto with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def furtherest_node_miles(self, *args):
        """
        Returns the maximum eccentricity from the source, in miles.

        .. warning:: Not working....
        """
        if args:
            if len(args) == 1:
                _net = args[0]
                _src = self.source
            elif len(args) == 2:
                _net, _src = args
        else:
            _net = self.G.graph
            _src = self.source
        dist = {}
        _net = _net.copy()
        if not _net.has_node(_src):
            _sp = nx.shortest_path(self.G.graph, _src, list(_net.nodes())[0])
            for n1, n2 in zip(_sp[:-1], _sp[1:]):
                _net.add_edge(n1, n2, length=self.G.graph[n1][n2]["length"])
        for node in _net.nodes():
            dist[node] = nx.shortest_path_length(_net, _src, node, weight="length")
        return np.max(list(dist.values())) * 0.000621371  # Convert length to miles 
Example #11
Source File: layout_unitigs.py    From SALSA with MIT License 6 votes vote down vote up
def get_seed_scaffold():

    g_idx = 1
    seed_scaffolds = {} #this stores initial long scaffolds
    to_merge = set()

    for subg in nx.connected_component_subgraphs(G):
        p = []
        for node in subg.nodes():
            if subg.degree(node) == 1:
                p.append(node)

        #If this is 2 then we have found the path!
        if len(p) == 2:
            path = nx.shortest_path(subg,p[0],p[1])
            seed_scaffolds[g_idx] = path
            g_idx += 1


        #else try to insert these contigs in the long scaffolds generated previously
        else:
            for node in subg.nodes():
                to_merge.add(node.split(':')[0])

    return seed_scaffolds, to_merge 
Example #12
Source File: tree.py    From fragile with MIT License 6 votes vote down vote up
def get_path_node_ids(self, leaf_id: NodeId, root_id: NodeId = None) -> List[NodeId]:
        """
        Get the data of the path between ``leaf_id`` and ``root_id``.

        Args:
            leaf_id: Id that identifies the leaf of the tree. \
                     If ``leaf_id`` is the hash of a walker state ``from_hash`` \
                     needs to be ``True``. Otherwise it refers to a node id of \
                     the leaf node.
            root_id: Node id of the root node of the tree.

        Returns:
            List of the node ids between ``root`` and ``leaf_id``.

        """
        root = root_id if root_id is not None else self.root_id
        nodes = nx.shortest_path(self.data, root, leaf_id)
        return nodes 
Example #13
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 #14
Source File: path_check.py    From bap-tutorial with MIT License 6 votes vote down vote up
def verify(prog, src_name, dst_name):
    src = prog.subs.find(src_name)
    dst = prog.subs.find(dst_name)
    if src is None or dst is None:
        return None

    graphs = GraphsBuilder()
    graphs.run(prog)
    cg = graphs.callgraph

    if nx.has_path(cg, src.id.number, dst.id.number):
        return ('calls', nx.shortest_path(cg, src.id.number, dst.id.number))

    calls = CallsitesCollector(graphs.callgraph, src.id.number, dst.id.number)

    for sub in prog.subs:
        calls.run(sub)
        cfg = graphs.callgraph.nodes[sub.id.number]['cfg']
        for src in calls.srcs:
            for dst in calls.dsts:
                if src != dst and nx.has_path(cfg, src, dst):
                    return ('sites', nx.shortest_path(cfg, src, dst))
        calls.clear()

    return None 
Example #15
Source File: find_best_mapping.py    From Liftoff with GNU General Public License v3.0 6 votes vote down vote up
def find_best_mapping(alignments, query_length,  parent, coords_to_exclude, children_dict, previous_gene_start, copy_tag):
    children = children_dict[parent.id]
    children_coords = liftoff_utils.merge_children_intervals(children)
    node_dict, aln_graph = intialize_graph()
    head_nodes = add_single_alignments(node_dict, aln_graph, alignments, children_coords, parent, coords_to_exclude,
                                       previous_gene_start)
    chain_alignments(head_nodes, node_dict, aln_graph, coords_to_exclude, parent, children_coords)
    add_target_node(aln_graph, node_dict, query_length, children_coords, parent)
    shortest_path = nx.shortest_path(aln_graph, source=0, target=len(node_dict) - 1,
                                     weight=lambda u, v, d: get_weight(u, v, d, aln_graph))
    shortest_path_weight = nx.shortest_path_length(aln_graph, source=0, target=len(node_dict) - 1,
                                                   weight=lambda u, v, d: get_weight(u, v, d, aln_graph))

    shortest_path_nodes = []
    for i in range  (1,len(shortest_path)-1):
        node_name = shortest_path[i]
        shortest_path_nodes.append(node_dict[node_name])
    if len(shortest_path_nodes) == 0:
        return {}, shortest_path_weight, 0,0

    mapped_children, alignment_coverage, seq_id = convert_all_children_coords(shortest_path_nodes, children, parent, copy_tag)
    return mapped_children, shortest_path_weight, alignment_coverage, seq_id 
Example #16
Source File: selection_multipleDeploys.py    From YAFS with MIT License 6 votes vote down vote up
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic,from_des):

        node_src = topology_src
        DES_dst = alloc_module[app_name][message.dst]  # returns an array with all DES process serving

        if message.dst not in self.rr.keys():
            self.rr[message.dst] = 0

        # print "GET PATH"
        # print "\tNode _ src (id_topology): %i" % node_src
        # print "\tRequest service: %s " % (message.dst)
        # print "\tProcess serving that service: %s (pos ID: %i)" % (DES_dst, self.rr[message.dst])

        next_DES_dst =DES_dst[self.rr[message.dst]]

        dst_node = alloc_DES[next_DES_dst]
        path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
        bestPath = [path]
        bestDES = [next_DES_dst]
        self.rr[message.dst] = (self.rr[message.dst] + 1) % len(DES_dst)

        return bestPath, bestDES 
Example #17
Source File: selection_multipleDeploys.py    From YAFS with MIT License 6 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:
            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: network_analysis.py    From ditto with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def list_lines_betweeen_nodes(self, net, node1, node2):
        """
        The function takes a network and two nodes as inputs.
        It returns a list of Line names forming the shortest path between the two nodes.
        """
        # Compute the shortest path as a sequence of node names
        path = nx.shortest_path(net, node1, node2)
        # Transform it in a sequence of edges (n0,n1),(n1,n2),(n2,n3)...
        edge_list = [(a, b) for a, b in zip(path[:-1], path[1:])]
        # Compute the sequence of corresponding lines
        line_list = []
        for edge in edge_list:
            if edge in self.node_line_mapping:
                line_list.append(self.node_line_mapping[edge])
            # If the edge might is reversed
            elif edge[::-1] in self.node_line_mapping:
                line_list.append(self.node_line_mapping[edge[::-1]])
        return line_list 
Example #19
Source File: greedy.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def bring_farthest_pair_together(self, pairs: Sequence[QidPair]):
        """Adds SWAPs to bring the farthest-apart pair of logical qubits
        together."""
        distances = [self.distance(pair) for pair in pairs]
        assert distances
        max_distance = min(distances)
        farthest_pairs = [
            pair for pair, d in zip(pairs, distances) if d == max_distance
        ]
        choice = self.prng.choice(len(farthest_pairs))
        farthest_pair = farthest_pairs[choice]
        edge = self.log_to_phys(*farthest_pair)
        shortest_path = nx.shortest_path(self.device_graph, *edge)
        assert len(shortest_path) - 1 == max_distance
        midpoint = max_distance // 2
        self.swap_along_path(shortest_path[:midpoint])
        self.swap_along_path(shortest_path[midpoint:]) 
Example #20
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def hasConnectedBoundaries(code, loops_graph, Exts):
    if len(loops_graph.edges()) <= 1:
        return False
    for ext1 in loops_graph.nodes():
        for ext2 in loops_graph.nodes():
            if ext1 in Exts and ext2 in Exts and ext1 != ext2:
                if nx.has_path(loops_graph,ext1,ext2):
                    path = nx.shortest_path(loops_graph, ext1, ext2)
                    for node in path:
                        if node not in Exts:
                            return True
    return False 
Example #21
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def connectedBoundaries(loops_graph, Exts):
    for ext1 in loops_graph.nodes():
        for ext2 in loops_graph.nodes():
            if ext1 in Exts and ext2 in Exts and ext1 != ext2:
                if nx.has_path(loops_graph,ext1,ext2):
                    path = nx.shortest_path(loops_graph, ext1, ext2)
                    for node in path:
                        if node not in Exts:
                            return ext1, ext2 
Example #22
Source File: stanford_parser.py    From coling2018_fake-news-challenge with Apache License 2.0 5 votes vote down vote up
def calculate_distance(sentence, token1_index, token2_index):
    graph = create_dependency_graph(sentence)
    path = nx.shortest_path(graph, source=token1_index, target=token2_index)
    '''
    print('path: {0}'.format(path))
    print('shortest path: ' + str(len(path)))

    for token_id in path:
        token = tokens[token_id-1]
        token_text = token['originalText']
        print('Node {0}\ttoken_text: {1}'.format(token_id,token_text))
    '''
    return len(path) 
Example #23
Source File: simple.py    From dqa-net with Apache License 2.0 5 votes vote down vote up
def guess(graph, question, choices):
    MAX = 9999
    SUBMAX = 999
    ques_node = find_node(graph, question)
    dists = []
    for choice in choices:
        choice_node = find_node(graph, choice)
        if ques_node is None and choice_node is None:
            dist = MAX
        elif ques_node is None and choice_node is not None:
            dist = SUBMAX
        elif ques_node is not None and choice_node is None:
            dist = MAX
        else:
            if nx.has_path(graph, ques_node, choice_node):
                pl = len(nx.shortest_path(graph, ques_node, choice_node))
                dist = pl
            else:
                dist = MAX
        dists.append(dist)
    answer, dist = min(enumerate(dists), key=lambda x: x[1])
    max_dist = max(dists)
    if dist == MAX:
        return None
    if dist == max_dist:
        return None
    return answer 
Example #24
Source File: sim_feats.py    From 4lang with MIT License 5 votes vote down vote up
def __init__(self, cfg, section, lexicon):
        self.lexicon = lexicon
        self.batch = cfg.getboolean(section, 'batch')
        self.feats_to_get = cfg.get(section, 'sim_types').split('|')
        self.feats_dict = {
            'links_jaccard' : ['links_jaccard'],
            'entities_jaccard' : ['entities_jaccard'],
            'nodes_jaccard' : ['nodes_jaccard'],
            'links_contain' : ['links_contain'],
            'nodes_contain' : ['nodes_contain'],
            '0-connected' : ['0-connected'],
            'is_antonym' : ['is_antonym'],
            'subgraphs' : ['subgraph_3N'],
            'fullgraph' : ['shortest_path']
        }
        self.no_path_cnt = 0
        self.expand_path = cfg.getboolean(section, 'expand_path')

        self.shortest_path_file_name = cfg.get(section, 'shortest_path_res')
        if not os.path.isfile(self.shortest_path_file_name) or cfg.getboolean(section, 'calc_shortest_path'):
            self.calc_path = True
            shortest_path_dir = os.path.dirname(self.shortest_path_file_name)
            if not os.path.exists(shortest_path_dir):
                os.makedirs(shortest_path_dir)
            self.shortest_path_res = open(self.shortest_path_file_name, 'w')
        else:
            self.calc_path = False


        if 'fullgraph' in self.feats_to_get:
            self.fullgraph_options = FullgraphOptions(cfg)
            self.machinegraph_options = MachineGraphOptions(self.fullgraph_options)
            if not self.expand_path:
                self.full_graph = self.lexicon.get_full_graph(self.fullgraph_options)
                print "NODES count: {0}".format(len(self.full_graph.nodes()))
                print "EDGES count: {0}".format(len(self.full_graph.edges()))
                self.UG = self.full_graph.to_undirected() 
Example #25
Source File: swarm_wave.py    From FractalAI with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_branch(self, leaf_id) -> list:
        """
        Get the observation from the game ended at leaf_id
        :param leaf_id: id of the leaf nodei belonging to the branch that will be recovered.
        :return: Sequence of observations belonging to a given branch of the tree.
        """
        return [self.data.node[n]["obs"] for n in nx.shortest_path(self.data, 0, leaf_id)[1:]] 
Example #26
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def DSP_Path(DualGraph, terminal1, terminal2):
    return nx.shortest_path(DualGraph, terminal1, terminal2) 
Example #27
Source File: mwpm.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def InternalRecovery(code, terminal1, terminal2, type, charge_type):
    measure_chain = nx.shortest_path(code.Dual[type], terminal1, terminal2)
    chain_length = nx.shortest_path_length(code.Dual[type], terminal1, terminal2)
    for link in range(chain_length):
        vertex1 = measure_chain[link]
        vertex2 = measure_chain[link + 1]
        for data_qubit in code.Stabilizers[type][vertex1]['data']:
            if data_qubit in code.Stabilizers[type][vertex2]['data']:
                prior_charge = code.Primal.node[data_qubit]['charge'][charge_type]
                code.Primal.node[data_qubit]['charge'][charge_type] = (prior_charge + 1) % 2

    return code 
Example #28
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 #29
Source File: experiment2.py    From YAFS with MIT License 5 votes vote down vote up
def computingWeights(t,all_nodes_dev,edge_dev,workload_type):
    minPath = {}
    for node in all_nodes_dev:
        for edge in edge_dev:
            if node == edge:
                paths = [[node]]
            else:
                paths = list(nx.shortest_path(t.G, source=node, target=edge))
            minPath[(node, edge)] = paths

    edges = t.G.edges
    minStep = {} #Vertice x Device
    for vertex in edges:
        for dev in edge_dev:
            minvalue = min(len(minPath[(vertex[0],dev)]),len(minPath[(vertex[1],dev)]))
            minStep[(vertex,dev)]=minvalue

    weight_load = range(0,len(workload_type))
    version_printed_weights2 =range(0,len(workload_type))
    for idx,load in enumerate(workload_type):
        weight_load[idx] = {}
        version_printed_weights2[idx] = {}
        for key in minStep:
            if key[1] in workload_type[idx]:
                if key[0] in weight_load[idx]:
                    weight_load[idx][key[0]] += 1.0/minStep[key]
                    version_printed_weights2[idx][key[0]] += minStep[key]
                else:
                    weight_load[idx][key[0]] = 1.0/minStep[key]
                    version_printed_weights2[idx][key[0]] = minStep[key]
    return weight_load 
Example #30
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:
        value = {"model": "d-"}
        topoDST = sim.topology.find_IDs(value)
        minLenPath = float('inf')
        minPath = []
        for dev in topoDST:
            path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dev))
            if len(path)<minLenPath:
                minLenPath = len(path)
                minPath = path

        # print "MIN PATH ",minPath
        last_dest_topo = minPath[len(minPath) - 1]
        if last_dest_topo not in self.running_services.keys():
            run_service = []
            for des in DES_dst:
                if alloc_DES[des] == last_dest_topo:
                    # print "This process are running in this device: ", des  ### Same times that numOfMobilesPerDept by level
                    run_service.append(des)
            self.running_services[last_dest_topo] = run_service

        # print self.running_services[last_dest_topo]

        if last_dest_topo not in self.round_robin_module_calculator:
            self.round_robin_module_calculator[last_dest_topo]=0
        else:
            self.round_robin_module_calculator[last_dest_topo] = (self.round_robin_module_calculator[last_dest_topo] + 1) % self.numOfMobilesPerDept

        nextDESServiceAtThatTopology = self.running_services[last_dest_topo][self.round_robin_module_calculator[last_dest_topo]]
        return minPath,nextDESServiceAtThatTopology