def test_bellman_ford_1(): compare_bellman_ford( bellman_ford( create_graph( ["s", "a", "b", "c", "x", "w", "z", "t"], [ ("s", "a", -1), ("s", "w", 2), ("s", "x", 1), ("a", "b", 1), ("b", "c", 0), ("c", "t", 2), ("w", "z", 3), ("z", "t", -6), ("x", "t", 1), ], track_in=True, ), "s", ), { "a": ["s", "a"], "b": ["s", "a", "b"], "c": ["s", "a", "b", "c"], "x": ["s", "x"], "w": ["s", "w"], "z": ["s", "w", "z"], "t": ["s", "w", "z", "t"], }, )
def test_bellman_ford_2(): compare_bellman_ford( bellman_ford( create_graph( ["s", "a", "b", "c", "x", "w", "z", "t"], [ ("s", "a", -1), ("s", "w", 2), ("s", "x", 1), ("a", "b", 1), ("b", "c", 0), ("c", "t", 2), ("w", "z", 3), ("z", "t", -6), ("x", "t", 1), ("w", "a", -3), ("b", "w", -1), ], track_in=True, ), "s", ), None, ) print("All Bellman Ford Tests Passed!")
def generating_delay_matrix(graph): d = {(i, j): 1000000 for i in list(graph.nodes) for j in list(graph.nodes)} for i in list(graph.nodes): for j in list(graph.nodes): path_length, path_nodes, negative_cycle = bf.bellman_ford(graph, source=i, target=j, weight="delay") d[(i, j)] = path_length return d
def get_optimal_for_state(PMs, state_or_nf, G_request, G_topology, state_name, tmp_mapping): min_host = {"host": "", "cost": 100000000} nf_hosts = [ pm for pm in PMs for nf in list(G_request.adj[state_name]) if nf in PMs[pm]['NFs'] ] best_nodes = [] for pm in PMs: delay_cost = 0 for dest_host in nf_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford( G_topology, source=pm, target=dest_host, weight="delay") delay_cost += path_length if delay_cost < min_host["cost"]: min_host["host"] = pm min_host["cost"] = delay_cost best_nodes = [pm] elif delay_cost == min_host["cost"]: best_nodes.append(pm) if len(best_nodes) > 1: capacity, load, states = get_tmp_mapping_data(best_nodes[0], tmp_mapping) best_load = capacity - load for i in best_nodes: c, l, s = get_tmp_mapping_data(i, tmp_mapping) cur_load = c - l if cur_load > best_load: min_host["host"] = i return min_host["host"], min_host["cost"]
def part1(dig): result = 0 for node in dig.nodes(): if node != 'shiny gold': path_nodes = bellmanford.bellman_ford(dig, node, 'shiny gold')[1] if len(path_nodes) > 0: result += 1 return result
def solve(self): graph = self.createGraph() path_length, path_nodes, negative_cycle = bf.bellman_ford( graph, source=0, target=1, weight="length") print("Is there a negative cycle? {0}".format(negative_cycle)) print("Shortest path length: {0}".format(path_length)) print("Shortest path: {0}".format(path_nodes)) return path_length
def generating_delay_matrix(graph): d = {} for i in list(graph.nodes): for j in list(graph.nodes): path_length, path_nodes, negative_cycle = bf.bellman_ford( graph, source=i, target=j, weight="delay") d = merge_two_dicts(d, {(i, j): path_length}) return d
def _all_nc(G, F, R, weight='weight'): # F and R should be EDGE iterables of G i guess. if not F: z_upper, C = _an_nc(G, R, weight) pi_upper = C if not C: return else: # step 2 G_F_R = G.copy() v = [e[0] for e in F] + [F[-1][1]] G_F_R.remove_nodes_from(v[1:-1]) G_F_R.remove_edges_from(R) G_F_R.remove_edges_from(list(G_F_R.out_edges( v[0]))) # errors if don't cast to list...! G_F_R.remove_edges_from(list(G_F_R.in_edges( v[-1]))) # i think probably an upstream bug. d_lower, pi_lower = bf.bellman_ford(G_F_R, v[-1], v[0], weight) counts = Counter(e[0] for e in pi_lower) c, count = max(counts.items(), key=lambda item: item[1]) if count > 1: G_0_F_R = G_F_R.copy() G_0_F_R.remove_node(c) d_0, _ = bf.bellman_ford_k( G_0_F_R, v[-1], v[0], G_0_F_R.number_of_nodes(), weight) # the tacit assumed - 1 needs to be overridden. G_1_F_R = G_F_R.copy() G_1_F_R.remove_edges_from(list(G_1_F_R.out_edges(c))) G_2_F_R = G_F_R.copy() G_2_F_R.remove_edges_from(list(G_2_F_R.in_edges(c))) d_1 = min( bf.bellman_ford_k(G_1_F_R, v[-1], c, k, weight)[0] + bf.bellman_ford_k(G_2_F_R, c, v[0], G_F_R.number_of_nodes() - 1 - k, weight)[0] for k in range(1, G_F_R.number_of_nodes() - 1)) z_lower = sum(G.edges[u, v][weight] for u, v in F) + min(d_0, d_1) else: z_lower = sum(G.edges[u, v][weight] for u, v in F) + d_lower if z_lower >= 0: return d_upper, pi_upper = bf.dijkstra(G_F_R, v[-1], v[0]) # pi_upper is EDGES z_upper = sum(G.edges[u, v][weight] for u, v in F) + d_upper if z_upper < 0: C = F + pi_upper else: # step 5 for e in G_F_R.out_edges(v[-1]): yield from _all_nc(G, F + [e], R) return yield z_upper, C # step 4 for i, e in enumerate(pi_upper): yield from _all_nc(G, F + pi_upper[:i], R + [e])
def get_cost_of_mapping(state, src_host, PMs, G_request, G_topology): dst_hosts = [ pm for pm in PMs for nf in list(G_request.adj[state]) if nf in PMs[pm]['NFs'] ] delay_cost = 0 for dest_host in dst_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford( G_topology, source=src_host, target=dest_host, weight="delay") delay_cost += path_length return delay_cost
def generating_delay_matrix(self): """ This method generated a delay matrix of the cluster :return: A dictionary as delay matrix """ d = {(i, j): float('inf') for i in self.topology.nodes for j in self.topology.nodes} for i in self.topology.nodes: for j in self.topology.nodes: path_length, path_nodes, negative_cycle = bf.bellman_ford(self.topology, source=i, target=j, weight="delay") d[(i, j)] = path_length return d
def __init__(self, topology, functions, placement_module, distribution): MasterController.topology = topology MasterController.functions = functions MasterController.placement_module = placement_module MasterController.delay_dist = distribution MasterController.min_delay_between_hosts = dict() for h1 in topology.nodes: for h2 in topology.nodes: MasterController.min_delay_between_hosts.update( {(h1, h2): bf.bellman_ford(topology, source=h1, target=h2, weight="delay")[0]})
def do_mapping(G_request, G_topology, PMs, mapping, virtual_element, pairing = {}, writer_count = 0, master = ""): #FIXME: cost should be infinity min_host = {"host": "", "cost": 100000000} max_host = {"host": "", "cost": 0} destinations = [pairing[virtual_element]] if writer_count > 0 and master != "": destinations.append(master) # In case of replicas max_hosts = [] aa_nodes = get_aa_nodes(virtual_element, G_request, mapping, master) tmp_dst_hosts = [get_PM_of_NF(G_topology, i, mapping) for i in destinations] # delete none hosts dst_hosts = [tmp_dst_hosts[i] for i in range(len(tmp_dst_hosts)) if tmp_dst_hosts[i] != None] for pm in PMs: if pm not in aa_nodes: if PMs[pm]['capacity'] >= G_request.nodes[virtual_element]['size']: if dst_hosts != []: delay_cost = 0 for dest_host in dst_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford(G_topology, source=pm, target=dest_host, weight="delay") delay_cost += path_length if delay_cost < min_host["cost"]: min_host["host"] = pm min_host["cost"] = delay_cost else: if max_hosts == []: max_hosts.append({"host":pm, "capacity":PMs[pm]["capacity"]}) else: inserting = False for i in max_hosts: if i["capacity"] < PMs[pm]['capacity']: max_hosts.insert(max_hosts.index(i),{'host':pm,'capacity':PMs[pm]['capacity']}) inserting = True break if not inserting: max_hosts.append({'host': pm, 'capacity': PMs[pm]['capacity']}) if max_hosts != []: mapping[virtual_element] = {"host": max_hosts[0]["host"]} PMs[max_hosts[0]["host"]]['capacity'] = PMs[max_hosts[0]["host"]]['capacity'] - G_request.nodes[virtual_element]['size'] elif min_host["host"] != "": mapping[virtual_element] = {"host": min_host["host"], "cost": min_host["cost"]} PMs[min_host["host"]]['capacity'] = PMs[min_host["host"]]['capacity'] - G_request.nodes[virtual_element]['size'] else: valid_mapping = False print("There is no valid mapping for the given problem by the Greedy Algorythm")
def solve(self): graph = self.createGraph() nrows, ncols = self.distArray.shape path_length, path_nodes, negative_cycle = bf.bellman_ford( graph, source=(0, 0), target=(nrows - 1, ncols - 1), weight="length") path_length += self.distArray[0, 0] print("Is there a negative cycle? {0}".format(negative_cycle)) print("Shortest path length: {0}".format(path_length)) print("Shortest path: {0}".format(path_nodes)) return path_length
def bellmanFord(g, pocetnigrad, ostaliGradovi): start1 = time.time() for el in ostaliGradovi: if el == pocetnigrad: continue path_length, path_nodes, negative_cycle = bf.bellman_ford( g, pocetnigrad, el) print("Postoji li negativni krug {0}".format(negative_cycle)) print("Najkraci put duzina: {0}".format(path_length)) print("Najkraci put: {0}".format(path_nodes)) print("-------------------------------------") end = time.time() print(end - start1)
def generatebellmanford(graph): ### Upgrade code by updating graph for affected node only nested_d = {} nested_p = {} # for base in graph: # print('generatebellmanford: run base = ' + base) # base = 'HKD' # d,p = bellman.bellman_ford(graph,base) d,p = bellmanford.bellman_ford(graph, base) # print('d of ' + base + ' = ') # print(json.dumps(d,indent=4, sort_keys=True)) # print('p of ' + base + ' = ') # print(json.dumps(p,indent=4, sort_keys=True)) nested_d[base] = d nested_p[base] = p return nested_d, nested_p
def list_maximum_likehood_on_embeddings(list_num, nodes): nodes.insert(0, [0]) nodes.append([1]) st.write(nodes) G = nx.DiGraph() dis_df = [] for gid, (lefts, rights) in enumerate(zip(nodes[:-1], nodes[1:])): for lid, left in enumerate(lefts): for rid, right in enumerate(rights): v = distance(left, right) dis_df.append({"from": left, "to": right, "dis": v}) G.add_edge((gid, lid, left), (gid + 1, rid, right), distance=v) # dis_df = pd.DataFrame(dis_df) # dis_df = dis_df[(dis_df["from"] != 0) & (dis_df["to"] != 1)] # st.dataframe(dis_df.sort_values(by="dis"), width=800) length, nodes, negative_cycle = bf.bellman_ford(G, (0, 0, 0), (list_num + 1, 0, 1), weight='distance') return nodes, G, length, negative_cycle
def get_possible_dest_nodes(tmp_mapping, src_host, state, state_size, G_request, G_topology, current_load): possible_nodes = [] PMs = G_topology.nodes nf_hosts = [ pm for pm in PMs for nf in list(G_request.adj[state]) if nf in PMs[pm]['NFs'] ] for pm in PMs: delay_cost = 0 for dest_host in nf_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford( G_topology, source=pm, target=dest_host, weight="delay") delay_cost += path_length # Inserting PM if possible_nodes == []: possible_nodes.append({"node": pm, "cost": delay_cost}) else: insert = False for n in possible_nodes: if delay_cost < n["cost"]: possible_nodes.insert(possible_nodes.index(n), { "node": pm, "cost": delay_cost }) insert = True break if not insert: possible_nodes.append({"node": pm, "cost": delay_cost}) for i in possible_nodes: if i['node'] != src_host: detailed_host = next(a for a in tmp_mapping if a["node"] == i["node"]) if (detailed_host['capacity'] - (detailed_host['load'] + state_size)) > current_load: return i['node'] raise Exception("There is no valid mapping!")
def map_with_no_replicas(G_request, G_topology, mapping, PMs, states, replicas, nfs, actual_state): success_map, mapping = try_to_map_locally(G_request, G_topology, mapping, actual_state) if not success_map: min_host = {"host": "", "cost": 100000000} nf_hosts = [pm for pm in PMs for nf in list(G_request.adj[s]) if nf in PMs[pm]['NFs']] for pm in PMs: if PMs[pm]['capacity'] >= states[actual_state]['size']: delay_cost = 0 for dest_host in nf_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford(G_topology, source=pm, target=dest_host, weight="delay") delay_cost += path_length if delay_cost < min_host["cost"]: min_host["host"] = pm min_host["cost"] = delay_cost if min_host["host"] != "": mapping[s] = {"host": min_host["host"], "cost": min_host["cost"]} PMs[min_host["host"]]['capacity'] = PMs[min_host["host"]]['capacity'] - states[actual_state]['size'] else: valid_mapping = False print("There is no valid mapping for the given problem by the Greedy Algorythm")
""" A shortest path problem on a digraph with 4 nodes in which the source and target nodes are not connected. Expected solution: - Negative cycle? False - Shortest path length = inf - Shortest path = None """ import networkx as nx import bellmanford as bf G = nx.DiGraph() G.add_edge(1, 2, length=1) G.add_edge(3, 4, length=1) length, nodes, negative_cycle = bf.bellman_ford(G, source=1, target=4, weight='length') print("Negative cycle?", negative_cycle) print("Shortest path length =", length) print("Shortest path =", nodes)
import weightedgraph import bellmanford nodenumbers = {'N1':0, 'N2':1, 'N3':2, 'N4':3, 'N5':4, 'N6':5, 'N7':6, 'N8':7} G = weightedgraph.Graph(len(nodenumbers)) for node in nodenumbers: G.set_vertex(nodenumbers[node],node) G.add_edge(nodenumbers['N1'],nodenumbers['N2'],3) G.add_edge(nodenumbers['N1'],nodenumbers['N4'],2) G.add_edge(nodenumbers['N1'],nodenumbers['N3'],3) G.add_edge(nodenumbers['N2'],nodenumbers['N4'],9) G.add_edge(nodenumbers['N2'],nodenumbers['N5'],4) G.add_edge(nodenumbers['N2'],nodenumbers['N7'],2) G.add_edge(nodenumbers['N3'],nodenumbers['N4'],4) G.add_edge(nodenumbers['N3'],nodenumbers['N5'],1) G.add_edge(nodenumbers['N3'],nodenumbers['N7'],6) G.add_edge(nodenumbers['N3'],nodenumbers['N8'],-6) G.add_edge(nodenumbers['N4'],nodenumbers['N6'],1) G.add_edge(nodenumbers['N5'],nodenumbers['N7'],7) G.print_graph() bellmanford.bellman_ford(G,nodenumbers['N1'])
archivo = str(sys.argv[1]) algoritmo = str(sys.argv[2]) nodoInicial = str(sys.argv[3]) nodoDestino = str(sys.argv[4]) if algoritmo == 'dijkstra': grafo = archivo_leer(archivo) print('\nALGORITMO DIJKSTRA:') print(escribir_ruta(nodoInicial, nodoDestino, reconstruir_ruta(nodoDestino, dijkstra.dijkstra(grafo,nodoInicial,nodoDestino)))) print('\n') #print(dijkstra.dijkstra(grafo,nodoInicial,nodoDestino)) elif algoritmo == 'bellmanford': grafo = archivo_leer(archivo) print('\nALGORITMO BELLMAN-FORD:') print(escribir_ruta(nodoInicial, nodoDestino, reconstruir_ruta(nodoDestino, bellmanford.bellman_ford(grafo,nodoInicial)))) print('\n') #print(bellmanford.bellman_ford(grafo,nodoInicial)) elif algoritmo == 'a*': grafo = archivo_leer_h(archivo) print('\nALGORITMO A*:') print(escribir_ruta(nodoInicial, nodoDestino, reconstruir_ruta(nodoDestino, aestrella.a_estrella(grafo,nodoInicial,nodoDestino)))) print('\n') print(aestrella.a_estrella(grafo,nodoInicial,nodoDestino)) else: print('Error en el nombre del algoritmo: {' + algoritmo + '}') except OSError: print("No se puedo abrir el archivo: ", archivo)
def solving_placement_problem_from_file(topology_graph, request_graph, test_num, results_path): if not os.path.isfile("{}/p5_greedy_result_{}.json".format(results_path, test_num)): # Reading networkx file G_topology = read_json_file(topology_graph) G_request = read_json_file(request_graph) PMs = G_topology.nodes set_virtual_nodes = list(G_request.nodes) set_state, set_replica, set_nf = [], [], [] for i in set_virtual_nodes: if "function" in i: set_nf.append(i) elif "state" in i: set_state.append(i) elif "replica" in i: set_replica.append(i) else: raise Exception("Invalid request graph") t1 = datetime.datetime.now() ordered_states = ordering_states(G_request, set_state) mapping = {i: {} for i in ordered_states + set_replica} valid_mapping = True for s in ordered_states: if get_replica_neighbors(s, G_request) == 0: map_with_no_replicas(G_request, G_topology, mapping, PMs, set_state, set_replica, set_nf, s) else: replicas = get_replica_neighbors(s, G_request) functions = get_function_neighbors(s, G_request, set_nf) we_count, writing_edges = get_writing_edge_count(s, G_request, set_nf) if we_count > 1: ve_function_pairing = {replicas[i]:"" for i in range(len(replicas))} for j in range(len(functions)): ve_function_pairing[replicas[j]] = functions[j] else: ve_function_pairing = {i: "" for i in [s] + replicas} unpaired_functions = functions if we_count == 1: writer_function =writing_edges[0][0] ve_function_pairing[s] = writer_function unpaired_functions.remove(writer_function) else: ve_function_pairing[s] = functions[0] unpaired_functions.remove(functions[0]) iter = 0 for ve, function in ve_function_pairing.items(): try: if ve_function_pairing[ve] == "": ve_function_pairing[ve] = unpaired_functions[iter] iter += 1 except: break do_mapping(G_request, G_topology, PMs, mapping, s, ve_function_pairing, we_count) for r in replicas: do_mapping(G_request, G_topology, PMs, mapping, r, ve_function_pairing, we_count, s) t2 = datetime.datetime.now() f = open("optimization_results/p5_greedy_result_{}.json".format(test_num), "a") if valid_mapping: for state, map in mapping.items(): #sum_cost += map["cost"] f.write("State {} -> PM {}, COST: ?\n".format(state, map["host"])) print("x_({},{}) = 1".format(map["host"], state)) # Calculating cost servers = [i for i in PMs if "server" in i] server_permutations = list(itertools.permutations(servers, 2)) x_vars = {(i, u): 0 for i in PMs for u in set_state + set_replica + set_nf} for state, map in mapping.items(): x_vars[map["host"], state] = 1 for i in PMs: if PMs[i]['NFs'] != []: for u in PMs[i]['NFs']: x_vars[i, u] = 1 print("Generating state-function adjacency matrix...") e_r = generating_req_adj(set_state, set_nf + set_replica, G_request) print("Generating delay matrix...") d = generating_delay_matrix(G_topology) index_permutations = list(itertools.permutations((set_state + set_nf + set_replica), 2)) z_vars = {(u, v): 0 for u, v in index_permutations} for u,v in index_permutations: if "function" in u and "state" in v: if e_r[u,v] == 1: z_vars[u,v] = 1 elif "function" in u and "replica" in v: if e_r[u,v] == 1: raise Exception("Wrong Request Graph") elif "function" in u and "function" in v: if e_r[u, v] == 1: raise Exception("Wrong Request Graph") elif "state" in u and "function" in v: if e_r[u, v] == 1: replicas = get_replica_neighbors(u, G_request) if len(replicas) == 0: z_vars[u,v] = 1 else: links = [(u,v)] + [(r,v) for r in replicas] # FIXME: infinity min_cost = 10000000000 min_link = None for i,j in links: source = get_PM_of_NF(G_topology, i, mapping) destination = get_PM_of_NF(G_topology, j, mapping) path_length, path_nodes, negative_cycle = bf.bellman_ford(G_topology, source=source, target=destination, weight="delay") if path_length < min_cost: min_cost = path_length min_link = (i,j) if min_link == (u,v): z_vars[u,v] = 1 elif "state" in u and "replica" in v: if e_r[u, v] == 1: z_vars[u,v] = 1 elif "state" in u and "state" in v: if e_r[u, v] == 1: raise Exception("Wrong Request Graph") elif "replica" in u and "function" in v: if e_r[u, v] == 1: master = next(i for i in set_state if u in G_request.nodes[i]['replicas']) replicas = get_replica_neighbors(master, G_request) links = [(r, v) for r in replicas] + [(master,v)] # FIXME: infinity min_cost = 10000000000 min_link = None for i, j in links: source = get_PM_of_NF(G_topology, i, mapping) destination = get_PM_of_NF(G_topology, j, mapping) path_length, path_nodes, negative_cycle = bf.bellman_ford(G_topology, source=source, target=destination, weight="delay") if path_length < min_cost: min_cost = path_length min_link = (i, j) if min_link == (u, v): z_vars[u, v] = 1 elif "replica" in u and "state" in v: if e_r[u, v] == 1: raise Exception("Wrong Request Graph") elif "replica" in u and "replica" in v: if e_r[u, v] == 1: raise Exception("Wrong Request Graph") sum_cost = 0 print("x_vars[i, u] * \tx_vars[j, v] * \te_r[u, v] * \td[i, j] * \tz_vars[u, v]") for i, j in server_permutations: for u, v in list(itertools.permutations(set_state + set_replica + set_nf, 2)): c = x_vars[i, u] * x_vars[j, v] * e_r[u, v] * d[i, j] * z_vars[u, v] if c > 0: pass #print("i : {}\tj : {}\tu : {}\tv : {}".format(i,j,u,v)) #print("{} * {} * {} * {} * {}".format(x_vars[i, u], x_vars[j, v], e_r[u, v], d[i, j], z_vars[u, v])) #print("----------------------------------------------------") sum_cost += c print("*** RUNNING TIME: {} ***".format(t2-t1)) f.write("*** RUNNING TIME: {} ***\n".format(t2-t1)) print("*** Delay cost: {} ***".format(sum_cost)) f.write("*** Delay cost: {} ***\n".format(sum_cost)) return sum_cost, t2-t1 else: f.write("There is no valid mapping for the given problem by the Greedy Algorythm\n") return 0, t2-t1 else: with open("{}/p5_greedy_result_{}.json".format(results_path, test_num)) as f: lines = f.read().splitlines() cost = int(lines[-1].split(" ")[3]) rt = lines[-2].split(" ")[3] print("*** RUNNING TIME: {} ***".format(rt)) print("*** Delay cost: {} ***".format(cost)) return cost, rt
def solving_placement_problem_from_file(topology_graph, request_graph, test_num): # Reading networkx file G_topology = read_json_file(topology_graph) G_request = read_json_file(request_graph) PMs = G_topology.nodes state_or_nf = G_request.nodes set_state_or_nf = list(G_request.nodes) set_state, set_nf = [], [] for i in set_state_or_nf: if "function" in i: set_nf.append(i) elif "state" in i: set_state.append(i) t1 = datetime.datetime.now() ordered_states = ordering_states(G_request,set_state, set_nf ) mapping = {i : {} for i in ordered_states} valid_mapping = True for s in ordered_states: if s == "state_4": asd = 0 success_map, mapping = try_to_map_locally(G_request, G_topology, mapping, s) if not success_map: min_host = {"host":"", "cost":100000000} nf_hosts = [pm for pm in PMs for nf in list(G_request.adj[s]) if nf in PMs[pm]['NFs']] for pm in PMs: if PMs[pm]['capacity'] >= state_or_nf[s]['size']: delay_cost = 0 for dest_host in nf_hosts: path_length, path_nodes, negative_cycle = bf.bellman_ford(G_topology, source=pm, target=dest_host, weight="delay") delay_cost += path_length if delay_cost < min_host["cost"]: min_host["host"] = pm min_host["cost"] = delay_cost if min_host["host"] != "": mapping[s] = {"host": min_host["host"], "cost": min_host["cost"]} PMs[min_host["host"]]['capacity'] = PMs[min_host["host"]]['capacity'] - state_or_nf[s]['size'] else: valid_mapping = False print("There is no valid mapping for the given problem by the Greedy Algorythm") t2 = datetime.datetime.now() f = open("optimization_results/p3_greedy_result_{}.json".format(test_num), "a") if valid_mapping: sum_cost = 0 for state, map in mapping.iteritems(): sum_cost += map["cost"] #print("State {} -> PM {}, COST: {}".format(state, map["host"], map["cost"])) f.write("State {} -> PM {}, COST: {}\n".format(state, map["host"], map["cost"])) print("*** Delay cost: {} ***".format(sum_cost)) f.write("*** Delay cost: {} ***\n".format(sum_cost)) return sum_cost, t2-t1 else: f.write("There is no valid mapping for the given problem by the Greedy Algorythm\n") return 0, t2-t1
print(next(all_p)) # та же длина, но другой мартшрут ''' # Дейкстра print( nx.dijkstra_path(G, source='Москва', target='Екатеринбург', weight='weight')) # Дейкстра - длина пути print( nx.dijkstra_path_length(G, source='Москва', target='Екатеринбург', weight='weight')) print( nx.bellman_ford_path(G, source='Москва', target='Екатеринбург', weight='weight')) # есть библиотека pip install bellmanford import bellmanford as bf # на выходе - длина пути, сам путь, есть ли отрицательные циклы path_length, path_nodes, negative_cycle = bf.bellman_ford( G, source='Москва', target='Екатеринбург', weight='weight') print(path_length, path_nodes, negative_cycle)